1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "riscv-lower"
44 
45 STATISTIC(NumTailCalls, "Number of tail calls");
46 
47 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
48                                          const RISCVSubtarget &STI)
49     : TargetLowering(TM), Subtarget(STI) {
50 
51   if (Subtarget.isRV32E())
52     report_fatal_error("Codegen not yet implemented for RV32E");
53 
54   RISCVABI::ABI ABI = Subtarget.getTargetABI();
55   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
56 
57   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
58       !Subtarget.hasStdExtF()) {
59     errs() << "Hard-float 'f' ABI can't be used for a target that "
60                 "doesn't support the F instruction set extension (ignoring "
61                           "target-abi)\n";
62     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
63   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
64              !Subtarget.hasStdExtD()) {
65     errs() << "Hard-float 'd' ABI can't be used for a target that "
66               "doesn't support the D instruction set extension (ignoring "
67               "target-abi)\n";
68     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
69   }
70 
71   switch (ABI) {
72   default:
73     report_fatal_error("Don't know how to lower this ABI");
74   case RISCVABI::ABI_ILP32:
75   case RISCVABI::ABI_ILP32F:
76   case RISCVABI::ABI_ILP32D:
77   case RISCVABI::ABI_LP64:
78   case RISCVABI::ABI_LP64F:
79   case RISCVABI::ABI_LP64D:
80     break;
81   }
82 
83   MVT XLenVT = Subtarget.getXLenVT();
84 
85   // Set up the register classes.
86   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
87 
88   if (Subtarget.hasStdExtZfh())
89     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
90   if (Subtarget.hasStdExtF())
91     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
92   if (Subtarget.hasStdExtD())
93     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
94 
95   static const MVT::SimpleValueType BoolVecVTs[] = {
96       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
97       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
98   static const MVT::SimpleValueType IntVecVTs[] = {
99       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
100       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
101       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
102       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
103       MVT::nxv4i64, MVT::nxv8i64};
104   static const MVT::SimpleValueType F16VecVTs[] = {
105       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
106       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
107   static const MVT::SimpleValueType F32VecVTs[] = {
108       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
109   static const MVT::SimpleValueType F64VecVTs[] = {
110       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
111 
112   if (Subtarget.hasStdExtV()) {
113     auto addRegClassForRVV = [this](MVT VT) {
114       unsigned Size = VT.getSizeInBits().getKnownMinValue();
115       assert(Size <= 512 && isPowerOf2_32(Size));
116       const TargetRegisterClass *RC;
117       if (Size <= 64)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 128)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 256)
122         RC = &RISCV::VRM4RegClass;
123       else
124         RC = &RISCV::VRM8RegClass;
125 
126       addRegisterClass(VT, RC);
127     };
128 
129     for (MVT VT : BoolVecVTs)
130       addRegClassForRVV(VT);
131     for (MVT VT : IntVecVTs)
132       addRegClassForRVV(VT);
133 
134     if (Subtarget.hasStdExtZfh())
135       for (MVT VT : F16VecVTs)
136         addRegClassForRVV(VT);
137 
138     if (Subtarget.hasStdExtF())
139       for (MVT VT : F32VecVTs)
140         addRegClassForRVV(VT);
141 
142     if (Subtarget.hasStdExtD())
143       for (MVT VT : F64VecVTs)
144         addRegClassForRVV(VT);
145 
146     if (Subtarget.useRVVForFixedLengthVectors()) {
147       auto addRegClassForFixedVectors = [this](MVT VT) {
148         MVT ContainerVT = getContainerForFixedLengthVector(VT);
149         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
150         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
151         addRegisterClass(VT, TRI.getRegClass(RCID));
152       };
153       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
154         if (useRVVForFixedLengthVectorVT(VT))
155           addRegClassForFixedVectors(VT);
156 
157       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
158         if (useRVVForFixedLengthVectorVT(VT))
159           addRegClassForFixedVectors(VT);
160     }
161   }
162 
163   // Compute derived properties from the register classes.
164   computeRegisterProperties(STI.getRegisterInfo());
165 
166   setStackPointerRegisterToSaveRestore(RISCV::X2);
167 
168   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
169     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
170 
171   // TODO: add all necessary setOperationAction calls.
172   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
173 
174   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
175   setOperationAction(ISD::BR_CC, XLenVT, Expand);
176   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
177   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
178 
179   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
180   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
181 
182   setOperationAction(ISD::VASTART, MVT::Other, Custom);
183   setOperationAction(ISD::VAARG, MVT::Other, Expand);
184   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
185   setOperationAction(ISD::VAEND, MVT::Other, Expand);
186 
187   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
188   if (!Subtarget.hasStdExtZbb()) {
189     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
190     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
191   }
192 
193   if (Subtarget.is64Bit()) {
194     setOperationAction(ISD::ADD, MVT::i32, Custom);
195     setOperationAction(ISD::SUB, MVT::i32, Custom);
196     setOperationAction(ISD::SHL, MVT::i32, Custom);
197     setOperationAction(ISD::SRA, MVT::i32, Custom);
198     setOperationAction(ISD::SRL, MVT::i32, Custom);
199 
200     setOperationAction(ISD::UADDO, MVT::i32, Custom);
201     setOperationAction(ISD::USUBO, MVT::i32, Custom);
202     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
203     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
204   } else {
205     setLibcallName(RTLIB::SHL_I128, nullptr);
206     setLibcallName(RTLIB::SRL_I128, nullptr);
207     setLibcallName(RTLIB::SRA_I128, nullptr);
208     setLibcallName(RTLIB::MUL_I128, nullptr);
209     setLibcallName(RTLIB::MULO_I64, nullptr);
210   }
211 
212   if (!Subtarget.hasStdExtM()) {
213     setOperationAction(ISD::MUL, XLenVT, Expand);
214     setOperationAction(ISD::MULHS, XLenVT, Expand);
215     setOperationAction(ISD::MULHU, XLenVT, Expand);
216     setOperationAction(ISD::SDIV, XLenVT, Expand);
217     setOperationAction(ISD::UDIV, XLenVT, Expand);
218     setOperationAction(ISD::SREM, XLenVT, Expand);
219     setOperationAction(ISD::UREM, XLenVT, Expand);
220   } else {
221     if (Subtarget.is64Bit()) {
222       setOperationAction(ISD::MUL, MVT::i32, Custom);
223       setOperationAction(ISD::MUL, MVT::i128, Custom);
224 
225       setOperationAction(ISD::SDIV, MVT::i8, Custom);
226       setOperationAction(ISD::UDIV, MVT::i8, Custom);
227       setOperationAction(ISD::UREM, MVT::i8, Custom);
228       setOperationAction(ISD::SDIV, MVT::i16, Custom);
229       setOperationAction(ISD::UDIV, MVT::i16, Custom);
230       setOperationAction(ISD::UREM, MVT::i16, Custom);
231       setOperationAction(ISD::SDIV, MVT::i32, Custom);
232       setOperationAction(ISD::UDIV, MVT::i32, Custom);
233       setOperationAction(ISD::UREM, MVT::i32, Custom);
234     } else {
235       setOperationAction(ISD::MUL, MVT::i64, Custom);
236     }
237   }
238 
239   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
240   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
241   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
242   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
243 
244   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
245   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
246   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
247 
248   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
249     if (Subtarget.is64Bit()) {
250       setOperationAction(ISD::ROTL, MVT::i32, Custom);
251       setOperationAction(ISD::ROTR, MVT::i32, Custom);
252     }
253   } else {
254     setOperationAction(ISD::ROTL, XLenVT, Expand);
255     setOperationAction(ISD::ROTR, XLenVT, Expand);
256   }
257 
258   if (Subtarget.hasStdExtZbp()) {
259     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
260     // more combining.
261     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
262     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
263     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
264     // BSWAP i8 doesn't exist.
265     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
266     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
267 
268     if (Subtarget.is64Bit()) {
269       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
270       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
271     }
272   } else {
273     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
274     // pattern match it directly in isel.
275     setOperationAction(ISD::BSWAP, XLenVT,
276                        Subtarget.hasStdExtZbb() ? Legal : Expand);
277   }
278 
279   if (Subtarget.hasStdExtZbb()) {
280     setOperationAction(ISD::SMIN, XLenVT, Legal);
281     setOperationAction(ISD::SMAX, XLenVT, Legal);
282     setOperationAction(ISD::UMIN, XLenVT, Legal);
283     setOperationAction(ISD::UMAX, XLenVT, Legal);
284 
285     if (Subtarget.is64Bit()) {
286       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
287       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
288       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
289       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
290     }
291   } else {
292     setOperationAction(ISD::CTTZ, XLenVT, Expand);
293     setOperationAction(ISD::CTLZ, XLenVT, Expand);
294     setOperationAction(ISD::CTPOP, XLenVT, Expand);
295   }
296 
297   if (Subtarget.hasStdExtZbt()) {
298     setOperationAction(ISD::FSHL, XLenVT, Custom);
299     setOperationAction(ISD::FSHR, XLenVT, Custom);
300     setOperationAction(ISD::SELECT, XLenVT, Legal);
301 
302     if (Subtarget.is64Bit()) {
303       setOperationAction(ISD::FSHL, MVT::i32, Custom);
304       setOperationAction(ISD::FSHR, MVT::i32, Custom);
305     }
306   } else {
307     setOperationAction(ISD::SELECT, XLenVT, Custom);
308   }
309 
310   static const ISD::CondCode FPCCToExpand[] = {
311       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
312       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
313       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
314 
315   static const ISD::NodeType FPOpToExpand[] = {
316       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
317       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
318 
319   if (Subtarget.hasStdExtZfh())
320     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
321 
322   if (Subtarget.hasStdExtZfh()) {
323     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
324     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
325     setOperationAction(ISD::LRINT, MVT::f16, Legal);
326     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
327     setOperationAction(ISD::LROUND, MVT::f16, Legal);
328     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
329     for (auto CC : FPCCToExpand)
330       setCondCodeAction(CC, MVT::f16, Expand);
331     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
332     setOperationAction(ISD::SELECT, MVT::f16, Custom);
333     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
334     for (auto Op : FPOpToExpand)
335       setOperationAction(Op, MVT::f16, Expand);
336   }
337 
338   if (Subtarget.hasStdExtF()) {
339     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
340     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
341     setOperationAction(ISD::LRINT, MVT::f32, Legal);
342     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
343     setOperationAction(ISD::LROUND, MVT::f32, Legal);
344     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
345     for (auto CC : FPCCToExpand)
346       setCondCodeAction(CC, MVT::f32, Expand);
347     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
348     setOperationAction(ISD::SELECT, MVT::f32, Custom);
349     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
350     for (auto Op : FPOpToExpand)
351       setOperationAction(Op, MVT::f32, Expand);
352     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
353     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
354   }
355 
356   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
357     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
358 
359   if (Subtarget.hasStdExtD()) {
360     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
361     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
362     setOperationAction(ISD::LRINT, MVT::f64, Legal);
363     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
364     setOperationAction(ISD::LROUND, MVT::f64, Legal);
365     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
366     for (auto CC : FPCCToExpand)
367       setCondCodeAction(CC, MVT::f64, Expand);
368     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
369     setOperationAction(ISD::SELECT, MVT::f64, Custom);
370     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
373     for (auto Op : FPOpToExpand)
374       setOperationAction(Op, MVT::f64, Expand);
375     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
376     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377   }
378 
379   if (Subtarget.is64Bit()) {
380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
383     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
384   }
385 
386   if (Subtarget.hasStdExtF()) {
387     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
388     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
389 
390     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
391     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
392   }
393 
394   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
395   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
396   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
397   setOperationAction(ISD::JumpTable, XLenVT, Custom);
398 
399   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction(ISD::TRAP, MVT::Other, Legal);
407   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
408   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
409   if (Subtarget.is64Bit())
410     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
411 
412   if (Subtarget.hasStdExtA()) {
413     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
414     setMinCmpXchgSizeInBits(32);
415   } else {
416     setMaxAtomicSizeInBitsSupported(0);
417   }
418 
419   setBooleanContents(ZeroOrOneBooleanContent);
420 
421   if (Subtarget.hasStdExtV()) {
422     setBooleanVectorContents(ZeroOrOneBooleanContent);
423 
424     setOperationAction(ISD::VSCALE, XLenVT, Custom);
425 
426     // RVV intrinsics may have illegal operands.
427     // We also need to custom legalize vmv.x.s.
428     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
429     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
430     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
431     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
432     if (Subtarget.is64Bit()) {
433       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
434     } else {
435       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
436       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
437     }
438 
439     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
440     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
441 
442     static const unsigned IntegerVPOps[] = {
443         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
444         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
445         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
446         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
447         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
448         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
449         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN};
450 
451     static const unsigned FloatingPointVPOps[] = {
452         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
453         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
454         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX};
455 
456     if (!Subtarget.is64Bit()) {
457       // We must custom-lower certain vXi64 operations on RV32 due to the vector
458       // element type being illegal.
459       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
460       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
461 
462       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
463       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
464       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
465       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
466       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
467       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
468       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
469       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
470 
471       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
472       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
473       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
474       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
475       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
476       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
477       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
478       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
479     }
480 
481     for (MVT VT : BoolVecVTs) {
482       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
483 
484       // Mask VTs are custom-expanded into a series of standard nodes
485       setOperationAction(ISD::TRUNCATE, VT, Custom);
486       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
487       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
488       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
489 
490       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
491       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
492 
493       setOperationAction(ISD::SELECT, VT, Custom);
494       setOperationAction(ISD::SELECT_CC, VT, Expand);
495       setOperationAction(ISD::VSELECT, VT, Expand);
496 
497       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
498       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
499       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
500 
501       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
502       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
503       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
504 
505       // RVV has native int->float & float->int conversions where the
506       // element type sizes are within one power-of-two of each other. Any
507       // wider distances between type sizes have to be lowered as sequences
508       // which progressively narrow the gap in stages.
509       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
510       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
511       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
512       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
513 
514       // Expand all extending loads to types larger than this, and truncating
515       // stores from types larger than this.
516       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
517         setTruncStoreAction(OtherVT, VT, Expand);
518         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
519         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
520         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
521       }
522     }
523 
524     for (MVT VT : IntVecVTs) {
525       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
526       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
527 
528       setOperationAction(ISD::SMIN, VT, Legal);
529       setOperationAction(ISD::SMAX, VT, Legal);
530       setOperationAction(ISD::UMIN, VT, Legal);
531       setOperationAction(ISD::UMAX, VT, Legal);
532 
533       setOperationAction(ISD::ROTL, VT, Expand);
534       setOperationAction(ISD::ROTR, VT, Expand);
535 
536       setOperationAction(ISD::CTTZ, VT, Expand);
537       setOperationAction(ISD::CTLZ, VT, Expand);
538       setOperationAction(ISD::CTPOP, VT, Expand);
539 
540       // Custom-lower extensions and truncations from/to mask types.
541       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
542       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
543       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
544 
545       // RVV has native int->float & float->int conversions where the
546       // element type sizes are within one power-of-two of each other. Any
547       // wider distances between type sizes have to be lowered as sequences
548       // which progressively narrow the gap in stages.
549       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
550       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
551       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
552       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
553 
554       setOperationAction(ISD::SADDSAT, VT, Legal);
555       setOperationAction(ISD::UADDSAT, VT, Legal);
556       setOperationAction(ISD::SSUBSAT, VT, Legal);
557       setOperationAction(ISD::USUBSAT, VT, Legal);
558 
559       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
560       // nodes which truncate by one power of two at a time.
561       setOperationAction(ISD::TRUNCATE, VT, Custom);
562 
563       // Custom-lower insert/extract operations to simplify patterns.
564       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
565       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
566 
567       // Custom-lower reduction operations to set up the corresponding custom
568       // nodes' operands.
569       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
570       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
571       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
572       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
573       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
574       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
575       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
576       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
577 
578       for (unsigned VPOpc : IntegerVPOps)
579         setOperationAction(VPOpc, VT, Custom);
580 
581       setOperationAction(ISD::LOAD, VT, Custom);
582       setOperationAction(ISD::STORE, VT, Custom);
583 
584       setOperationAction(ISD::MLOAD, VT, Custom);
585       setOperationAction(ISD::MSTORE, VT, Custom);
586       setOperationAction(ISD::MGATHER, VT, Custom);
587       setOperationAction(ISD::MSCATTER, VT, Custom);
588 
589       setOperationAction(ISD::VP_LOAD, VT, Custom);
590       setOperationAction(ISD::VP_STORE, VT, Custom);
591       setOperationAction(ISD::VP_GATHER, VT, Custom);
592       setOperationAction(ISD::VP_SCATTER, VT, Custom);
593 
594       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
595       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
596       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
597 
598       setOperationAction(ISD::SELECT, VT, Custom);
599       setOperationAction(ISD::SELECT_CC, VT, Expand);
600 
601       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
602       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
603 
604       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
605         setTruncStoreAction(VT, OtherVT, Expand);
606         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
607         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
608         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
609       }
610     }
611 
612     // Expand various CCs to best match the RVV ISA, which natively supports UNE
613     // but no other unordered comparisons, and supports all ordered comparisons
614     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
615     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
616     // and we pattern-match those back to the "original", swapping operands once
617     // more. This way we catch both operations and both "vf" and "fv" forms with
618     // fewer patterns.
619     static const ISD::CondCode VFPCCToExpand[] = {
620         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
621         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
622         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
623     };
624 
625     // Sets common operation actions on RVV floating-point vector types.
626     const auto SetCommonVFPActions = [&](MVT VT) {
627       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
628       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
629       // sizes are within one power-of-two of each other. Therefore conversions
630       // between vXf16 and vXf64 must be lowered as sequences which convert via
631       // vXf32.
632       setOperationAction(ISD::FP_ROUND, VT, Custom);
633       setOperationAction(ISD::FP_EXTEND, VT, Custom);
634       // Custom-lower insert/extract operations to simplify patterns.
635       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
636       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
637       // Expand various condition codes (explained above).
638       for (auto CC : VFPCCToExpand)
639         setCondCodeAction(CC, VT, Expand);
640 
641       setOperationAction(ISD::FMINNUM, VT, Legal);
642       setOperationAction(ISD::FMAXNUM, VT, Legal);
643 
644       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
645       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
646       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
647       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
648 
649       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
650 
651       setOperationAction(ISD::LOAD, VT, Custom);
652       setOperationAction(ISD::STORE, VT, Custom);
653 
654       setOperationAction(ISD::MLOAD, VT, Custom);
655       setOperationAction(ISD::MSTORE, VT, Custom);
656       setOperationAction(ISD::MGATHER, VT, Custom);
657       setOperationAction(ISD::MSCATTER, VT, Custom);
658 
659       setOperationAction(ISD::VP_LOAD, VT, Custom);
660       setOperationAction(ISD::VP_STORE, VT, Custom);
661       setOperationAction(ISD::VP_GATHER, VT, Custom);
662       setOperationAction(ISD::VP_SCATTER, VT, Custom);
663 
664       setOperationAction(ISD::SELECT, VT, Custom);
665       setOperationAction(ISD::SELECT_CC, VT, Expand);
666 
667       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
668       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
669       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
670 
671       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
672 
673       for (unsigned VPOpc : FloatingPointVPOps)
674         setOperationAction(VPOpc, VT, Custom);
675     };
676 
677     // Sets common extload/truncstore actions on RVV floating-point vector
678     // types.
679     const auto SetCommonVFPExtLoadTruncStoreActions =
680         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
681           for (auto SmallVT : SmallerVTs) {
682             setTruncStoreAction(VT, SmallVT, Expand);
683             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
684           }
685         };
686 
687     if (Subtarget.hasStdExtZfh())
688       for (MVT VT : F16VecVTs)
689         SetCommonVFPActions(VT);
690 
691     for (MVT VT : F32VecVTs) {
692       if (Subtarget.hasStdExtF())
693         SetCommonVFPActions(VT);
694       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
695     }
696 
697     for (MVT VT : F64VecVTs) {
698       if (Subtarget.hasStdExtD())
699         SetCommonVFPActions(VT);
700       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
701       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
702     }
703 
704     if (Subtarget.useRVVForFixedLengthVectors()) {
705       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
706         if (!useRVVForFixedLengthVectorVT(VT))
707           continue;
708 
709         // By default everything must be expanded.
710         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
711           setOperationAction(Op, VT, Expand);
712         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
713           setTruncStoreAction(VT, OtherVT, Expand);
714           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
715           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
716           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
717         }
718 
719         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
720         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
721         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
722 
723         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
724         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
725 
726         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
727         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
728 
729         setOperationAction(ISD::LOAD, VT, Custom);
730         setOperationAction(ISD::STORE, VT, Custom);
731 
732         setOperationAction(ISD::SETCC, VT, Custom);
733 
734         setOperationAction(ISD::SELECT, VT, Custom);
735 
736         setOperationAction(ISD::TRUNCATE, VT, Custom);
737 
738         setOperationAction(ISD::BITCAST, VT, Custom);
739 
740         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
741         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
742         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
743 
744         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
745         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
746         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
747 
748         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
749         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
750         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
751         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
752 
753         // Operations below are different for between masks and other vectors.
754         if (VT.getVectorElementType() == MVT::i1) {
755           setOperationAction(ISD::AND, VT, Custom);
756           setOperationAction(ISD::OR, VT, Custom);
757           setOperationAction(ISD::XOR, VT, Custom);
758           continue;
759         }
760 
761         // Use SPLAT_VECTOR to prevent type legalization from destroying the
762         // splats when type legalizing i64 scalar on RV32.
763         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
764         // improvements first.
765         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
766           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
767           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
768         }
769 
770         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
771         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
772 
773         setOperationAction(ISD::MLOAD, VT, Custom);
774         setOperationAction(ISD::MSTORE, VT, Custom);
775         setOperationAction(ISD::MGATHER, VT, Custom);
776         setOperationAction(ISD::MSCATTER, VT, Custom);
777 
778         setOperationAction(ISD::VP_LOAD, VT, Custom);
779         setOperationAction(ISD::VP_STORE, VT, Custom);
780         setOperationAction(ISD::VP_GATHER, VT, Custom);
781         setOperationAction(ISD::VP_SCATTER, VT, Custom);
782 
783         setOperationAction(ISD::ADD, VT, Custom);
784         setOperationAction(ISD::MUL, VT, Custom);
785         setOperationAction(ISD::SUB, VT, Custom);
786         setOperationAction(ISD::AND, VT, Custom);
787         setOperationAction(ISD::OR, VT, Custom);
788         setOperationAction(ISD::XOR, VT, Custom);
789         setOperationAction(ISD::SDIV, VT, Custom);
790         setOperationAction(ISD::SREM, VT, Custom);
791         setOperationAction(ISD::UDIV, VT, Custom);
792         setOperationAction(ISD::UREM, VT, Custom);
793         setOperationAction(ISD::SHL, VT, Custom);
794         setOperationAction(ISD::SRA, VT, Custom);
795         setOperationAction(ISD::SRL, VT, Custom);
796 
797         setOperationAction(ISD::SMIN, VT, Custom);
798         setOperationAction(ISD::SMAX, VT, Custom);
799         setOperationAction(ISD::UMIN, VT, Custom);
800         setOperationAction(ISD::UMAX, VT, Custom);
801         setOperationAction(ISD::ABS,  VT, Custom);
802 
803         setOperationAction(ISD::MULHS, VT, Custom);
804         setOperationAction(ISD::MULHU, VT, Custom);
805 
806         setOperationAction(ISD::SADDSAT, VT, Custom);
807         setOperationAction(ISD::UADDSAT, VT, Custom);
808         setOperationAction(ISD::SSUBSAT, VT, Custom);
809         setOperationAction(ISD::USUBSAT, VT, Custom);
810 
811         setOperationAction(ISD::VSELECT, VT, Custom);
812         setOperationAction(ISD::SELECT_CC, VT, Expand);
813 
814         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
815         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
816         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
817 
818         // Custom-lower reduction operations to set up the corresponding custom
819         // nodes' operands.
820         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
821         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
822         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
823         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
824         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
825 
826         for (unsigned VPOpc : IntegerVPOps)
827           setOperationAction(VPOpc, VT, Custom);
828       }
829 
830       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
831         if (!useRVVForFixedLengthVectorVT(VT))
832           continue;
833 
834         // By default everything must be expanded.
835         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
836           setOperationAction(Op, VT, Expand);
837         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
838           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
839           setTruncStoreAction(VT, OtherVT, Expand);
840         }
841 
842         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
843         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
844         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
845 
846         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
847         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
848         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
849         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
850         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
851 
852         setOperationAction(ISD::LOAD, VT, Custom);
853         setOperationAction(ISD::STORE, VT, Custom);
854         setOperationAction(ISD::MLOAD, VT, Custom);
855         setOperationAction(ISD::MSTORE, VT, Custom);
856         setOperationAction(ISD::MGATHER, VT, Custom);
857         setOperationAction(ISD::MSCATTER, VT, Custom);
858 
859         setOperationAction(ISD::VP_LOAD, VT, Custom);
860         setOperationAction(ISD::VP_STORE, VT, Custom);
861         setOperationAction(ISD::VP_GATHER, VT, Custom);
862         setOperationAction(ISD::VP_SCATTER, VT, Custom);
863 
864         setOperationAction(ISD::FADD, VT, Custom);
865         setOperationAction(ISD::FSUB, VT, Custom);
866         setOperationAction(ISD::FMUL, VT, Custom);
867         setOperationAction(ISD::FDIV, VT, Custom);
868         setOperationAction(ISD::FNEG, VT, Custom);
869         setOperationAction(ISD::FABS, VT, Custom);
870         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
871         setOperationAction(ISD::FSQRT, VT, Custom);
872         setOperationAction(ISD::FMA, VT, Custom);
873         setOperationAction(ISD::FMINNUM, VT, Custom);
874         setOperationAction(ISD::FMAXNUM, VT, Custom);
875 
876         setOperationAction(ISD::FP_ROUND, VT, Custom);
877         setOperationAction(ISD::FP_EXTEND, VT, Custom);
878 
879         for (auto CC : VFPCCToExpand)
880           setCondCodeAction(CC, VT, Expand);
881 
882         setOperationAction(ISD::VSELECT, VT, Custom);
883         setOperationAction(ISD::SELECT, VT, Custom);
884         setOperationAction(ISD::SELECT_CC, VT, Expand);
885 
886         setOperationAction(ISD::BITCAST, VT, Custom);
887 
888         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
889         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
890         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
891         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
892 
893         for (unsigned VPOpc : FloatingPointVPOps)
894           setOperationAction(VPOpc, VT, Custom);
895       }
896 
897       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
898       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
899       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
900       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
901       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
902       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
903       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
904       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
905     }
906   }
907 
908   // Function alignments.
909   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
910   setMinFunctionAlignment(FunctionAlignment);
911   setPrefFunctionAlignment(FunctionAlignment);
912 
913   setMinimumJumpTableEntries(5);
914 
915   // Jumps are expensive, compared to logic
916   setJumpIsExpensive();
917 
918   // We can use any register for comparisons
919   setHasMultipleConditionRegisters();
920 
921   setTargetDAGCombine(ISD::ADD);
922   setTargetDAGCombine(ISD::SUB);
923   setTargetDAGCombine(ISD::AND);
924   setTargetDAGCombine(ISD::OR);
925   setTargetDAGCombine(ISD::XOR);
926   setTargetDAGCombine(ISD::ANY_EXTEND);
927   setTargetDAGCombine(ISD::ZERO_EXTEND);
928   if (Subtarget.hasStdExtV()) {
929     setTargetDAGCombine(ISD::FCOPYSIGN);
930     setTargetDAGCombine(ISD::MGATHER);
931     setTargetDAGCombine(ISD::MSCATTER);
932     setTargetDAGCombine(ISD::VP_GATHER);
933     setTargetDAGCombine(ISD::VP_SCATTER);
934     setTargetDAGCombine(ISD::SRA);
935     setTargetDAGCombine(ISD::SRL);
936     setTargetDAGCombine(ISD::SHL);
937     setTargetDAGCombine(ISD::STORE);
938   }
939 }
940 
941 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
942                                             LLVMContext &Context,
943                                             EVT VT) const {
944   if (!VT.isVector())
945     return getPointerTy(DL);
946   if (Subtarget.hasStdExtV() &&
947       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
948     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
949   return VT.changeVectorElementTypeToInteger();
950 }
951 
952 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
953   return Subtarget.getXLenVT();
954 }
955 
956 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
957                                              const CallInst &I,
958                                              MachineFunction &MF,
959                                              unsigned Intrinsic) const {
960   auto &DL = I.getModule()->getDataLayout();
961   switch (Intrinsic) {
962   default:
963     return false;
964   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
965   case Intrinsic::riscv_masked_atomicrmw_add_i32:
966   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
967   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
968   case Intrinsic::riscv_masked_atomicrmw_max_i32:
969   case Intrinsic::riscv_masked_atomicrmw_min_i32:
970   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
971   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
972   case Intrinsic::riscv_masked_cmpxchg_i32: {
973     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
974     Info.opc = ISD::INTRINSIC_W_CHAIN;
975     Info.memVT = MVT::getVT(PtrTy->getElementType());
976     Info.ptrVal = I.getArgOperand(0);
977     Info.offset = 0;
978     Info.align = Align(4);
979     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
980                  MachineMemOperand::MOVolatile;
981     return true;
982   }
983   case Intrinsic::riscv_masked_strided_load:
984     Info.opc = ISD::INTRINSIC_W_CHAIN;
985     Info.ptrVal = I.getArgOperand(1);
986     Info.memVT = getValueType(DL, I.getType()->getScalarType());
987     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
988     Info.size = MemoryLocation::UnknownSize;
989     Info.flags |= MachineMemOperand::MOLoad;
990     return true;
991   case Intrinsic::riscv_masked_strided_store:
992     Info.opc = ISD::INTRINSIC_VOID;
993     Info.ptrVal = I.getArgOperand(1);
994     Info.memVT =
995         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
996     Info.align = Align(
997         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
998         8);
999     Info.size = MemoryLocation::UnknownSize;
1000     Info.flags |= MachineMemOperand::MOStore;
1001     return true;
1002   }
1003 }
1004 
1005 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1006                                                 const AddrMode &AM, Type *Ty,
1007                                                 unsigned AS,
1008                                                 Instruction *I) const {
1009   // No global is ever allowed as a base.
1010   if (AM.BaseGV)
1011     return false;
1012 
1013   // Require a 12-bit signed offset.
1014   if (!isInt<12>(AM.BaseOffs))
1015     return false;
1016 
1017   switch (AM.Scale) {
1018   case 0: // "r+i" or just "i", depending on HasBaseReg.
1019     break;
1020   case 1:
1021     if (!AM.HasBaseReg) // allow "r+i".
1022       break;
1023     return false; // disallow "r+r" or "r+r+i".
1024   default:
1025     return false;
1026   }
1027 
1028   return true;
1029 }
1030 
1031 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1032   return isInt<12>(Imm);
1033 }
1034 
1035 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1036   return isInt<12>(Imm);
1037 }
1038 
1039 // On RV32, 64-bit integers are split into their high and low parts and held
1040 // in two different registers, so the trunc is free since the low register can
1041 // just be used.
1042 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1043   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1044     return false;
1045   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1046   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1047   return (SrcBits == 64 && DestBits == 32);
1048 }
1049 
1050 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1051   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1052       !SrcVT.isInteger() || !DstVT.isInteger())
1053     return false;
1054   unsigned SrcBits = SrcVT.getSizeInBits();
1055   unsigned DestBits = DstVT.getSizeInBits();
1056   return (SrcBits == 64 && DestBits == 32);
1057 }
1058 
1059 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1060   // Zexts are free if they can be combined with a load.
1061   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1062     EVT MemVT = LD->getMemoryVT();
1063     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1064          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1065         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1066          LD->getExtensionType() == ISD::ZEXTLOAD))
1067       return true;
1068   }
1069 
1070   return TargetLowering::isZExtFree(Val, VT2);
1071 }
1072 
1073 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1074   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1075 }
1076 
1077 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1078   return Subtarget.hasStdExtZbb();
1079 }
1080 
1081 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1082   return Subtarget.hasStdExtZbb();
1083 }
1084 
1085 /// Check if sinking \p I's operands to I's basic block is profitable, because
1086 /// the operands can be folded into a target instruction, e.g.
1087 /// splats of scalars can fold into vector instructions.
1088 bool RISCVTargetLowering::shouldSinkOperands(
1089     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1090   using namespace llvm::PatternMatch;
1091 
1092   if (!I->getType()->isVectorTy() || !Subtarget.hasStdExtV())
1093     return false;
1094 
1095   auto IsSinker = [&](Instruction *I, int Operand) {
1096     switch (I->getOpcode()) {
1097     case Instruction::Add:
1098     case Instruction::Sub:
1099     case Instruction::Mul:
1100     case Instruction::And:
1101     case Instruction::Or:
1102     case Instruction::Xor:
1103     case Instruction::FAdd:
1104     case Instruction::FSub:
1105     case Instruction::FMul:
1106     case Instruction::FDiv:
1107     case Instruction::ICmp:
1108     case Instruction::FCmp:
1109       return true;
1110     case Instruction::Shl:
1111     case Instruction::LShr:
1112     case Instruction::AShr:
1113       return Operand == 1;
1114     case Instruction::Call:
1115       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1116         switch (II->getIntrinsicID()) {
1117         case Intrinsic::fma:
1118           return Operand == 0 || Operand == 1;
1119         default:
1120           return false;
1121         }
1122       }
1123       return false;
1124     default:
1125       return false;
1126     }
1127   };
1128 
1129   for (auto OpIdx : enumerate(I->operands())) {
1130     if (!IsSinker(I, OpIdx.index()))
1131       continue;
1132 
1133     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1134     // Make sure we are not already sinking this operand
1135     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1136       continue;
1137 
1138     // We are looking for a splat that can be sunk.
1139     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1140                              m_Undef(), m_ZeroMask())))
1141       continue;
1142 
1143     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1144     // and vector registers
1145     for (Use &U : Op->uses()) {
1146       Instruction *Insn = cast<Instruction>(U.getUser());
1147       if (!IsSinker(Insn, U.getOperandNo()))
1148         return false;
1149     }
1150 
1151     Ops.push_back(&Op->getOperandUse(0));
1152     Ops.push_back(&OpIdx.value());
1153   }
1154   return true;
1155 }
1156 
1157 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1158                                        bool ForCodeSize) const {
1159   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1160     return false;
1161   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1162     return false;
1163   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1164     return false;
1165   if (Imm.isNegZero())
1166     return false;
1167   return Imm.isZero();
1168 }
1169 
1170 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1171   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1172          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1173          (VT == MVT::f64 && Subtarget.hasStdExtD());
1174 }
1175 
1176 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1177                                                       CallingConv::ID CC,
1178                                                       EVT VT) const {
1179   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1180   // end up using a GPR but that will be decided based on ABI.
1181   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1182     return MVT::f32;
1183 
1184   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1185 }
1186 
1187 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1188                                                            CallingConv::ID CC,
1189                                                            EVT VT) const {
1190   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1191   // end up using a GPR but that will be decided based on ABI.
1192   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1193     return 1;
1194 
1195   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1196 }
1197 
1198 // Changes the condition code and swaps operands if necessary, so the SetCC
1199 // operation matches one of the comparisons supported directly by branches
1200 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1201 // with 1/-1.
1202 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1203                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1204   // Convert X > -1 to X >= 0.
1205   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1206     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1207     CC = ISD::SETGE;
1208     return;
1209   }
1210   // Convert X < 1 to 0 >= X.
1211   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1212     RHS = LHS;
1213     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1214     CC = ISD::SETGE;
1215     return;
1216   }
1217 
1218   switch (CC) {
1219   default:
1220     break;
1221   case ISD::SETGT:
1222   case ISD::SETLE:
1223   case ISD::SETUGT:
1224   case ISD::SETULE:
1225     CC = ISD::getSetCCSwappedOperands(CC);
1226     std::swap(LHS, RHS);
1227     break;
1228   }
1229 }
1230 
1231 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1232   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1233   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1234   if (VT.getVectorElementType() == MVT::i1)
1235     KnownSize *= 8;
1236 
1237   switch (KnownSize) {
1238   default:
1239     llvm_unreachable("Invalid LMUL.");
1240   case 8:
1241     return RISCVII::VLMUL::LMUL_F8;
1242   case 16:
1243     return RISCVII::VLMUL::LMUL_F4;
1244   case 32:
1245     return RISCVII::VLMUL::LMUL_F2;
1246   case 64:
1247     return RISCVII::VLMUL::LMUL_1;
1248   case 128:
1249     return RISCVII::VLMUL::LMUL_2;
1250   case 256:
1251     return RISCVII::VLMUL::LMUL_4;
1252   case 512:
1253     return RISCVII::VLMUL::LMUL_8;
1254   }
1255 }
1256 
1257 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1258   switch (LMul) {
1259   default:
1260     llvm_unreachable("Invalid LMUL.");
1261   case RISCVII::VLMUL::LMUL_F8:
1262   case RISCVII::VLMUL::LMUL_F4:
1263   case RISCVII::VLMUL::LMUL_F2:
1264   case RISCVII::VLMUL::LMUL_1:
1265     return RISCV::VRRegClassID;
1266   case RISCVII::VLMUL::LMUL_2:
1267     return RISCV::VRM2RegClassID;
1268   case RISCVII::VLMUL::LMUL_4:
1269     return RISCV::VRM4RegClassID;
1270   case RISCVII::VLMUL::LMUL_8:
1271     return RISCV::VRM8RegClassID;
1272   }
1273 }
1274 
1275 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1276   RISCVII::VLMUL LMUL = getLMUL(VT);
1277   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1278       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1279       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1280       LMUL == RISCVII::VLMUL::LMUL_1) {
1281     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1282                   "Unexpected subreg numbering");
1283     return RISCV::sub_vrm1_0 + Index;
1284   }
1285   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1286     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1287                   "Unexpected subreg numbering");
1288     return RISCV::sub_vrm2_0 + Index;
1289   }
1290   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1291     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1292                   "Unexpected subreg numbering");
1293     return RISCV::sub_vrm4_0 + Index;
1294   }
1295   llvm_unreachable("Invalid vector type.");
1296 }
1297 
1298 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1299   if (VT.getVectorElementType() == MVT::i1)
1300     return RISCV::VRRegClassID;
1301   return getRegClassIDForLMUL(getLMUL(VT));
1302 }
1303 
1304 // Attempt to decompose a subvector insert/extract between VecVT and
1305 // SubVecVT via subregister indices. Returns the subregister index that
1306 // can perform the subvector insert/extract with the given element index, as
1307 // well as the index corresponding to any leftover subvectors that must be
1308 // further inserted/extracted within the register class for SubVecVT.
1309 std::pair<unsigned, unsigned>
1310 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1311     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1312     const RISCVRegisterInfo *TRI) {
1313   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1314                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1315                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1316                 "Register classes not ordered");
1317   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1318   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1319   // Try to compose a subregister index that takes us from the incoming
1320   // LMUL>1 register class down to the outgoing one. At each step we half
1321   // the LMUL:
1322   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1323   // Note that this is not guaranteed to find a subregister index, such as
1324   // when we are extracting from one VR type to another.
1325   unsigned SubRegIdx = RISCV::NoSubRegister;
1326   for (const unsigned RCID :
1327        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1328     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1329       VecVT = VecVT.getHalfNumVectorElementsVT();
1330       bool IsHi =
1331           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1332       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1333                                             getSubregIndexByMVT(VecVT, IsHi));
1334       if (IsHi)
1335         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1336     }
1337   return {SubRegIdx, InsertExtractIdx};
1338 }
1339 
1340 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1341 // stores for those types.
1342 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1343   return !Subtarget.useRVVForFixedLengthVectors() ||
1344          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1345 }
1346 
1347 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1348   if (ScalarTy->isPointerTy())
1349     return true;
1350 
1351   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1352       ScalarTy->isIntegerTy(32) || ScalarTy->isIntegerTy(64))
1353     return true;
1354 
1355   if (ScalarTy->isHalfTy())
1356     return Subtarget.hasStdExtZfh();
1357   if (ScalarTy->isFloatTy())
1358     return Subtarget.hasStdExtF();
1359   if (ScalarTy->isDoubleTy())
1360     return Subtarget.hasStdExtD();
1361 
1362   return false;
1363 }
1364 
1365 static bool useRVVForFixedLengthVectorVT(MVT VT,
1366                                          const RISCVSubtarget &Subtarget) {
1367   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1368   if (!Subtarget.useRVVForFixedLengthVectors())
1369     return false;
1370 
1371   // We only support a set of vector types with a consistent maximum fixed size
1372   // across all supported vector element types to avoid legalization issues.
1373   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1374   // fixed-length vector type we support is 1024 bytes.
1375   if (VT.getFixedSizeInBits() > 1024 * 8)
1376     return false;
1377 
1378   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1379 
1380   MVT EltVT = VT.getVectorElementType();
1381 
1382   // Don't use RVV for vectors we cannot scalarize if required.
1383   switch (EltVT.SimpleTy) {
1384   // i1 is supported but has different rules.
1385   default:
1386     return false;
1387   case MVT::i1:
1388     // Masks can only use a single register.
1389     if (VT.getVectorNumElements() > MinVLen)
1390       return false;
1391     MinVLen /= 8;
1392     break;
1393   case MVT::i8:
1394   case MVT::i16:
1395   case MVT::i32:
1396   case MVT::i64:
1397     break;
1398   case MVT::f16:
1399     if (!Subtarget.hasStdExtZfh())
1400       return false;
1401     break;
1402   case MVT::f32:
1403     if (!Subtarget.hasStdExtF())
1404       return false;
1405     break;
1406   case MVT::f64:
1407     if (!Subtarget.hasStdExtD())
1408       return false;
1409     break;
1410   }
1411 
1412   // Reject elements larger than ELEN.
1413   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1414     return false;
1415 
1416   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1417   // Don't use RVV for types that don't fit.
1418   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1419     return false;
1420 
1421   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1422   // the base fixed length RVV support in place.
1423   if (!VT.isPow2VectorType())
1424     return false;
1425 
1426   return true;
1427 }
1428 
1429 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1430   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1431 }
1432 
1433 // Return the largest legal scalable vector type that matches VT's element type.
1434 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1435                                             const RISCVSubtarget &Subtarget) {
1436   // This may be called before legal types are setup.
1437   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1438           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1439          "Expected legal fixed length vector!");
1440 
1441   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1442   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1443 
1444   MVT EltVT = VT.getVectorElementType();
1445   switch (EltVT.SimpleTy) {
1446   default:
1447     llvm_unreachable("unexpected element type for RVV container");
1448   case MVT::i1:
1449   case MVT::i8:
1450   case MVT::i16:
1451   case MVT::i32:
1452   case MVT::i64:
1453   case MVT::f16:
1454   case MVT::f32:
1455   case MVT::f64: {
1456     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1457     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1458     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1459     unsigned NumElts =
1460         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1461     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1462     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1463     return MVT::getScalableVectorVT(EltVT, NumElts);
1464   }
1465   }
1466 }
1467 
1468 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1469                                             const RISCVSubtarget &Subtarget) {
1470   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1471                                           Subtarget);
1472 }
1473 
1474 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1475   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1476 }
1477 
1478 // Grow V to consume an entire RVV register.
1479 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1480                                        const RISCVSubtarget &Subtarget) {
1481   assert(VT.isScalableVector() &&
1482          "Expected to convert into a scalable vector!");
1483   assert(V.getValueType().isFixedLengthVector() &&
1484          "Expected a fixed length vector operand!");
1485   SDLoc DL(V);
1486   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1487   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1488 }
1489 
1490 // Shrink V so it's just big enough to maintain a VT's worth of data.
1491 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1492                                          const RISCVSubtarget &Subtarget) {
1493   assert(VT.isFixedLengthVector() &&
1494          "Expected to convert into a fixed length vector!");
1495   assert(V.getValueType().isScalableVector() &&
1496          "Expected a scalable vector operand!");
1497   SDLoc DL(V);
1498   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1499   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1500 }
1501 
1502 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1503 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1504 // the vector type that it is contained in.
1505 static std::pair<SDValue, SDValue>
1506 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1507                 const RISCVSubtarget &Subtarget) {
1508   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1509   MVT XLenVT = Subtarget.getXLenVT();
1510   SDValue VL = VecVT.isFixedLengthVector()
1511                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1512                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1513   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1514   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1515   return {Mask, VL};
1516 }
1517 
1518 // As above but assuming the given type is a scalable vector type.
1519 static std::pair<SDValue, SDValue>
1520 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1521                         const RISCVSubtarget &Subtarget) {
1522   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1523   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1524 }
1525 
1526 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1527 // of either is (currently) supported. This can get us into an infinite loop
1528 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1529 // as a ..., etc.
1530 // Until either (or both) of these can reliably lower any node, reporting that
1531 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1532 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1533 // which is not desirable.
1534 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1535     EVT VT, unsigned DefinedValues) const {
1536   return false;
1537 }
1538 
1539 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1540   // Only splats are currently supported.
1541   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1542     return true;
1543 
1544   return false;
1545 }
1546 
1547 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1548   // RISCV FP-to-int conversions saturate to the destination register size, but
1549   // don't produce 0 for nan. We can use a conversion instruction and fix the
1550   // nan case with a compare and a select.
1551   SDValue Src = Op.getOperand(0);
1552 
1553   EVT DstVT = Op.getValueType();
1554   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1555 
1556   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1557   unsigned Opc;
1558   if (SatVT == DstVT)
1559     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1560   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1561     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1562   else
1563     return SDValue();
1564   // FIXME: Support other SatVTs by clamping before or after the conversion.
1565 
1566   SDLoc DL(Op);
1567   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1568 
1569   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1570   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1571 }
1572 
1573 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1574                                  const RISCVSubtarget &Subtarget) {
1575   MVT VT = Op.getSimpleValueType();
1576   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1577 
1578   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1579 
1580   SDLoc DL(Op);
1581   SDValue Mask, VL;
1582   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1583 
1584   unsigned Opc =
1585       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1586   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1587   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1588 }
1589 
1590 struct VIDSequence {
1591   int64_t StepNumerator;
1592   unsigned StepDenominator;
1593   int64_t Addend;
1594 };
1595 
1596 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1597 // to the (non-zero) step S and start value X. This can be then lowered as the
1598 // RVV sequence (VID * S) + X, for example.
1599 // The step S is represented as an integer numerator divided by a positive
1600 // denominator. Note that the implementation currently only identifies
1601 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1602 // cannot detect 2/3, for example.
1603 // Note that this method will also match potentially unappealing index
1604 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1605 // determine whether this is worth generating code for.
1606 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1607   unsigned NumElts = Op.getNumOperands();
1608   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1609   if (!Op.getValueType().isInteger())
1610     return None;
1611 
1612   Optional<unsigned> SeqStepDenom;
1613   Optional<int64_t> SeqStepNum, SeqAddend;
1614   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1615   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1616   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1617     // Assume undef elements match the sequence; we just have to be careful
1618     // when interpolating across them.
1619     if (Op.getOperand(Idx).isUndef())
1620       continue;
1621     // The BUILD_VECTOR must be all constants.
1622     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1623       return None;
1624 
1625     uint64_t Val = Op.getConstantOperandVal(Idx) &
1626                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1627 
1628     if (PrevElt) {
1629       // Calculate the step since the last non-undef element, and ensure
1630       // it's consistent across the entire sequence.
1631       unsigned IdxDiff = Idx - PrevElt->second;
1632       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1633 
1634       // A zero-value value difference means that we're somewhere in the middle
1635       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1636       // step change before evaluating the sequence.
1637       if (ValDiff != 0) {
1638         int64_t Remainder = ValDiff % IdxDiff;
1639         // Normalize the step if it's greater than 1.
1640         if (Remainder != ValDiff) {
1641           // The difference must cleanly divide the element span.
1642           if (Remainder != 0)
1643             return None;
1644           ValDiff /= IdxDiff;
1645           IdxDiff = 1;
1646         }
1647 
1648         if (!SeqStepNum)
1649           SeqStepNum = ValDiff;
1650         else if (ValDiff != SeqStepNum)
1651           return None;
1652 
1653         if (!SeqStepDenom)
1654           SeqStepDenom = IdxDiff;
1655         else if (IdxDiff != *SeqStepDenom)
1656           return None;
1657       }
1658     }
1659 
1660     // Record and/or check any addend.
1661     if (SeqStepNum && SeqStepDenom) {
1662       uint64_t ExpectedVal =
1663           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1664       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1665       if (!SeqAddend)
1666         SeqAddend = Addend;
1667       else if (SeqAddend != Addend)
1668         return None;
1669     }
1670 
1671     // Record this non-undef element for later.
1672     if (!PrevElt || PrevElt->first != Val)
1673       PrevElt = std::make_pair(Val, Idx);
1674   }
1675   // We need to have logged both a step and an addend for this to count as
1676   // a legal index sequence.
1677   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1678     return None;
1679 
1680   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1681 }
1682 
1683 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1684                                  const RISCVSubtarget &Subtarget) {
1685   MVT VT = Op.getSimpleValueType();
1686   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1687 
1688   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1689 
1690   SDLoc DL(Op);
1691   SDValue Mask, VL;
1692   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1693 
1694   MVT XLenVT = Subtarget.getXLenVT();
1695   unsigned NumElts = Op.getNumOperands();
1696 
1697   if (VT.getVectorElementType() == MVT::i1) {
1698     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1699       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1700       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1701     }
1702 
1703     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1704       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1705       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1706     }
1707 
1708     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1709     // scalar integer chunks whose bit-width depends on the number of mask
1710     // bits and XLEN.
1711     // First, determine the most appropriate scalar integer type to use. This
1712     // is at most XLenVT, but may be shrunk to a smaller vector element type
1713     // according to the size of the final vector - use i8 chunks rather than
1714     // XLenVT if we're producing a v8i1. This results in more consistent
1715     // codegen across RV32 and RV64.
1716     unsigned NumViaIntegerBits =
1717         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1718     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1719       // If we have to use more than one INSERT_VECTOR_ELT then this
1720       // optimization is likely to increase code size; avoid peforming it in
1721       // such a case. We can use a load from a constant pool in this case.
1722       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1723         return SDValue();
1724       // Now we can create our integer vector type. Note that it may be larger
1725       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1726       MVT IntegerViaVecVT =
1727           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1728                            divideCeil(NumElts, NumViaIntegerBits));
1729 
1730       uint64_t Bits = 0;
1731       unsigned BitPos = 0, IntegerEltIdx = 0;
1732       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1733 
1734       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1735         // Once we accumulate enough bits to fill our scalar type, insert into
1736         // our vector and clear our accumulated data.
1737         if (I != 0 && I % NumViaIntegerBits == 0) {
1738           if (NumViaIntegerBits <= 32)
1739             Bits = SignExtend64(Bits, 32);
1740           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1741           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1742                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1743           Bits = 0;
1744           BitPos = 0;
1745           IntegerEltIdx++;
1746         }
1747         SDValue V = Op.getOperand(I);
1748         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1749         Bits |= ((uint64_t)BitValue << BitPos);
1750       }
1751 
1752       // Insert the (remaining) scalar value into position in our integer
1753       // vector type.
1754       if (NumViaIntegerBits <= 32)
1755         Bits = SignExtend64(Bits, 32);
1756       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1757       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1758                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1759 
1760       if (NumElts < NumViaIntegerBits) {
1761         // If we're producing a smaller vector than our minimum legal integer
1762         // type, bitcast to the equivalent (known-legal) mask type, and extract
1763         // our final mask.
1764         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1765         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1766         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1767                           DAG.getConstant(0, DL, XLenVT));
1768       } else {
1769         // Else we must have produced an integer type with the same size as the
1770         // mask type; bitcast for the final result.
1771         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1772         Vec = DAG.getBitcast(VT, Vec);
1773       }
1774 
1775       return Vec;
1776     }
1777 
1778     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1779     // vector type, we have a legal equivalently-sized i8 type, so we can use
1780     // that.
1781     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1782     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1783 
1784     SDValue WideVec;
1785     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1786       // For a splat, perform a scalar truncate before creating the wider
1787       // vector.
1788       assert(Splat.getValueType() == XLenVT &&
1789              "Unexpected type for i1 splat value");
1790       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1791                           DAG.getConstant(1, DL, XLenVT));
1792       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1793     } else {
1794       SmallVector<SDValue, 8> Ops(Op->op_values());
1795       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1796       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1797       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1798     }
1799 
1800     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1801   }
1802 
1803   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1804     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1805                                         : RISCVISD::VMV_V_X_VL;
1806     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1807     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1808   }
1809 
1810   // Try and match index sequences, which we can lower to the vid instruction
1811   // with optional modifications. An all-undef vector is matched by
1812   // getSplatValue, above.
1813   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1814     int64_t StepNumerator = SimpleVID->StepNumerator;
1815     unsigned StepDenominator = SimpleVID->StepDenominator;
1816     int64_t Addend = SimpleVID->Addend;
1817     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1818     // threshold since it's the immediate value many RVV instructions accept.
1819     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1820         isInt<5>(Addend)) {
1821       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1822       // Convert right out of the scalable type so we can use standard ISD
1823       // nodes for the rest of the computation. If we used scalable types with
1824       // these, we'd lose the fixed-length vector info and generate worse
1825       // vsetvli code.
1826       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1827       assert(StepNumerator != 0 && "Invalid step");
1828       bool Negate = false;
1829       if (StepNumerator != 1) {
1830         int64_t SplatStepVal = StepNumerator;
1831         unsigned Opcode = ISD::MUL;
1832         if (isPowerOf2_64(std::abs(StepNumerator))) {
1833           Negate = StepNumerator < 0;
1834           Opcode = ISD::SHL;
1835           SplatStepVal = Log2_64(std::abs(StepNumerator));
1836         }
1837         SDValue SplatStep = DAG.getSplatVector(
1838             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1839         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1840       }
1841       if (StepDenominator != 1) {
1842         SDValue SplatStep = DAG.getSplatVector(
1843             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1844         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1845       }
1846       if (Addend != 0 || Negate) {
1847         SDValue SplatAddend =
1848             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1849         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1850       }
1851       return VID;
1852     }
1853   }
1854 
1855   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1856   // when re-interpreted as a vector with a larger element type. For example,
1857   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1858   // could be instead splat as
1859   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1860   // TODO: This optimization could also work on non-constant splats, but it
1861   // would require bit-manipulation instructions to construct the splat value.
1862   SmallVector<SDValue> Sequence;
1863   unsigned EltBitSize = VT.getScalarSizeInBits();
1864   const auto *BV = cast<BuildVectorSDNode>(Op);
1865   if (VT.isInteger() && EltBitSize < 64 &&
1866       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1867       BV->getRepeatedSequence(Sequence) &&
1868       (Sequence.size() * EltBitSize) <= 64) {
1869     unsigned SeqLen = Sequence.size();
1870     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1871     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1872     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1873             ViaIntVT == MVT::i64) &&
1874            "Unexpected sequence type");
1875 
1876     unsigned EltIdx = 0;
1877     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1878     uint64_t SplatValue = 0;
1879     // Construct the amalgamated value which can be splatted as this larger
1880     // vector type.
1881     for (const auto &SeqV : Sequence) {
1882       if (!SeqV.isUndef())
1883         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1884                        << (EltIdx * EltBitSize));
1885       EltIdx++;
1886     }
1887 
1888     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1889     // achieve better constant materializion.
1890     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1891       SplatValue = SignExtend64(SplatValue, 32);
1892 
1893     // Since we can't introduce illegal i64 types at this stage, we can only
1894     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1895     // way we can use RVV instructions to splat.
1896     assert((ViaIntVT.bitsLE(XLenVT) ||
1897             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1898            "Unexpected bitcast sequence");
1899     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1900       SDValue ViaVL =
1901           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1902       MVT ViaContainerVT =
1903           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1904       SDValue Splat =
1905           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1906                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1907       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1908       return DAG.getBitcast(VT, Splat);
1909     }
1910   }
1911 
1912   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1913   // which constitute a large proportion of the elements. In such cases we can
1914   // splat a vector with the dominant element and make up the shortfall with
1915   // INSERT_VECTOR_ELTs.
1916   // Note that this includes vectors of 2 elements by association. The
1917   // upper-most element is the "dominant" one, allowing us to use a splat to
1918   // "insert" the upper element, and an insert of the lower element at position
1919   // 0, which improves codegen.
1920   SDValue DominantValue;
1921   unsigned MostCommonCount = 0;
1922   DenseMap<SDValue, unsigned> ValueCounts;
1923   unsigned NumUndefElts =
1924       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1925 
1926   // Track the number of scalar loads we know we'd be inserting, estimated as
1927   // any non-zero floating-point constant. Other kinds of element are either
1928   // already in registers or are materialized on demand. The threshold at which
1929   // a vector load is more desirable than several scalar materializion and
1930   // vector-insertion instructions is not known.
1931   unsigned NumScalarLoads = 0;
1932 
1933   for (SDValue V : Op->op_values()) {
1934     if (V.isUndef())
1935       continue;
1936 
1937     ValueCounts.insert(std::make_pair(V, 0));
1938     unsigned &Count = ValueCounts[V];
1939 
1940     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1941       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1942 
1943     // Is this value dominant? In case of a tie, prefer the highest element as
1944     // it's cheaper to insert near the beginning of a vector than it is at the
1945     // end.
1946     if (++Count >= MostCommonCount) {
1947       DominantValue = V;
1948       MostCommonCount = Count;
1949     }
1950   }
1951 
1952   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1953   unsigned NumDefElts = NumElts - NumUndefElts;
1954   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1955 
1956   // Don't perform this optimization when optimizing for size, since
1957   // materializing elements and inserting them tends to cause code bloat.
1958   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1959       ((MostCommonCount > DominantValueCountThreshold) ||
1960        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1961     // Start by splatting the most common element.
1962     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1963 
1964     DenseSet<SDValue> Processed{DominantValue};
1965     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1966     for (const auto &OpIdx : enumerate(Op->ops())) {
1967       const SDValue &V = OpIdx.value();
1968       if (V.isUndef() || !Processed.insert(V).second)
1969         continue;
1970       if (ValueCounts[V] == 1) {
1971         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1972                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1973       } else {
1974         // Blend in all instances of this value using a VSELECT, using a
1975         // mask where each bit signals whether that element is the one
1976         // we're after.
1977         SmallVector<SDValue> Ops;
1978         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1979           return DAG.getConstant(V == V1, DL, XLenVT);
1980         });
1981         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
1982                           DAG.getBuildVector(SelMaskTy, DL, Ops),
1983                           DAG.getSplatBuildVector(VT, DL, V), Vec);
1984       }
1985     }
1986 
1987     return Vec;
1988   }
1989 
1990   return SDValue();
1991 }
1992 
1993 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
1994                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
1995   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
1996     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
1997     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
1998     // If Hi constant is all the same sign bit as Lo, lower this as a custom
1999     // node in order to try and match RVV vector/scalar instructions.
2000     if ((LoC >> 31) == HiC)
2001       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2002   }
2003 
2004   // Fall back to a stack store and stride x0 vector load.
2005   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2006 }
2007 
2008 // Called by type legalization to handle splat of i64 on RV32.
2009 // FIXME: We can optimize this when the type has sign or zero bits in one
2010 // of the halves.
2011 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2012                                    SDValue VL, SelectionDAG &DAG) {
2013   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2014   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2015                            DAG.getConstant(0, DL, MVT::i32));
2016   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2017                            DAG.getConstant(1, DL, MVT::i32));
2018   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2019 }
2020 
2021 // This function lowers a splat of a scalar operand Splat with the vector
2022 // length VL. It ensures the final sequence is type legal, which is useful when
2023 // lowering a splat after type legalization.
2024 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2025                                 SelectionDAG &DAG,
2026                                 const RISCVSubtarget &Subtarget) {
2027   if (VT.isFloatingPoint())
2028     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2029 
2030   MVT XLenVT = Subtarget.getXLenVT();
2031 
2032   // Simplest case is that the operand needs to be promoted to XLenVT.
2033   if (Scalar.getValueType().bitsLE(XLenVT)) {
2034     // If the operand is a constant, sign extend to increase our chances
2035     // of being able to use a .vi instruction. ANY_EXTEND would become a
2036     // a zero extend and the simm5 check in isel would fail.
2037     // FIXME: Should we ignore the upper bits in isel instead?
2038     unsigned ExtOpc =
2039         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2040     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2041     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2042   }
2043 
2044   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2045          "Unexpected scalar for splat lowering!");
2046 
2047   // Otherwise use the more complicated splatting algorithm.
2048   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2049 }
2050 
2051 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2052                                    const RISCVSubtarget &Subtarget) {
2053   SDValue V1 = Op.getOperand(0);
2054   SDValue V2 = Op.getOperand(1);
2055   SDLoc DL(Op);
2056   MVT XLenVT = Subtarget.getXLenVT();
2057   MVT VT = Op.getSimpleValueType();
2058   unsigned NumElts = VT.getVectorNumElements();
2059   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2060 
2061   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2062 
2063   SDValue TrueMask, VL;
2064   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2065 
2066   if (SVN->isSplat()) {
2067     const int Lane = SVN->getSplatIndex();
2068     if (Lane >= 0) {
2069       MVT SVT = VT.getVectorElementType();
2070 
2071       // Turn splatted vector load into a strided load with an X0 stride.
2072       SDValue V = V1;
2073       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2074       // with undef.
2075       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2076       int Offset = Lane;
2077       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2078         int OpElements =
2079             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2080         V = V.getOperand(Offset / OpElements);
2081         Offset %= OpElements;
2082       }
2083 
2084       // We need to ensure the load isn't atomic or volatile.
2085       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2086         auto *Ld = cast<LoadSDNode>(V);
2087         Offset *= SVT.getStoreSize();
2088         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2089                                                    TypeSize::Fixed(Offset), DL);
2090 
2091         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2092         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2093           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2094           SDValue IntID =
2095               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2096           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2097                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2098           SDValue NewLoad = DAG.getMemIntrinsicNode(
2099               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2100               DAG.getMachineFunction().getMachineMemOperand(
2101                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2102           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2103           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2104         }
2105 
2106         // Otherwise use a scalar load and splat. This will give the best
2107         // opportunity to fold a splat into the operation. ISel can turn it into
2108         // the x0 strided load if we aren't able to fold away the select.
2109         if (SVT.isFloatingPoint())
2110           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2111                           Ld->getPointerInfo().getWithOffset(Offset),
2112                           Ld->getOriginalAlign(),
2113                           Ld->getMemOperand()->getFlags());
2114         else
2115           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2116                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2117                              Ld->getOriginalAlign(),
2118                              Ld->getMemOperand()->getFlags());
2119         DAG.makeEquivalentMemoryOrdering(Ld, V);
2120 
2121         unsigned Opc =
2122             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2123         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2124         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2125       }
2126 
2127       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2128       assert(Lane < (int)NumElts && "Unexpected lane!");
2129       SDValue Gather =
2130           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2131                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2132       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2133     }
2134   }
2135 
2136   // Detect shuffles which can be re-expressed as vector selects; these are
2137   // shuffles in which each element in the destination is taken from an element
2138   // at the corresponding index in either source vectors.
2139   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2140     int MaskIndex = MaskIdx.value();
2141     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2142   });
2143 
2144   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2145 
2146   SmallVector<SDValue> MaskVals;
2147   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2148   // merged with a second vrgather.
2149   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2150 
2151   // By default we preserve the original operand order, and use a mask to
2152   // select LHS as true and RHS as false. However, since RVV vector selects may
2153   // feature splats but only on the LHS, we may choose to invert our mask and
2154   // instead select between RHS and LHS.
2155   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2156   bool InvertMask = IsSelect == SwapOps;
2157 
2158   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2159   // half.
2160   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2161 
2162   // Now construct the mask that will be used by the vselect or blended
2163   // vrgather operation. For vrgathers, construct the appropriate indices into
2164   // each vector.
2165   for (int MaskIndex : SVN->getMask()) {
2166     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2167     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2168     if (!IsSelect) {
2169       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2170       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2171                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2172                                      : DAG.getUNDEF(XLenVT));
2173       GatherIndicesRHS.push_back(
2174           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2175                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2176       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2177         ++LHSIndexCounts[MaskIndex];
2178       if (!IsLHSOrUndefIndex)
2179         ++RHSIndexCounts[MaskIndex - NumElts];
2180     }
2181   }
2182 
2183   if (SwapOps) {
2184     std::swap(V1, V2);
2185     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2186   }
2187 
2188   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2189   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2190   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2191 
2192   if (IsSelect)
2193     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2194 
2195   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2196     // On such a large vector we're unable to use i8 as the index type.
2197     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2198     // may involve vector splitting if we're already at LMUL=8, or our
2199     // user-supplied maximum fixed-length LMUL.
2200     return SDValue();
2201   }
2202 
2203   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2204   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2205   MVT IndexVT = VT.changeTypeToInteger();
2206   // Since we can't introduce illegal index types at this stage, use i16 and
2207   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2208   // than XLenVT.
2209   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2210     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2211     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2212   }
2213 
2214   MVT IndexContainerVT =
2215       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2216 
2217   SDValue Gather;
2218   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2219   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2220   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2221     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2222   } else {
2223     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2224     // If only one index is used, we can use a "splat" vrgather.
2225     // TODO: We can splat the most-common index and fix-up any stragglers, if
2226     // that's beneficial.
2227     if (LHSIndexCounts.size() == 1) {
2228       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2229       Gather =
2230           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2231                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2232     } else {
2233       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2234       LHSIndices =
2235           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2236 
2237       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2238                            TrueMask, VL);
2239     }
2240   }
2241 
2242   // If a second vector operand is used by this shuffle, blend it in with an
2243   // additional vrgather.
2244   if (!V2.isUndef()) {
2245     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2246     // If only one index is used, we can use a "splat" vrgather.
2247     // TODO: We can splat the most-common index and fix-up any stragglers, if
2248     // that's beneficial.
2249     if (RHSIndexCounts.size() == 1) {
2250       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2251       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2252                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2253     } else {
2254       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2255       RHSIndices =
2256           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2257       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2258                        VL);
2259     }
2260 
2261     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2262     SelectMask =
2263         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2264 
2265     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2266                          Gather, VL);
2267   }
2268 
2269   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2270 }
2271 
2272 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2273                                      SDLoc DL, SelectionDAG &DAG,
2274                                      const RISCVSubtarget &Subtarget) {
2275   if (VT.isScalableVector())
2276     return DAG.getFPExtendOrRound(Op, DL, VT);
2277   assert(VT.isFixedLengthVector() &&
2278          "Unexpected value type for RVV FP extend/round lowering");
2279   SDValue Mask, VL;
2280   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2281   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2282                         ? RISCVISD::FP_EXTEND_VL
2283                         : RISCVISD::FP_ROUND_VL;
2284   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2285 }
2286 
2287 // While RVV has alignment restrictions, we should always be able to load as a
2288 // legal equivalently-sized byte-typed vector instead. This method is
2289 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2290 // the load is already correctly-aligned, it returns SDValue().
2291 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2292                                                     SelectionDAG &DAG) const {
2293   auto *Load = cast<LoadSDNode>(Op);
2294   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2295 
2296   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2297                                      Load->getMemoryVT(),
2298                                      *Load->getMemOperand()))
2299     return SDValue();
2300 
2301   SDLoc DL(Op);
2302   MVT VT = Op.getSimpleValueType();
2303   unsigned EltSizeBits = VT.getScalarSizeInBits();
2304   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2305          "Unexpected unaligned RVV load type");
2306   MVT NewVT =
2307       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2308   assert(NewVT.isValid() &&
2309          "Expecting equally-sized RVV vector types to be legal");
2310   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2311                           Load->getPointerInfo(), Load->getOriginalAlign(),
2312                           Load->getMemOperand()->getFlags());
2313   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2314 }
2315 
2316 // While RVV has alignment restrictions, we should always be able to store as a
2317 // legal equivalently-sized byte-typed vector instead. This method is
2318 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2319 // returns SDValue() if the store is already correctly aligned.
2320 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2321                                                      SelectionDAG &DAG) const {
2322   auto *Store = cast<StoreSDNode>(Op);
2323   assert(Store && Store->getValue().getValueType().isVector() &&
2324          "Expected vector store");
2325 
2326   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2327                                      Store->getMemoryVT(),
2328                                      *Store->getMemOperand()))
2329     return SDValue();
2330 
2331   SDLoc DL(Op);
2332   SDValue StoredVal = Store->getValue();
2333   MVT VT = StoredVal.getSimpleValueType();
2334   unsigned EltSizeBits = VT.getScalarSizeInBits();
2335   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2336          "Unexpected unaligned RVV store type");
2337   MVT NewVT =
2338       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2339   assert(NewVT.isValid() &&
2340          "Expecting equally-sized RVV vector types to be legal");
2341   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2342   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2343                       Store->getPointerInfo(), Store->getOriginalAlign(),
2344                       Store->getMemOperand()->getFlags());
2345 }
2346 
2347 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2348                                             SelectionDAG &DAG) const {
2349   switch (Op.getOpcode()) {
2350   default:
2351     report_fatal_error("unimplemented operand");
2352   case ISD::GlobalAddress:
2353     return lowerGlobalAddress(Op, DAG);
2354   case ISD::BlockAddress:
2355     return lowerBlockAddress(Op, DAG);
2356   case ISD::ConstantPool:
2357     return lowerConstantPool(Op, DAG);
2358   case ISD::JumpTable:
2359     return lowerJumpTable(Op, DAG);
2360   case ISD::GlobalTLSAddress:
2361     return lowerGlobalTLSAddress(Op, DAG);
2362   case ISD::SELECT:
2363     return lowerSELECT(Op, DAG);
2364   case ISD::BRCOND:
2365     return lowerBRCOND(Op, DAG);
2366   case ISD::VASTART:
2367     return lowerVASTART(Op, DAG);
2368   case ISD::FRAMEADDR:
2369     return lowerFRAMEADDR(Op, DAG);
2370   case ISD::RETURNADDR:
2371     return lowerRETURNADDR(Op, DAG);
2372   case ISD::SHL_PARTS:
2373     return lowerShiftLeftParts(Op, DAG);
2374   case ISD::SRA_PARTS:
2375     return lowerShiftRightParts(Op, DAG, true);
2376   case ISD::SRL_PARTS:
2377     return lowerShiftRightParts(Op, DAG, false);
2378   case ISD::BITCAST: {
2379     SDLoc DL(Op);
2380     EVT VT = Op.getValueType();
2381     SDValue Op0 = Op.getOperand(0);
2382     EVT Op0VT = Op0.getValueType();
2383     MVT XLenVT = Subtarget.getXLenVT();
2384     if (VT.isFixedLengthVector()) {
2385       // We can handle fixed length vector bitcasts with a simple replacement
2386       // in isel.
2387       if (Op0VT.isFixedLengthVector())
2388         return Op;
2389       // When bitcasting from scalar to fixed-length vector, insert the scalar
2390       // into a one-element vector of the result type, and perform a vector
2391       // bitcast.
2392       if (!Op0VT.isVector()) {
2393         auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2394         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2395                                               DAG.getUNDEF(BVT), Op0,
2396                                               DAG.getConstant(0, DL, XLenVT)));
2397       }
2398       return SDValue();
2399     }
2400     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2401     // thus: bitcast the vector to a one-element vector type whose element type
2402     // is the same as the result type, and extract the first element.
2403     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2404       LLVMContext &Context = *DAG.getContext();
2405       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
2406       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2407                          DAG.getConstant(0, DL, XLenVT));
2408     }
2409     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2410       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2411       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2412       return FPConv;
2413     }
2414     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2415         Subtarget.hasStdExtF()) {
2416       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2417       SDValue FPConv =
2418           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2419       return FPConv;
2420     }
2421     return SDValue();
2422   }
2423   case ISD::INTRINSIC_WO_CHAIN:
2424     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2425   case ISD::INTRINSIC_W_CHAIN:
2426     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2427   case ISD::INTRINSIC_VOID:
2428     return LowerINTRINSIC_VOID(Op, DAG);
2429   case ISD::BSWAP:
2430   case ISD::BITREVERSE: {
2431     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2432     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2433     MVT VT = Op.getSimpleValueType();
2434     SDLoc DL(Op);
2435     // Start with the maximum immediate value which is the bitwidth - 1.
2436     unsigned Imm = VT.getSizeInBits() - 1;
2437     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2438     if (Op.getOpcode() == ISD::BSWAP)
2439       Imm &= ~0x7U;
2440     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2441                        DAG.getConstant(Imm, DL, VT));
2442   }
2443   case ISD::FSHL:
2444   case ISD::FSHR: {
2445     MVT VT = Op.getSimpleValueType();
2446     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2447     SDLoc DL(Op);
2448     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2449       return Op;
2450     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2451     // use log(XLen) bits. Mask the shift amount accordingly.
2452     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2453     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2454                                 DAG.getConstant(ShAmtWidth, DL, VT));
2455     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2456     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2457   }
2458   case ISD::TRUNCATE: {
2459     SDLoc DL(Op);
2460     MVT VT = Op.getSimpleValueType();
2461     // Only custom-lower vector truncates
2462     if (!VT.isVector())
2463       return Op;
2464 
2465     // Truncates to mask types are handled differently
2466     if (VT.getVectorElementType() == MVT::i1)
2467       return lowerVectorMaskTrunc(Op, DAG);
2468 
2469     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2470     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2471     // truncate by one power of two at a time.
2472     MVT DstEltVT = VT.getVectorElementType();
2473 
2474     SDValue Src = Op.getOperand(0);
2475     MVT SrcVT = Src.getSimpleValueType();
2476     MVT SrcEltVT = SrcVT.getVectorElementType();
2477 
2478     assert(DstEltVT.bitsLT(SrcEltVT) &&
2479            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2480            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2481            "Unexpected vector truncate lowering");
2482 
2483     MVT ContainerVT = SrcVT;
2484     if (SrcVT.isFixedLengthVector()) {
2485       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2486       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2487     }
2488 
2489     SDValue Result = Src;
2490     SDValue Mask, VL;
2491     std::tie(Mask, VL) =
2492         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2493     LLVMContext &Context = *DAG.getContext();
2494     const ElementCount Count = ContainerVT.getVectorElementCount();
2495     do {
2496       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2497       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2498       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2499                            Mask, VL);
2500     } while (SrcEltVT != DstEltVT);
2501 
2502     if (SrcVT.isFixedLengthVector())
2503       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2504 
2505     return Result;
2506   }
2507   case ISD::ANY_EXTEND:
2508   case ISD::ZERO_EXTEND:
2509     if (Op.getOperand(0).getValueType().isVector() &&
2510         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2511       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2512     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2513   case ISD::SIGN_EXTEND:
2514     if (Op.getOperand(0).getValueType().isVector() &&
2515         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2516       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2517     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2518   case ISD::SPLAT_VECTOR_PARTS:
2519     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2520   case ISD::INSERT_VECTOR_ELT:
2521     return lowerINSERT_VECTOR_ELT(Op, DAG);
2522   case ISD::EXTRACT_VECTOR_ELT:
2523     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2524   case ISD::VSCALE: {
2525     MVT VT = Op.getSimpleValueType();
2526     SDLoc DL(Op);
2527     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2528     // We define our scalable vector types for lmul=1 to use a 64 bit known
2529     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2530     // vscale as VLENB / 8.
2531     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2532     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2533       // We assume VLENB is a multiple of 8. We manually choose the best shift
2534       // here because SimplifyDemandedBits isn't always able to simplify it.
2535       uint64_t Val = Op.getConstantOperandVal(0);
2536       if (isPowerOf2_64(Val)) {
2537         uint64_t Log2 = Log2_64(Val);
2538         if (Log2 < 3)
2539           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2540                              DAG.getConstant(3 - Log2, DL, VT));
2541         if (Log2 > 3)
2542           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2543                              DAG.getConstant(Log2 - 3, DL, VT));
2544         return VLENB;
2545       }
2546       // If the multiplier is a multiple of 8, scale it down to avoid needing
2547       // to shift the VLENB value.
2548       if ((Val % 8) == 0)
2549         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2550                            DAG.getConstant(Val / 8, DL, VT));
2551     }
2552 
2553     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2554                                  DAG.getConstant(3, DL, VT));
2555     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2556   }
2557   case ISD::FP_EXTEND: {
2558     // RVV can only do fp_extend to types double the size as the source. We
2559     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2560     // via f32.
2561     SDLoc DL(Op);
2562     MVT VT = Op.getSimpleValueType();
2563     SDValue Src = Op.getOperand(0);
2564     MVT SrcVT = Src.getSimpleValueType();
2565 
2566     // Prepare any fixed-length vector operands.
2567     MVT ContainerVT = VT;
2568     if (SrcVT.isFixedLengthVector()) {
2569       ContainerVT = getContainerForFixedLengthVector(VT);
2570       MVT SrcContainerVT =
2571           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2572       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2573     }
2574 
2575     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2576         SrcVT.getVectorElementType() != MVT::f16) {
2577       // For scalable vectors, we only need to close the gap between
2578       // vXf16->vXf64.
2579       if (!VT.isFixedLengthVector())
2580         return Op;
2581       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2582       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2583       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2584     }
2585 
2586     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2587     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2588     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2589         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2590 
2591     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2592                                            DL, DAG, Subtarget);
2593     if (VT.isFixedLengthVector())
2594       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2595     return Extend;
2596   }
2597   case ISD::FP_ROUND: {
2598     // RVV can only do fp_round to types half the size as the source. We
2599     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2600     // conversion instruction.
2601     SDLoc DL(Op);
2602     MVT VT = Op.getSimpleValueType();
2603     SDValue Src = Op.getOperand(0);
2604     MVT SrcVT = Src.getSimpleValueType();
2605 
2606     // Prepare any fixed-length vector operands.
2607     MVT ContainerVT = VT;
2608     if (VT.isFixedLengthVector()) {
2609       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2610       ContainerVT =
2611           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2612       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2613     }
2614 
2615     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2616         SrcVT.getVectorElementType() != MVT::f64) {
2617       // For scalable vectors, we only need to close the gap between
2618       // vXf64<->vXf16.
2619       if (!VT.isFixedLengthVector())
2620         return Op;
2621       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2622       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2623       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2624     }
2625 
2626     SDValue Mask, VL;
2627     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2628 
2629     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2630     SDValue IntermediateRound =
2631         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2632     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2633                                           DL, DAG, Subtarget);
2634 
2635     if (VT.isFixedLengthVector())
2636       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2637     return Round;
2638   }
2639   case ISD::FP_TO_SINT:
2640   case ISD::FP_TO_UINT:
2641   case ISD::SINT_TO_FP:
2642   case ISD::UINT_TO_FP: {
2643     // RVV can only do fp<->int conversions to types half/double the size as
2644     // the source. We custom-lower any conversions that do two hops into
2645     // sequences.
2646     MVT VT = Op.getSimpleValueType();
2647     if (!VT.isVector())
2648       return Op;
2649     SDLoc DL(Op);
2650     SDValue Src = Op.getOperand(0);
2651     MVT EltVT = VT.getVectorElementType();
2652     MVT SrcVT = Src.getSimpleValueType();
2653     MVT SrcEltVT = SrcVT.getVectorElementType();
2654     unsigned EltSize = EltVT.getSizeInBits();
2655     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2656     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2657            "Unexpected vector element types");
2658 
2659     bool IsInt2FP = SrcEltVT.isInteger();
2660     // Widening conversions
2661     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2662       if (IsInt2FP) {
2663         // Do a regular integer sign/zero extension then convert to float.
2664         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2665                                       VT.getVectorElementCount());
2666         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2667                                  ? ISD::ZERO_EXTEND
2668                                  : ISD::SIGN_EXTEND;
2669         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2670         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2671       }
2672       // FP2Int
2673       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2674       // Do one doubling fp_extend then complete the operation by converting
2675       // to int.
2676       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2677       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2678       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2679     }
2680 
2681     // Narrowing conversions
2682     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2683       if (IsInt2FP) {
2684         // One narrowing int_to_fp, then an fp_round.
2685         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2686         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2687         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2688         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2689       }
2690       // FP2Int
2691       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2692       // representable by the integer, the result is poison.
2693       MVT IVecVT =
2694           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2695                            VT.getVectorElementCount());
2696       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2697       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2698     }
2699 
2700     // Scalable vectors can exit here. Patterns will handle equally-sized
2701     // conversions halving/doubling ones.
2702     if (!VT.isFixedLengthVector())
2703       return Op;
2704 
2705     // For fixed-length vectors we lower to a custom "VL" node.
2706     unsigned RVVOpc = 0;
2707     switch (Op.getOpcode()) {
2708     default:
2709       llvm_unreachable("Impossible opcode");
2710     case ISD::FP_TO_SINT:
2711       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2712       break;
2713     case ISD::FP_TO_UINT:
2714       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2715       break;
2716     case ISD::SINT_TO_FP:
2717       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2718       break;
2719     case ISD::UINT_TO_FP:
2720       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2721       break;
2722     }
2723 
2724     MVT ContainerVT, SrcContainerVT;
2725     // Derive the reference container type from the larger vector type.
2726     if (SrcEltSize > EltSize) {
2727       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2728       ContainerVT =
2729           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2730     } else {
2731       ContainerVT = getContainerForFixedLengthVector(VT);
2732       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2733     }
2734 
2735     SDValue Mask, VL;
2736     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2737 
2738     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2739     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2740     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2741   }
2742   case ISD::FP_TO_SINT_SAT:
2743   case ISD::FP_TO_UINT_SAT:
2744     return lowerFP_TO_INT_SAT(Op, DAG);
2745   case ISD::VECREDUCE_ADD:
2746   case ISD::VECREDUCE_UMAX:
2747   case ISD::VECREDUCE_SMAX:
2748   case ISD::VECREDUCE_UMIN:
2749   case ISD::VECREDUCE_SMIN:
2750     return lowerVECREDUCE(Op, DAG);
2751   case ISD::VECREDUCE_AND:
2752   case ISD::VECREDUCE_OR:
2753   case ISD::VECREDUCE_XOR:
2754     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2755       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
2756     return lowerVECREDUCE(Op, DAG);
2757   case ISD::VECREDUCE_FADD:
2758   case ISD::VECREDUCE_SEQ_FADD:
2759   case ISD::VECREDUCE_FMIN:
2760   case ISD::VECREDUCE_FMAX:
2761     return lowerFPVECREDUCE(Op, DAG);
2762   case ISD::VP_REDUCE_ADD:
2763   case ISD::VP_REDUCE_UMAX:
2764   case ISD::VP_REDUCE_SMAX:
2765   case ISD::VP_REDUCE_UMIN:
2766   case ISD::VP_REDUCE_SMIN:
2767   case ISD::VP_REDUCE_FADD:
2768   case ISD::VP_REDUCE_SEQ_FADD:
2769   case ISD::VP_REDUCE_FMIN:
2770   case ISD::VP_REDUCE_FMAX:
2771     return lowerVPREDUCE(Op, DAG);
2772   case ISD::VP_REDUCE_AND:
2773   case ISD::VP_REDUCE_OR:
2774   case ISD::VP_REDUCE_XOR:
2775     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
2776       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
2777     return lowerVPREDUCE(Op, DAG);
2778   case ISD::INSERT_SUBVECTOR:
2779     return lowerINSERT_SUBVECTOR(Op, DAG);
2780   case ISD::EXTRACT_SUBVECTOR:
2781     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2782   case ISD::STEP_VECTOR:
2783     return lowerSTEP_VECTOR(Op, DAG);
2784   case ISD::VECTOR_REVERSE:
2785     return lowerVECTOR_REVERSE(Op, DAG);
2786   case ISD::BUILD_VECTOR:
2787     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2788   case ISD::SPLAT_VECTOR:
2789     if (Op.getValueType().getVectorElementType() == MVT::i1)
2790       return lowerVectorMaskSplat(Op, DAG);
2791     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2792   case ISD::VECTOR_SHUFFLE:
2793     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2794   case ISD::CONCAT_VECTORS: {
2795     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2796     // better than going through the stack, as the default expansion does.
2797     SDLoc DL(Op);
2798     MVT VT = Op.getSimpleValueType();
2799     unsigned NumOpElts =
2800         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2801     SDValue Vec = DAG.getUNDEF(VT);
2802     for (const auto &OpIdx : enumerate(Op->ops()))
2803       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2804                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2805     return Vec;
2806   }
2807   case ISD::LOAD:
2808     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2809       return V;
2810     if (Op.getValueType().isFixedLengthVector())
2811       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2812     return Op;
2813   case ISD::STORE:
2814     if (auto V = expandUnalignedRVVStore(Op, DAG))
2815       return V;
2816     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2817       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2818     return Op;
2819   case ISD::MLOAD:
2820   case ISD::VP_LOAD:
2821     return lowerMaskedLoad(Op, DAG);
2822   case ISD::MSTORE:
2823   case ISD::VP_STORE:
2824     return lowerMaskedStore(Op, DAG);
2825   case ISD::SETCC:
2826     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2827   case ISD::ADD:
2828     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2829   case ISD::SUB:
2830     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2831   case ISD::MUL:
2832     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2833   case ISD::MULHS:
2834     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2835   case ISD::MULHU:
2836     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2837   case ISD::AND:
2838     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2839                                               RISCVISD::AND_VL);
2840   case ISD::OR:
2841     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2842                                               RISCVISD::OR_VL);
2843   case ISD::XOR:
2844     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2845                                               RISCVISD::XOR_VL);
2846   case ISD::SDIV:
2847     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2848   case ISD::SREM:
2849     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2850   case ISD::UDIV:
2851     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2852   case ISD::UREM:
2853     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2854   case ISD::SHL:
2855   case ISD::SRA:
2856   case ISD::SRL:
2857     if (Op.getSimpleValueType().isFixedLengthVector())
2858       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2859     // This can be called for an i32 shift amount that needs to be promoted.
2860     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2861            "Unexpected custom legalisation");
2862     return SDValue();
2863   case ISD::SADDSAT:
2864     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2865   case ISD::UADDSAT:
2866     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2867   case ISD::SSUBSAT:
2868     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2869   case ISD::USUBSAT:
2870     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2871   case ISD::FADD:
2872     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2873   case ISD::FSUB:
2874     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2875   case ISD::FMUL:
2876     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2877   case ISD::FDIV:
2878     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2879   case ISD::FNEG:
2880     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2881   case ISD::FABS:
2882     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2883   case ISD::FSQRT:
2884     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2885   case ISD::FMA:
2886     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2887   case ISD::SMIN:
2888     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2889   case ISD::SMAX:
2890     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2891   case ISD::UMIN:
2892     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2893   case ISD::UMAX:
2894     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2895   case ISD::FMINNUM:
2896     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2897   case ISD::FMAXNUM:
2898     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2899   case ISD::ABS:
2900     return lowerABS(Op, DAG);
2901   case ISD::VSELECT:
2902     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2903   case ISD::FCOPYSIGN:
2904     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2905   case ISD::MGATHER:
2906   case ISD::VP_GATHER:
2907     return lowerMaskedGather(Op, DAG);
2908   case ISD::MSCATTER:
2909   case ISD::VP_SCATTER:
2910     return lowerMaskedScatter(Op, DAG);
2911   case ISD::FLT_ROUNDS_:
2912     return lowerGET_ROUNDING(Op, DAG);
2913   case ISD::SET_ROUNDING:
2914     return lowerSET_ROUNDING(Op, DAG);
2915   case ISD::VP_ADD:
2916     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2917   case ISD::VP_SUB:
2918     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2919   case ISD::VP_MUL:
2920     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2921   case ISD::VP_SDIV:
2922     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2923   case ISD::VP_UDIV:
2924     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2925   case ISD::VP_SREM:
2926     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2927   case ISD::VP_UREM:
2928     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2929   case ISD::VP_AND:
2930     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2931   case ISD::VP_OR:
2932     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2933   case ISD::VP_XOR:
2934     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2935   case ISD::VP_ASHR:
2936     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2937   case ISD::VP_LSHR:
2938     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2939   case ISD::VP_SHL:
2940     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2941   case ISD::VP_FADD:
2942     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2943   case ISD::VP_FSUB:
2944     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2945   case ISD::VP_FMUL:
2946     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2947   case ISD::VP_FDIV:
2948     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2949   }
2950 }
2951 
2952 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2953                              SelectionDAG &DAG, unsigned Flags) {
2954   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2955 }
2956 
2957 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2958                              SelectionDAG &DAG, unsigned Flags) {
2959   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2960                                    Flags);
2961 }
2962 
2963 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2964                              SelectionDAG &DAG, unsigned Flags) {
2965   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2966                                    N->getOffset(), Flags);
2967 }
2968 
2969 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2970                              SelectionDAG &DAG, unsigned Flags) {
2971   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2972 }
2973 
2974 template <class NodeTy>
2975 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
2976                                      bool IsLocal) const {
2977   SDLoc DL(N);
2978   EVT Ty = getPointerTy(DAG.getDataLayout());
2979 
2980   if (isPositionIndependent()) {
2981     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2982     if (IsLocal)
2983       // Use PC-relative addressing to access the symbol. This generates the
2984       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
2985       // %pcrel_lo(auipc)).
2986       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2987 
2988     // Use PC-relative addressing to access the GOT for this symbol, then load
2989     // the address from the GOT. This generates the pattern (PseudoLA sym),
2990     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
2991     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
2992   }
2993 
2994   switch (getTargetMachine().getCodeModel()) {
2995   default:
2996     report_fatal_error("Unsupported code model for lowering");
2997   case CodeModel::Small: {
2998     // Generate a sequence for accessing addresses within the first 2 GiB of
2999     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3000     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3001     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3002     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3003     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3004   }
3005   case CodeModel::Medium: {
3006     // Generate a sequence for accessing addresses within any 2GiB range within
3007     // the address space. This generates the pattern (PseudoLLA sym), which
3008     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3009     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3010     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3011   }
3012   }
3013 }
3014 
3015 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3016                                                 SelectionDAG &DAG) const {
3017   SDLoc DL(Op);
3018   EVT Ty = Op.getValueType();
3019   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3020   int64_t Offset = N->getOffset();
3021   MVT XLenVT = Subtarget.getXLenVT();
3022 
3023   const GlobalValue *GV = N->getGlobal();
3024   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3025   SDValue Addr = getAddr(N, DAG, IsLocal);
3026 
3027   // In order to maximise the opportunity for common subexpression elimination,
3028   // emit a separate ADD node for the global address offset instead of folding
3029   // it in the global address node. Later peephole optimisations may choose to
3030   // fold it back in when profitable.
3031   if (Offset != 0)
3032     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3033                        DAG.getConstant(Offset, DL, XLenVT));
3034   return Addr;
3035 }
3036 
3037 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3038                                                SelectionDAG &DAG) const {
3039   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3040 
3041   return getAddr(N, DAG);
3042 }
3043 
3044 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3045                                                SelectionDAG &DAG) const {
3046   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3047 
3048   return getAddr(N, DAG);
3049 }
3050 
3051 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3052                                             SelectionDAG &DAG) const {
3053   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3054 
3055   return getAddr(N, DAG);
3056 }
3057 
3058 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3059                                               SelectionDAG &DAG,
3060                                               bool UseGOT) const {
3061   SDLoc DL(N);
3062   EVT Ty = getPointerTy(DAG.getDataLayout());
3063   const GlobalValue *GV = N->getGlobal();
3064   MVT XLenVT = Subtarget.getXLenVT();
3065 
3066   if (UseGOT) {
3067     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3068     // load the address from the GOT and add the thread pointer. This generates
3069     // the pattern (PseudoLA_TLS_IE sym), which expands to
3070     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3071     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3072     SDValue Load =
3073         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3074 
3075     // Add the thread pointer.
3076     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3077     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3078   }
3079 
3080   // Generate a sequence for accessing the address relative to the thread
3081   // pointer, with the appropriate adjustment for the thread pointer offset.
3082   // This generates the pattern
3083   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3084   SDValue AddrHi =
3085       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3086   SDValue AddrAdd =
3087       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3088   SDValue AddrLo =
3089       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3090 
3091   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3092   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3093   SDValue MNAdd = SDValue(
3094       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3095       0);
3096   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3097 }
3098 
3099 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3100                                                SelectionDAG &DAG) const {
3101   SDLoc DL(N);
3102   EVT Ty = getPointerTy(DAG.getDataLayout());
3103   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3104   const GlobalValue *GV = N->getGlobal();
3105 
3106   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3107   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3108   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3109   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3110   SDValue Load =
3111       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3112 
3113   // Prepare argument list to generate call.
3114   ArgListTy Args;
3115   ArgListEntry Entry;
3116   Entry.Node = Load;
3117   Entry.Ty = CallTy;
3118   Args.push_back(Entry);
3119 
3120   // Setup call to __tls_get_addr.
3121   TargetLowering::CallLoweringInfo CLI(DAG);
3122   CLI.setDebugLoc(DL)
3123       .setChain(DAG.getEntryNode())
3124       .setLibCallee(CallingConv::C, CallTy,
3125                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3126                     std::move(Args));
3127 
3128   return LowerCallTo(CLI).first;
3129 }
3130 
3131 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3132                                                    SelectionDAG &DAG) const {
3133   SDLoc DL(Op);
3134   EVT Ty = Op.getValueType();
3135   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3136   int64_t Offset = N->getOffset();
3137   MVT XLenVT = Subtarget.getXLenVT();
3138 
3139   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3140 
3141   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3142       CallingConv::GHC)
3143     report_fatal_error("In GHC calling convention TLS is not supported");
3144 
3145   SDValue Addr;
3146   switch (Model) {
3147   case TLSModel::LocalExec:
3148     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3149     break;
3150   case TLSModel::InitialExec:
3151     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3152     break;
3153   case TLSModel::LocalDynamic:
3154   case TLSModel::GeneralDynamic:
3155     Addr = getDynamicTLSAddr(N, DAG);
3156     break;
3157   }
3158 
3159   // In order to maximise the opportunity for common subexpression elimination,
3160   // emit a separate ADD node for the global address offset instead of folding
3161   // it in the global address node. Later peephole optimisations may choose to
3162   // fold it back in when profitable.
3163   if (Offset != 0)
3164     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3165                        DAG.getConstant(Offset, DL, XLenVT));
3166   return Addr;
3167 }
3168 
3169 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3170   SDValue CondV = Op.getOperand(0);
3171   SDValue TrueV = Op.getOperand(1);
3172   SDValue FalseV = Op.getOperand(2);
3173   SDLoc DL(Op);
3174   MVT VT = Op.getSimpleValueType();
3175   MVT XLenVT = Subtarget.getXLenVT();
3176 
3177   // Lower vector SELECTs to VSELECTs by splatting the condition.
3178   if (VT.isVector()) {
3179     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3180     SDValue CondSplat = VT.isScalableVector()
3181                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3182                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3183     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3184   }
3185 
3186   // If the result type is XLenVT and CondV is the output of a SETCC node
3187   // which also operated on XLenVT inputs, then merge the SETCC node into the
3188   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3189   // compare+branch instructions. i.e.:
3190   // (select (setcc lhs, rhs, cc), truev, falsev)
3191   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3192   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3193       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3194     SDValue LHS = CondV.getOperand(0);
3195     SDValue RHS = CondV.getOperand(1);
3196     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3197     ISD::CondCode CCVal = CC->get();
3198 
3199     // Special case for a select of 2 constants that have a diffence of 1.
3200     // Normally this is done by DAGCombine, but if the select is introduced by
3201     // type legalization or op legalization, we miss it. Restricting to SETLT
3202     // case for now because that is what signed saturating add/sub need.
3203     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3204     // but we would probably want to swap the true/false values if the condition
3205     // is SETGE/SETLE to avoid an XORI.
3206     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3207         CCVal == ISD::SETLT) {
3208       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3209       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3210       if (TrueVal - 1 == FalseVal)
3211         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3212       if (TrueVal + 1 == FalseVal)
3213         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3214     }
3215 
3216     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3217 
3218     SDValue TargetCC = DAG.getCondCode(CCVal);
3219     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3220     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3221   }
3222 
3223   // Otherwise:
3224   // (select condv, truev, falsev)
3225   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3226   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3227   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3228 
3229   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3230 
3231   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3232 }
3233 
3234 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3235   SDValue CondV = Op.getOperand(1);
3236   SDLoc DL(Op);
3237   MVT XLenVT = Subtarget.getXLenVT();
3238 
3239   if (CondV.getOpcode() == ISD::SETCC &&
3240       CondV.getOperand(0).getValueType() == XLenVT) {
3241     SDValue LHS = CondV.getOperand(0);
3242     SDValue RHS = CondV.getOperand(1);
3243     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3244 
3245     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3246 
3247     SDValue TargetCC = DAG.getCondCode(CCVal);
3248     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3249                        LHS, RHS, TargetCC, Op.getOperand(2));
3250   }
3251 
3252   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3253                      CondV, DAG.getConstant(0, DL, XLenVT),
3254                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3255 }
3256 
3257 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3258   MachineFunction &MF = DAG.getMachineFunction();
3259   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3260 
3261   SDLoc DL(Op);
3262   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3263                                  getPointerTy(MF.getDataLayout()));
3264 
3265   // vastart just stores the address of the VarArgsFrameIndex slot into the
3266   // memory location argument.
3267   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3268   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3269                       MachinePointerInfo(SV));
3270 }
3271 
3272 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3273                                             SelectionDAG &DAG) const {
3274   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3275   MachineFunction &MF = DAG.getMachineFunction();
3276   MachineFrameInfo &MFI = MF.getFrameInfo();
3277   MFI.setFrameAddressIsTaken(true);
3278   Register FrameReg = RI.getFrameRegister(MF);
3279   int XLenInBytes = Subtarget.getXLen() / 8;
3280 
3281   EVT VT = Op.getValueType();
3282   SDLoc DL(Op);
3283   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3284   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3285   while (Depth--) {
3286     int Offset = -(XLenInBytes * 2);
3287     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3288                               DAG.getIntPtrConstant(Offset, DL));
3289     FrameAddr =
3290         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3291   }
3292   return FrameAddr;
3293 }
3294 
3295 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3296                                              SelectionDAG &DAG) const {
3297   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3298   MachineFunction &MF = DAG.getMachineFunction();
3299   MachineFrameInfo &MFI = MF.getFrameInfo();
3300   MFI.setReturnAddressIsTaken(true);
3301   MVT XLenVT = Subtarget.getXLenVT();
3302   int XLenInBytes = Subtarget.getXLen() / 8;
3303 
3304   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3305     return SDValue();
3306 
3307   EVT VT = Op.getValueType();
3308   SDLoc DL(Op);
3309   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3310   if (Depth) {
3311     int Off = -XLenInBytes;
3312     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3313     SDValue Offset = DAG.getConstant(Off, DL, VT);
3314     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3315                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3316                        MachinePointerInfo());
3317   }
3318 
3319   // Return the value of the return address register, marking it an implicit
3320   // live-in.
3321   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3322   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3323 }
3324 
3325 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3326                                                  SelectionDAG &DAG) const {
3327   SDLoc DL(Op);
3328   SDValue Lo = Op.getOperand(0);
3329   SDValue Hi = Op.getOperand(1);
3330   SDValue Shamt = Op.getOperand(2);
3331   EVT VT = Lo.getValueType();
3332 
3333   // if Shamt-XLEN < 0: // Shamt < XLEN
3334   //   Lo = Lo << Shamt
3335   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3336   // else:
3337   //   Lo = 0
3338   //   Hi = Lo << (Shamt-XLEN)
3339 
3340   SDValue Zero = DAG.getConstant(0, DL, VT);
3341   SDValue One = DAG.getConstant(1, DL, VT);
3342   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3343   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3344   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3345   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3346 
3347   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3348   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3349   SDValue ShiftRightLo =
3350       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3351   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3352   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3353   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3354 
3355   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3356 
3357   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3358   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3359 
3360   SDValue Parts[2] = {Lo, Hi};
3361   return DAG.getMergeValues(Parts, DL);
3362 }
3363 
3364 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3365                                                   bool IsSRA) const {
3366   SDLoc DL(Op);
3367   SDValue Lo = Op.getOperand(0);
3368   SDValue Hi = Op.getOperand(1);
3369   SDValue Shamt = Op.getOperand(2);
3370   EVT VT = Lo.getValueType();
3371 
3372   // SRA expansion:
3373   //   if Shamt-XLEN < 0: // Shamt < XLEN
3374   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3375   //     Hi = Hi >>s Shamt
3376   //   else:
3377   //     Lo = Hi >>s (Shamt-XLEN);
3378   //     Hi = Hi >>s (XLEN-1)
3379   //
3380   // SRL expansion:
3381   //   if Shamt-XLEN < 0: // Shamt < XLEN
3382   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3383   //     Hi = Hi >>u Shamt
3384   //   else:
3385   //     Lo = Hi >>u (Shamt-XLEN);
3386   //     Hi = 0;
3387 
3388   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3389 
3390   SDValue Zero = DAG.getConstant(0, DL, VT);
3391   SDValue One = DAG.getConstant(1, DL, VT);
3392   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3393   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3394   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3395   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3396 
3397   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3398   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3399   SDValue ShiftLeftHi =
3400       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3401   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3402   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3403   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3404   SDValue HiFalse =
3405       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3406 
3407   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3408 
3409   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3410   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3411 
3412   SDValue Parts[2] = {Lo, Hi};
3413   return DAG.getMergeValues(Parts, DL);
3414 }
3415 
3416 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3417 // legal equivalently-sized i8 type, so we can use that as a go-between.
3418 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3419                                                   SelectionDAG &DAG) const {
3420   SDLoc DL(Op);
3421   MVT VT = Op.getSimpleValueType();
3422   SDValue SplatVal = Op.getOperand(0);
3423   // All-zeros or all-ones splats are handled specially.
3424   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3425     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3426     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3427   }
3428   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3429     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3430     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3431   }
3432   MVT XLenVT = Subtarget.getXLenVT();
3433   assert(SplatVal.getValueType() == XLenVT &&
3434          "Unexpected type for i1 splat value");
3435   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3436   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3437                          DAG.getConstant(1, DL, XLenVT));
3438   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3439   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3440   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3441 }
3442 
3443 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3444 // illegal (currently only vXi64 RV32).
3445 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3446 // them to SPLAT_VECTOR_I64
3447 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3448                                                      SelectionDAG &DAG) const {
3449   SDLoc DL(Op);
3450   MVT VecVT = Op.getSimpleValueType();
3451   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3452          "Unexpected SPLAT_VECTOR_PARTS lowering");
3453 
3454   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3455   SDValue Lo = Op.getOperand(0);
3456   SDValue Hi = Op.getOperand(1);
3457 
3458   if (VecVT.isFixedLengthVector()) {
3459     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3460     SDLoc DL(Op);
3461     SDValue Mask, VL;
3462     std::tie(Mask, VL) =
3463         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3464 
3465     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3466     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3467   }
3468 
3469   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3470     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3471     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3472     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3473     // node in order to try and match RVV vector/scalar instructions.
3474     if ((LoC >> 31) == HiC)
3475       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3476   }
3477 
3478   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3479   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3480       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3481       Hi.getConstantOperandVal(1) == 31)
3482     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3483 
3484   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3485   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3486                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3487 }
3488 
3489 // Custom-lower extensions from mask vectors by using a vselect either with 1
3490 // for zero/any-extension or -1 for sign-extension:
3491 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3492 // Note that any-extension is lowered identically to zero-extension.
3493 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3494                                                 int64_t ExtTrueVal) const {
3495   SDLoc DL(Op);
3496   MVT VecVT = Op.getSimpleValueType();
3497   SDValue Src = Op.getOperand(0);
3498   // Only custom-lower extensions from mask types
3499   assert(Src.getValueType().isVector() &&
3500          Src.getValueType().getVectorElementType() == MVT::i1);
3501 
3502   MVT XLenVT = Subtarget.getXLenVT();
3503   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3504   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3505 
3506   if (VecVT.isScalableVector()) {
3507     // Be careful not to introduce illegal scalar types at this stage, and be
3508     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3509     // illegal and must be expanded. Since we know that the constants are
3510     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3511     bool IsRV32E64 =
3512         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3513 
3514     if (!IsRV32E64) {
3515       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3516       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3517     } else {
3518       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3519       SplatTrueVal =
3520           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3521     }
3522 
3523     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3524   }
3525 
3526   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3527   MVT I1ContainerVT =
3528       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3529 
3530   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3531 
3532   SDValue Mask, VL;
3533   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3534 
3535   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3536   SplatTrueVal =
3537       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3538   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3539                                SplatTrueVal, SplatZero, VL);
3540 
3541   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3542 }
3543 
3544 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3545     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3546   MVT ExtVT = Op.getSimpleValueType();
3547   // Only custom-lower extensions from fixed-length vector types.
3548   if (!ExtVT.isFixedLengthVector())
3549     return Op;
3550   MVT VT = Op.getOperand(0).getSimpleValueType();
3551   // Grab the canonical container type for the extended type. Infer the smaller
3552   // type from that to ensure the same number of vector elements, as we know
3553   // the LMUL will be sufficient to hold the smaller type.
3554   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3555   // Get the extended container type manually to ensure the same number of
3556   // vector elements between source and dest.
3557   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3558                                      ContainerExtVT.getVectorElementCount());
3559 
3560   SDValue Op1 =
3561       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3562 
3563   SDLoc DL(Op);
3564   SDValue Mask, VL;
3565   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3566 
3567   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3568 
3569   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3570 }
3571 
3572 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3573 // setcc operation:
3574 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3575 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3576                                                   SelectionDAG &DAG) const {
3577   SDLoc DL(Op);
3578   EVT MaskVT = Op.getValueType();
3579   // Only expect to custom-lower truncations to mask types
3580   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3581          "Unexpected type for vector mask lowering");
3582   SDValue Src = Op.getOperand(0);
3583   MVT VecVT = Src.getSimpleValueType();
3584 
3585   // If this is a fixed vector, we need to convert it to a scalable vector.
3586   MVT ContainerVT = VecVT;
3587   if (VecVT.isFixedLengthVector()) {
3588     ContainerVT = getContainerForFixedLengthVector(VecVT);
3589     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3590   }
3591 
3592   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3593   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3594 
3595   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3596   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3597 
3598   if (VecVT.isScalableVector()) {
3599     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3600     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3601   }
3602 
3603   SDValue Mask, VL;
3604   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3605 
3606   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3607   SDValue Trunc =
3608       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3609   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3610                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3611   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3612 }
3613 
3614 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3615 // first position of a vector, and that vector is slid up to the insert index.
3616 // By limiting the active vector length to index+1 and merging with the
3617 // original vector (with an undisturbed tail policy for elements >= VL), we
3618 // achieve the desired result of leaving all elements untouched except the one
3619 // at VL-1, which is replaced with the desired value.
3620 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3621                                                     SelectionDAG &DAG) const {
3622   SDLoc DL(Op);
3623   MVT VecVT = Op.getSimpleValueType();
3624   SDValue Vec = Op.getOperand(0);
3625   SDValue Val = Op.getOperand(1);
3626   SDValue Idx = Op.getOperand(2);
3627 
3628   if (VecVT.getVectorElementType() == MVT::i1) {
3629     // FIXME: For now we just promote to an i8 vector and insert into that,
3630     // but this is probably not optimal.
3631     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3632     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3633     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3634     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3635   }
3636 
3637   MVT ContainerVT = VecVT;
3638   // If the operand is a fixed-length vector, convert to a scalable one.
3639   if (VecVT.isFixedLengthVector()) {
3640     ContainerVT = getContainerForFixedLengthVector(VecVT);
3641     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3642   }
3643 
3644   MVT XLenVT = Subtarget.getXLenVT();
3645 
3646   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3647   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3648   // Even i64-element vectors on RV32 can be lowered without scalar
3649   // legalization if the most-significant 32 bits of the value are not affected
3650   // by the sign-extension of the lower 32 bits.
3651   // TODO: We could also catch sign extensions of a 32-bit value.
3652   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3653     const auto *CVal = cast<ConstantSDNode>(Val);
3654     if (isInt<32>(CVal->getSExtValue())) {
3655       IsLegalInsert = true;
3656       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3657     }
3658   }
3659 
3660   SDValue Mask, VL;
3661   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3662 
3663   SDValue ValInVec;
3664 
3665   if (IsLegalInsert) {
3666     unsigned Opc =
3667         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3668     if (isNullConstant(Idx)) {
3669       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3670       if (!VecVT.isFixedLengthVector())
3671         return Vec;
3672       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3673     }
3674     ValInVec =
3675         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3676   } else {
3677     // On RV32, i64-element vectors must be specially handled to place the
3678     // value at element 0, by using two vslide1up instructions in sequence on
3679     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3680     // this.
3681     SDValue One = DAG.getConstant(1, DL, XLenVT);
3682     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3683     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3684     MVT I32ContainerVT =
3685         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3686     SDValue I32Mask =
3687         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3688     // Limit the active VL to two.
3689     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3690     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3691     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3692     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3693                            InsertI64VL);
3694     // First slide in the hi value, then the lo in underneath it.
3695     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3696                            ValHi, I32Mask, InsertI64VL);
3697     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3698                            ValLo, I32Mask, InsertI64VL);
3699     // Bitcast back to the right container type.
3700     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3701   }
3702 
3703   // Now that the value is in a vector, slide it into position.
3704   SDValue InsertVL =
3705       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3706   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3707                                 ValInVec, Idx, Mask, InsertVL);
3708   if (!VecVT.isFixedLengthVector())
3709     return Slideup;
3710   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3711 }
3712 
3713 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3714 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3715 // types this is done using VMV_X_S to allow us to glean information about the
3716 // sign bits of the result.
3717 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3718                                                      SelectionDAG &DAG) const {
3719   SDLoc DL(Op);
3720   SDValue Idx = Op.getOperand(1);
3721   SDValue Vec = Op.getOperand(0);
3722   EVT EltVT = Op.getValueType();
3723   MVT VecVT = Vec.getSimpleValueType();
3724   MVT XLenVT = Subtarget.getXLenVT();
3725 
3726   if (VecVT.getVectorElementType() == MVT::i1) {
3727     // FIXME: For now we just promote to an i8 vector and extract from that,
3728     // but this is probably not optimal.
3729     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3730     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3731     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3732   }
3733 
3734   // If this is a fixed vector, we need to convert it to a scalable vector.
3735   MVT ContainerVT = VecVT;
3736   if (VecVT.isFixedLengthVector()) {
3737     ContainerVT = getContainerForFixedLengthVector(VecVT);
3738     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3739   }
3740 
3741   // If the index is 0, the vector is already in the right position.
3742   if (!isNullConstant(Idx)) {
3743     // Use a VL of 1 to avoid processing more elements than we need.
3744     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3745     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3746     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3747     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3748                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3749   }
3750 
3751   if (!EltVT.isInteger()) {
3752     // Floating-point extracts are handled in TableGen.
3753     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3754                        DAG.getConstant(0, DL, XLenVT));
3755   }
3756 
3757   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3758   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3759 }
3760 
3761 // Some RVV intrinsics may claim that they want an integer operand to be
3762 // promoted or expanded.
3763 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3764                                           const RISCVSubtarget &Subtarget) {
3765   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3766           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3767          "Unexpected opcode");
3768 
3769   if (!Subtarget.hasStdExtV())
3770     return SDValue();
3771 
3772   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3773   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3774   SDLoc DL(Op);
3775 
3776   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3777       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3778   if (!II || !II->SplatOperand)
3779     return SDValue();
3780 
3781   unsigned SplatOp = II->SplatOperand + HasChain;
3782   assert(SplatOp < Op.getNumOperands());
3783 
3784   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3785   SDValue &ScalarOp = Operands[SplatOp];
3786   MVT OpVT = ScalarOp.getSimpleValueType();
3787   MVT XLenVT = Subtarget.getXLenVT();
3788 
3789   // If this isn't a scalar, or its type is XLenVT we're done.
3790   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3791     return SDValue();
3792 
3793   // Simplest case is that the operand needs to be promoted to XLenVT.
3794   if (OpVT.bitsLT(XLenVT)) {
3795     // If the operand is a constant, sign extend to increase our chances
3796     // of being able to use a .vi instruction. ANY_EXTEND would become a
3797     // a zero extend and the simm5 check in isel would fail.
3798     // FIXME: Should we ignore the upper bits in isel instead?
3799     unsigned ExtOpc =
3800         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3801     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3802     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3803   }
3804 
3805   // Use the previous operand to get the vXi64 VT. The result might be a mask
3806   // VT for compares. Using the previous operand assumes that the previous
3807   // operand will never have a smaller element size than a scalar operand and
3808   // that a widening operation never uses SEW=64.
3809   // NOTE: If this fails the below assert, we can probably just find the
3810   // element count from any operand or result and use it to construct the VT.
3811   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3812   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3813 
3814   // The more complex case is when the scalar is larger than XLenVT.
3815   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3816          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3817 
3818   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3819   // on the instruction to sign-extend since SEW>XLEN.
3820   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3821     if (isInt<32>(CVal->getSExtValue())) {
3822       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3823       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3824     }
3825   }
3826 
3827   // We need to convert the scalar to a splat vector.
3828   // FIXME: Can we implicitly truncate the scalar if it is known to
3829   // be sign extended?
3830   // VL should be the last operand.
3831   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3832   assert(VL.getValueType() == XLenVT);
3833   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3834   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3835 }
3836 
3837 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3838                                                      SelectionDAG &DAG) const {
3839   unsigned IntNo = Op.getConstantOperandVal(0);
3840   SDLoc DL(Op);
3841   MVT XLenVT = Subtarget.getXLenVT();
3842 
3843   switch (IntNo) {
3844   default:
3845     break; // Don't custom lower most intrinsics.
3846   case Intrinsic::thread_pointer: {
3847     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3848     return DAG.getRegister(RISCV::X4, PtrVT);
3849   }
3850   case Intrinsic::riscv_orc_b:
3851     // Lower to the GORCI encoding for orc.b.
3852     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3853                        DAG.getConstant(7, DL, XLenVT));
3854   case Intrinsic::riscv_grev:
3855   case Intrinsic::riscv_gorc: {
3856     unsigned Opc =
3857         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3858     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3859   }
3860   case Intrinsic::riscv_shfl:
3861   case Intrinsic::riscv_unshfl: {
3862     unsigned Opc =
3863         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3864     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3865   }
3866   case Intrinsic::riscv_bcompress:
3867   case Intrinsic::riscv_bdecompress: {
3868     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3869                                                        : RISCVISD::BDECOMPRESS;
3870     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3871   }
3872   case Intrinsic::riscv_vmv_x_s:
3873     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3874     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3875                        Op.getOperand(1));
3876   case Intrinsic::riscv_vmv_v_x:
3877     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3878                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3879   case Intrinsic::riscv_vfmv_v_f:
3880     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3881                        Op.getOperand(1), Op.getOperand(2));
3882   case Intrinsic::riscv_vmv_s_x: {
3883     SDValue Scalar = Op.getOperand(2);
3884 
3885     if (Scalar.getValueType().bitsLE(XLenVT)) {
3886       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3887       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3888                          Op.getOperand(1), Scalar, Op.getOperand(3));
3889     }
3890 
3891     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3892 
3893     // This is an i64 value that lives in two scalar registers. We have to
3894     // insert this in a convoluted way. First we build vXi64 splat containing
3895     // the/ two values that we assemble using some bit math. Next we'll use
3896     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3897     // to merge element 0 from our splat into the source vector.
3898     // FIXME: This is probably not the best way to do this, but it is
3899     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3900     // point.
3901     //   sw lo, (a0)
3902     //   sw hi, 4(a0)
3903     //   vlse vX, (a0)
3904     //
3905     //   vid.v      vVid
3906     //   vmseq.vx   mMask, vVid, 0
3907     //   vmerge.vvm vDest, vSrc, vVal, mMask
3908     MVT VT = Op.getSimpleValueType();
3909     SDValue Vec = Op.getOperand(1);
3910     SDValue VL = Op.getOperand(3);
3911 
3912     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3913     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3914                                       DAG.getConstant(0, DL, MVT::i32), VL);
3915 
3916     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3917     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3918     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3919     SDValue SelectCond =
3920         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3921                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3922     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3923                        Vec, VL);
3924   }
3925   case Intrinsic::riscv_vslide1up:
3926   case Intrinsic::riscv_vslide1down:
3927   case Intrinsic::riscv_vslide1up_mask:
3928   case Intrinsic::riscv_vslide1down_mask: {
3929     // We need to special case these when the scalar is larger than XLen.
3930     unsigned NumOps = Op.getNumOperands();
3931     bool IsMasked = NumOps == 7;
3932     unsigned OpOffset = IsMasked ? 1 : 0;
3933     SDValue Scalar = Op.getOperand(2 + OpOffset);
3934     if (Scalar.getValueType().bitsLE(XLenVT))
3935       break;
3936 
3937     // Splatting a sign extended constant is fine.
3938     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3939       if (isInt<32>(CVal->getSExtValue()))
3940         break;
3941 
3942     MVT VT = Op.getSimpleValueType();
3943     assert(VT.getVectorElementType() == MVT::i64 &&
3944            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3945 
3946     // Convert the vector source to the equivalent nxvXi32 vector.
3947     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3948     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3949 
3950     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3951                                    DAG.getConstant(0, DL, XLenVT));
3952     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3953                                    DAG.getConstant(1, DL, XLenVT));
3954 
3955     // Double the VL since we halved SEW.
3956     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
3957     SDValue I32VL =
3958         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3959 
3960     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3961     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3962 
3963     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3964     // instructions.
3965     if (IntNo == Intrinsic::riscv_vslide1up ||
3966         IntNo == Intrinsic::riscv_vslide1up_mask) {
3967       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3968                         I32Mask, I32VL);
3969       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3970                         I32Mask, I32VL);
3971     } else {
3972       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3973                         I32Mask, I32VL);
3974       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3975                         I32Mask, I32VL);
3976     }
3977 
3978     // Convert back to nxvXi64.
3979     Vec = DAG.getBitcast(VT, Vec);
3980 
3981     if (!IsMasked)
3982       return Vec;
3983 
3984     // Apply mask after the operation.
3985     SDValue Mask = Op.getOperand(NumOps - 3);
3986     SDValue MaskedOff = Op.getOperand(1);
3987     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
3988   }
3989   }
3990 
3991   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3992 }
3993 
3994 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3995                                                     SelectionDAG &DAG) const {
3996   unsigned IntNo = Op.getConstantOperandVal(1);
3997   switch (IntNo) {
3998   default:
3999     break;
4000   case Intrinsic::riscv_masked_strided_load: {
4001     SDLoc DL(Op);
4002     MVT XLenVT = Subtarget.getXLenVT();
4003 
4004     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4005     // the selection of the masked intrinsics doesn't do this for us.
4006     SDValue Mask = Op.getOperand(5);
4007     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4008 
4009     MVT VT = Op->getSimpleValueType(0);
4010     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4011 
4012     SDValue PassThru = Op.getOperand(2);
4013     if (!IsUnmasked) {
4014       MVT MaskVT =
4015           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4016       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4017       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4018     }
4019 
4020     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4021 
4022     SDValue IntID = DAG.getTargetConstant(
4023         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4024         XLenVT);
4025 
4026     auto *Load = cast<MemIntrinsicSDNode>(Op);
4027     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4028     if (!IsUnmasked)
4029       Ops.push_back(PassThru);
4030     Ops.push_back(Op.getOperand(3)); // Ptr
4031     Ops.push_back(Op.getOperand(4)); // Stride
4032     if (!IsUnmasked)
4033       Ops.push_back(Mask);
4034     Ops.push_back(VL);
4035     if (!IsUnmasked) {
4036       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4037       Ops.push_back(Policy);
4038     }
4039 
4040     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4041     SDValue Result =
4042         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4043                                 Load->getMemoryVT(), Load->getMemOperand());
4044     SDValue Chain = Result.getValue(1);
4045     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4046     return DAG.getMergeValues({Result, Chain}, DL);
4047   }
4048   }
4049 
4050   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4051 }
4052 
4053 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4054                                                  SelectionDAG &DAG) const {
4055   unsigned IntNo = Op.getConstantOperandVal(1);
4056   switch (IntNo) {
4057   default:
4058     break;
4059   case Intrinsic::riscv_masked_strided_store: {
4060     SDLoc DL(Op);
4061     MVT XLenVT = Subtarget.getXLenVT();
4062 
4063     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4064     // the selection of the masked intrinsics doesn't do this for us.
4065     SDValue Mask = Op.getOperand(5);
4066     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4067 
4068     SDValue Val = Op.getOperand(2);
4069     MVT VT = Val.getSimpleValueType();
4070     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4071 
4072     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4073     if (!IsUnmasked) {
4074       MVT MaskVT =
4075           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4076       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4077     }
4078 
4079     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4080 
4081     SDValue IntID = DAG.getTargetConstant(
4082         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4083         XLenVT);
4084 
4085     auto *Store = cast<MemIntrinsicSDNode>(Op);
4086     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4087     Ops.push_back(Val);
4088     Ops.push_back(Op.getOperand(3)); // Ptr
4089     Ops.push_back(Op.getOperand(4)); // Stride
4090     if (!IsUnmasked)
4091       Ops.push_back(Mask);
4092     Ops.push_back(VL);
4093 
4094     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4095                                    Ops, Store->getMemoryVT(),
4096                                    Store->getMemOperand());
4097   }
4098   }
4099 
4100   return SDValue();
4101 }
4102 
4103 static MVT getLMUL1VT(MVT VT) {
4104   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4105          "Unexpected vector MVT");
4106   return MVT::getScalableVectorVT(
4107       VT.getVectorElementType(),
4108       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4109 }
4110 
4111 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4112   switch (ISDOpcode) {
4113   default:
4114     llvm_unreachable("Unhandled reduction");
4115   case ISD::VECREDUCE_ADD:
4116     return RISCVISD::VECREDUCE_ADD_VL;
4117   case ISD::VECREDUCE_UMAX:
4118     return RISCVISD::VECREDUCE_UMAX_VL;
4119   case ISD::VECREDUCE_SMAX:
4120     return RISCVISD::VECREDUCE_SMAX_VL;
4121   case ISD::VECREDUCE_UMIN:
4122     return RISCVISD::VECREDUCE_UMIN_VL;
4123   case ISD::VECREDUCE_SMIN:
4124     return RISCVISD::VECREDUCE_SMIN_VL;
4125   case ISD::VECREDUCE_AND:
4126     return RISCVISD::VECREDUCE_AND_VL;
4127   case ISD::VECREDUCE_OR:
4128     return RISCVISD::VECREDUCE_OR_VL;
4129   case ISD::VECREDUCE_XOR:
4130     return RISCVISD::VECREDUCE_XOR_VL;
4131   }
4132 }
4133 
4134 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4135                                                          SelectionDAG &DAG,
4136                                                          bool IsVP) const {
4137   SDLoc DL(Op);
4138   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4139   MVT VecVT = Vec.getSimpleValueType();
4140   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4141           Op.getOpcode() == ISD::VECREDUCE_OR ||
4142           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4143           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4144           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4145           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4146          "Unexpected reduction lowering");
4147 
4148   MVT XLenVT = Subtarget.getXLenVT();
4149   assert(Op.getValueType() == XLenVT &&
4150          "Expected reduction output to be legalized to XLenVT");
4151 
4152   MVT ContainerVT = VecVT;
4153   if (VecVT.isFixedLengthVector()) {
4154     ContainerVT = getContainerForFixedLengthVector(VecVT);
4155     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4156   }
4157 
4158   SDValue Mask, VL;
4159   if (IsVP) {
4160     Mask = Op.getOperand(2);
4161     VL = Op.getOperand(3);
4162   } else {
4163     std::tie(Mask, VL) =
4164         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4165   }
4166 
4167   unsigned BaseOpc;
4168   ISD::CondCode CC;
4169   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4170 
4171   switch (Op.getOpcode()) {
4172   default:
4173     llvm_unreachable("Unhandled reduction");
4174   case ISD::VECREDUCE_AND:
4175   case ISD::VP_REDUCE_AND: {
4176     // vpopc ~x == 0
4177     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4178     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4179     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4180     CC = ISD::SETEQ;
4181     BaseOpc = ISD::AND;
4182     break;
4183   }
4184   case ISD::VECREDUCE_OR:
4185   case ISD::VP_REDUCE_OR:
4186     // vpopc x != 0
4187     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4188     CC = ISD::SETNE;
4189     BaseOpc = ISD::OR;
4190     break;
4191   case ISD::VECREDUCE_XOR:
4192   case ISD::VP_REDUCE_XOR: {
4193     // ((vpopc x) & 1) != 0
4194     SDValue One = DAG.getConstant(1, DL, XLenVT);
4195     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
4196     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4197     CC = ISD::SETNE;
4198     BaseOpc = ISD::XOR;
4199     break;
4200   }
4201   }
4202 
4203   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4204 
4205   if (!IsVP)
4206     return SetCC;
4207 
4208   // Now include the start value in the operation.
4209   // Note that we must return the start value when no elements are operated
4210   // upon. The vpopc instructions we've emitted in each case above will return
4211   // 0 for an inactive vector, and so we've already received the neutral value:
4212   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4213   // can simply include the start value.
4214   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4215 }
4216 
4217 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4218                                             SelectionDAG &DAG) const {
4219   SDLoc DL(Op);
4220   SDValue Vec = Op.getOperand(0);
4221   EVT VecEVT = Vec.getValueType();
4222 
4223   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4224 
4225   // Due to ordering in legalize types we may have a vector type that needs to
4226   // be split. Do that manually so we can get down to a legal type.
4227   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4228          TargetLowering::TypeSplitVector) {
4229     SDValue Lo, Hi;
4230     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4231     VecEVT = Lo.getValueType();
4232     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4233   }
4234 
4235   // TODO: The type may need to be widened rather than split. Or widened before
4236   // it can be split.
4237   if (!isTypeLegal(VecEVT))
4238     return SDValue();
4239 
4240   MVT VecVT = VecEVT.getSimpleVT();
4241   MVT VecEltVT = VecVT.getVectorElementType();
4242   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4243 
4244   MVT ContainerVT = VecVT;
4245   if (VecVT.isFixedLengthVector()) {
4246     ContainerVT = getContainerForFixedLengthVector(VecVT);
4247     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4248   }
4249 
4250   MVT M1VT = getLMUL1VT(ContainerVT);
4251 
4252   SDValue Mask, VL;
4253   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4254 
4255   // FIXME: This is a VLMAX splat which might be too large and can prevent
4256   // vsetvli removal.
4257   SDValue NeutralElem =
4258       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4259   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4260   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4261                                   IdentitySplat, Mask, VL);
4262   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4263                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4264   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4265 }
4266 
4267 // Given a reduction op, this function returns the matching reduction opcode,
4268 // the vector SDValue and the scalar SDValue required to lower this to a
4269 // RISCVISD node.
4270 static std::tuple<unsigned, SDValue, SDValue>
4271 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4272   SDLoc DL(Op);
4273   auto Flags = Op->getFlags();
4274   unsigned Opcode = Op.getOpcode();
4275   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4276   switch (Opcode) {
4277   default:
4278     llvm_unreachable("Unhandled reduction");
4279   case ISD::VECREDUCE_FADD:
4280     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4281                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4282   case ISD::VECREDUCE_SEQ_FADD:
4283     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4284                            Op.getOperand(0));
4285   case ISD::VECREDUCE_FMIN:
4286     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4287                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4288   case ISD::VECREDUCE_FMAX:
4289     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4290                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4291   }
4292 }
4293 
4294 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4295                                               SelectionDAG &DAG) const {
4296   SDLoc DL(Op);
4297   MVT VecEltVT = Op.getSimpleValueType();
4298 
4299   unsigned RVVOpcode;
4300   SDValue VectorVal, ScalarVal;
4301   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4302       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4303   MVT VecVT = VectorVal.getSimpleValueType();
4304 
4305   MVT ContainerVT = VecVT;
4306   if (VecVT.isFixedLengthVector()) {
4307     ContainerVT = getContainerForFixedLengthVector(VecVT);
4308     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4309   }
4310 
4311   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4312 
4313   SDValue Mask, VL;
4314   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4315 
4316   // FIXME: This is a VLMAX splat which might be too large and can prevent
4317   // vsetvli removal.
4318   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4319   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4320                                   VectorVal, ScalarSplat, Mask, VL);
4321   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4322                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4323 }
4324 
4325 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4326   switch (ISDOpcode) {
4327   default:
4328     llvm_unreachable("Unhandled reduction");
4329   case ISD::VP_REDUCE_ADD:
4330     return RISCVISD::VECREDUCE_ADD_VL;
4331   case ISD::VP_REDUCE_UMAX:
4332     return RISCVISD::VECREDUCE_UMAX_VL;
4333   case ISD::VP_REDUCE_SMAX:
4334     return RISCVISD::VECREDUCE_SMAX_VL;
4335   case ISD::VP_REDUCE_UMIN:
4336     return RISCVISD::VECREDUCE_UMIN_VL;
4337   case ISD::VP_REDUCE_SMIN:
4338     return RISCVISD::VECREDUCE_SMIN_VL;
4339   case ISD::VP_REDUCE_AND:
4340     return RISCVISD::VECREDUCE_AND_VL;
4341   case ISD::VP_REDUCE_OR:
4342     return RISCVISD::VECREDUCE_OR_VL;
4343   case ISD::VP_REDUCE_XOR:
4344     return RISCVISD::VECREDUCE_XOR_VL;
4345   case ISD::VP_REDUCE_FADD:
4346     return RISCVISD::VECREDUCE_FADD_VL;
4347   case ISD::VP_REDUCE_SEQ_FADD:
4348     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4349   case ISD::VP_REDUCE_FMAX:
4350     return RISCVISD::VECREDUCE_FMAX_VL;
4351   case ISD::VP_REDUCE_FMIN:
4352     return RISCVISD::VECREDUCE_FMIN_VL;
4353   }
4354 }
4355 
4356 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4357                                            SelectionDAG &DAG) const {
4358   SDLoc DL(Op);
4359   SDValue Vec = Op.getOperand(1);
4360   EVT VecEVT = Vec.getValueType();
4361 
4362   // TODO: The type may need to be widened rather than split. Or widened before
4363   // it can be split.
4364   if (!isTypeLegal(VecEVT))
4365     return SDValue();
4366 
4367   MVT VecVT = VecEVT.getSimpleVT();
4368   MVT VecEltVT = VecVT.getVectorElementType();
4369   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4370 
4371   MVT ContainerVT = VecVT;
4372   if (VecVT.isFixedLengthVector()) {
4373     ContainerVT = getContainerForFixedLengthVector(VecVT);
4374     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4375   }
4376 
4377   SDValue VL = Op.getOperand(3);
4378   SDValue Mask = Op.getOperand(2);
4379 
4380   MVT M1VT = getLMUL1VT(ContainerVT);
4381   MVT XLenVT = Subtarget.getXLenVT();
4382   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4383 
4384   // FIXME: This is a VLMAX splat which might be too large and can prevent
4385   // vsetvli removal.
4386   SDValue StartSplat = DAG.getSplatVector(M1VT, DL, Op.getOperand(0));
4387   SDValue Reduction =
4388       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4389   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4390                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4391   if (!VecVT.isInteger())
4392     return Elt0;
4393   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4394 }
4395 
4396 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4397                                                    SelectionDAG &DAG) const {
4398   SDValue Vec = Op.getOperand(0);
4399   SDValue SubVec = Op.getOperand(1);
4400   MVT VecVT = Vec.getSimpleValueType();
4401   MVT SubVecVT = SubVec.getSimpleValueType();
4402 
4403   SDLoc DL(Op);
4404   MVT XLenVT = Subtarget.getXLenVT();
4405   unsigned OrigIdx = Op.getConstantOperandVal(2);
4406   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4407 
4408   // We don't have the ability to slide mask vectors up indexed by their i1
4409   // elements; the smallest we can do is i8. Often we are able to bitcast to
4410   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4411   // into a scalable one, we might not necessarily have enough scalable
4412   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4413   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4414       (OrigIdx != 0 || !Vec.isUndef())) {
4415     if (VecVT.getVectorMinNumElements() >= 8 &&
4416         SubVecVT.getVectorMinNumElements() >= 8) {
4417       assert(OrigIdx % 8 == 0 && "Invalid index");
4418       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4419              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4420              "Unexpected mask vector lowering");
4421       OrigIdx /= 8;
4422       SubVecVT =
4423           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4424                            SubVecVT.isScalableVector());
4425       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4426                                VecVT.isScalableVector());
4427       Vec = DAG.getBitcast(VecVT, Vec);
4428       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4429     } else {
4430       // We can't slide this mask vector up indexed by its i1 elements.
4431       // This poses a problem when we wish to insert a scalable vector which
4432       // can't be re-expressed as a larger type. Just choose the slow path and
4433       // extend to a larger type, then truncate back down.
4434       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4435       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4436       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4437       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4438       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4439                         Op.getOperand(2));
4440       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4441       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4442     }
4443   }
4444 
4445   // If the subvector vector is a fixed-length type, we cannot use subregister
4446   // manipulation to simplify the codegen; we don't know which register of a
4447   // LMUL group contains the specific subvector as we only know the minimum
4448   // register size. Therefore we must slide the vector group up the full
4449   // amount.
4450   if (SubVecVT.isFixedLengthVector()) {
4451     if (OrigIdx == 0 && Vec.isUndef())
4452       return Op;
4453     MVT ContainerVT = VecVT;
4454     if (VecVT.isFixedLengthVector()) {
4455       ContainerVT = getContainerForFixedLengthVector(VecVT);
4456       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4457     }
4458     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4459                          DAG.getUNDEF(ContainerVT), SubVec,
4460                          DAG.getConstant(0, DL, XLenVT));
4461     SDValue Mask =
4462         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4463     // Set the vector length to only the number of elements we care about. Note
4464     // that for slideup this includes the offset.
4465     SDValue VL =
4466         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4467     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4468     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4469                                   SubVec, SlideupAmt, Mask, VL);
4470     if (VecVT.isFixedLengthVector())
4471       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4472     return DAG.getBitcast(Op.getValueType(), Slideup);
4473   }
4474 
4475   unsigned SubRegIdx, RemIdx;
4476   std::tie(SubRegIdx, RemIdx) =
4477       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4478           VecVT, SubVecVT, OrigIdx, TRI);
4479 
4480   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4481   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4482                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4483                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4484 
4485   // 1. If the Idx has been completely eliminated and this subvector's size is
4486   // a vector register or a multiple thereof, or the surrounding elements are
4487   // undef, then this is a subvector insert which naturally aligns to a vector
4488   // register. These can easily be handled using subregister manipulation.
4489   // 2. If the subvector is smaller than a vector register, then the insertion
4490   // must preserve the undisturbed elements of the register. We do this by
4491   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4492   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4493   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4494   // LMUL=1 type back into the larger vector (resolving to another subregister
4495   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4496   // to avoid allocating a large register group to hold our subvector.
4497   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4498     return Op;
4499 
4500   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4501   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4502   // (in our case undisturbed). This means we can set up a subvector insertion
4503   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4504   // size of the subvector.
4505   MVT InterSubVT = VecVT;
4506   SDValue AlignedExtract = Vec;
4507   unsigned AlignedIdx = OrigIdx - RemIdx;
4508   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4509     InterSubVT = getLMUL1VT(VecVT);
4510     // Extract a subvector equal to the nearest full vector register type. This
4511     // should resolve to a EXTRACT_SUBREG instruction.
4512     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4513                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4514   }
4515 
4516   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4517   // For scalable vectors this must be further multiplied by vscale.
4518   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4519 
4520   SDValue Mask, VL;
4521   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4522 
4523   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4524   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4525   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4526   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4527 
4528   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4529                        DAG.getUNDEF(InterSubVT), SubVec,
4530                        DAG.getConstant(0, DL, XLenVT));
4531 
4532   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4533                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4534 
4535   // If required, insert this subvector back into the correct vector register.
4536   // This should resolve to an INSERT_SUBREG instruction.
4537   if (VecVT.bitsGT(InterSubVT))
4538     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4539                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4540 
4541   // We might have bitcast from a mask type: cast back to the original type if
4542   // required.
4543   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4544 }
4545 
4546 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4547                                                     SelectionDAG &DAG) const {
4548   SDValue Vec = Op.getOperand(0);
4549   MVT SubVecVT = Op.getSimpleValueType();
4550   MVT VecVT = Vec.getSimpleValueType();
4551 
4552   SDLoc DL(Op);
4553   MVT XLenVT = Subtarget.getXLenVT();
4554   unsigned OrigIdx = Op.getConstantOperandVal(1);
4555   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4556 
4557   // We don't have the ability to slide mask vectors down indexed by their i1
4558   // elements; the smallest we can do is i8. Often we are able to bitcast to
4559   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4560   // from a scalable one, we might not necessarily have enough scalable
4561   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4562   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4563     if (VecVT.getVectorMinNumElements() >= 8 &&
4564         SubVecVT.getVectorMinNumElements() >= 8) {
4565       assert(OrigIdx % 8 == 0 && "Invalid index");
4566       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4567              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4568              "Unexpected mask vector lowering");
4569       OrigIdx /= 8;
4570       SubVecVT =
4571           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4572                            SubVecVT.isScalableVector());
4573       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4574                                VecVT.isScalableVector());
4575       Vec = DAG.getBitcast(VecVT, Vec);
4576     } else {
4577       // We can't slide this mask vector down, indexed by its i1 elements.
4578       // This poses a problem when we wish to extract a scalable vector which
4579       // can't be re-expressed as a larger type. Just choose the slow path and
4580       // extend to a larger type, then truncate back down.
4581       // TODO: We could probably improve this when extracting certain fixed
4582       // from fixed, where we can extract as i8 and shift the correct element
4583       // right to reach the desired subvector?
4584       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4585       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4586       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4587       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4588                         Op.getOperand(1));
4589       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4590       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4591     }
4592   }
4593 
4594   // If the subvector vector is a fixed-length type, we cannot use subregister
4595   // manipulation to simplify the codegen; we don't know which register of a
4596   // LMUL group contains the specific subvector as we only know the minimum
4597   // register size. Therefore we must slide the vector group down the full
4598   // amount.
4599   if (SubVecVT.isFixedLengthVector()) {
4600     // With an index of 0 this is a cast-like subvector, which can be performed
4601     // with subregister operations.
4602     if (OrigIdx == 0)
4603       return Op;
4604     MVT ContainerVT = VecVT;
4605     if (VecVT.isFixedLengthVector()) {
4606       ContainerVT = getContainerForFixedLengthVector(VecVT);
4607       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4608     }
4609     SDValue Mask =
4610         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4611     // Set the vector length to only the number of elements we care about. This
4612     // avoids sliding down elements we're going to discard straight away.
4613     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4614     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4615     SDValue Slidedown =
4616         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4617                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4618     // Now we can use a cast-like subvector extract to get the result.
4619     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4620                             DAG.getConstant(0, DL, XLenVT));
4621     return DAG.getBitcast(Op.getValueType(), Slidedown);
4622   }
4623 
4624   unsigned SubRegIdx, RemIdx;
4625   std::tie(SubRegIdx, RemIdx) =
4626       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4627           VecVT, SubVecVT, OrigIdx, TRI);
4628 
4629   // If the Idx has been completely eliminated then this is a subvector extract
4630   // which naturally aligns to a vector register. These can easily be handled
4631   // using subregister manipulation.
4632   if (RemIdx == 0)
4633     return Op;
4634 
4635   // Else we must shift our vector register directly to extract the subvector.
4636   // Do this using VSLIDEDOWN.
4637 
4638   // If the vector type is an LMUL-group type, extract a subvector equal to the
4639   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4640   // instruction.
4641   MVT InterSubVT = VecVT;
4642   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4643     InterSubVT = getLMUL1VT(VecVT);
4644     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4645                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4646   }
4647 
4648   // Slide this vector register down by the desired number of elements in order
4649   // to place the desired subvector starting at element 0.
4650   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4651   // For scalable vectors this must be further multiplied by vscale.
4652   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4653 
4654   SDValue Mask, VL;
4655   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4656   SDValue Slidedown =
4657       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4658                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4659 
4660   // Now the vector is in the right position, extract our final subvector. This
4661   // should resolve to a COPY.
4662   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4663                           DAG.getConstant(0, DL, XLenVT));
4664 
4665   // We might have bitcast from a mask type: cast back to the original type if
4666   // required.
4667   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4668 }
4669 
4670 // Lower step_vector to the vid instruction. Any non-identity step value must
4671 // be accounted for my manual expansion.
4672 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4673                                               SelectionDAG &DAG) const {
4674   SDLoc DL(Op);
4675   MVT VT = Op.getSimpleValueType();
4676   MVT XLenVT = Subtarget.getXLenVT();
4677   SDValue Mask, VL;
4678   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4679   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4680   uint64_t StepValImm = Op.getConstantOperandVal(0);
4681   if (StepValImm != 1) {
4682     if (isPowerOf2_64(StepValImm)) {
4683       SDValue StepVal =
4684           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4685                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4686       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4687     } else {
4688       SDValue StepVal = lowerScalarSplat(
4689           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4690           DL, DAG, Subtarget);
4691       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4692     }
4693   }
4694   return StepVec;
4695 }
4696 
4697 // Implement vector_reverse using vrgather.vv with indices determined by
4698 // subtracting the id of each element from (VLMAX-1). This will convert
4699 // the indices like so:
4700 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4701 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4702 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4703                                                  SelectionDAG &DAG) const {
4704   SDLoc DL(Op);
4705   MVT VecVT = Op.getSimpleValueType();
4706   unsigned EltSize = VecVT.getScalarSizeInBits();
4707   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4708 
4709   unsigned MaxVLMAX = 0;
4710   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4711   if (VectorBitsMax != 0)
4712     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4713 
4714   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4715   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4716 
4717   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4718   // to use vrgatherei16.vv.
4719   // TODO: It's also possible to use vrgatherei16.vv for other types to
4720   // decrease register width for the index calculation.
4721   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4722     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4723     // Reverse each half, then reassemble them in reverse order.
4724     // NOTE: It's also possible that after splitting that VLMAX no longer
4725     // requires vrgatherei16.vv.
4726     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4727       SDValue Lo, Hi;
4728       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4729       EVT LoVT, HiVT;
4730       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4731       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4732       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4733       // Reassemble the low and high pieces reversed.
4734       // FIXME: This is a CONCAT_VECTORS.
4735       SDValue Res =
4736           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4737                       DAG.getIntPtrConstant(0, DL));
4738       return DAG.getNode(
4739           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4740           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4741     }
4742 
4743     // Just promote the int type to i16 which will double the LMUL.
4744     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4745     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4746   }
4747 
4748   MVT XLenVT = Subtarget.getXLenVT();
4749   SDValue Mask, VL;
4750   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4751 
4752   // Calculate VLMAX-1 for the desired SEW.
4753   unsigned MinElts = VecVT.getVectorMinNumElements();
4754   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4755                               DAG.getConstant(MinElts, DL, XLenVT));
4756   SDValue VLMinus1 =
4757       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4758 
4759   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4760   bool IsRV32E64 =
4761       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4762   SDValue SplatVL;
4763   if (!IsRV32E64)
4764     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4765   else
4766     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4767 
4768   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4769   SDValue Indices =
4770       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4771 
4772   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4773 }
4774 
4775 SDValue
4776 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4777                                                      SelectionDAG &DAG) const {
4778   SDLoc DL(Op);
4779   auto *Load = cast<LoadSDNode>(Op);
4780 
4781   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4782                                         Load->getMemoryVT(),
4783                                         *Load->getMemOperand()) &&
4784          "Expecting a correctly-aligned load");
4785 
4786   MVT VT = Op.getSimpleValueType();
4787   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4788 
4789   SDValue VL =
4790       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4791 
4792   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4793   SDValue NewLoad = DAG.getMemIntrinsicNode(
4794       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4795       Load->getMemoryVT(), Load->getMemOperand());
4796 
4797   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4798   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4799 }
4800 
4801 SDValue
4802 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4803                                                       SelectionDAG &DAG) const {
4804   SDLoc DL(Op);
4805   auto *Store = cast<StoreSDNode>(Op);
4806 
4807   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4808                                         Store->getMemoryVT(),
4809                                         *Store->getMemOperand()) &&
4810          "Expecting a correctly-aligned store");
4811 
4812   SDValue StoreVal = Store->getValue();
4813   MVT VT = StoreVal.getSimpleValueType();
4814 
4815   // If the size less than a byte, we need to pad with zeros to make a byte.
4816   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4817     VT = MVT::v8i1;
4818     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4819                            DAG.getConstant(0, DL, VT), StoreVal,
4820                            DAG.getIntPtrConstant(0, DL));
4821   }
4822 
4823   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4824 
4825   SDValue VL =
4826       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4827 
4828   SDValue NewValue =
4829       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4830   return DAG.getMemIntrinsicNode(
4831       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4832       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4833       Store->getMemoryVT(), Store->getMemOperand());
4834 }
4835 
4836 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
4837                                              SelectionDAG &DAG) const {
4838   SDLoc DL(Op);
4839   MVT VT = Op.getSimpleValueType();
4840 
4841   const auto *MemSD = cast<MemSDNode>(Op);
4842   EVT MemVT = MemSD->getMemoryVT();
4843   MachineMemOperand *MMO = MemSD->getMemOperand();
4844   SDValue Chain = MemSD->getChain();
4845   SDValue BasePtr = MemSD->getBasePtr();
4846 
4847   SDValue Mask, PassThru, VL;
4848   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
4849     Mask = VPLoad->getMask();
4850     PassThru = DAG.getUNDEF(VT);
4851     VL = VPLoad->getVectorLength();
4852   } else {
4853     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
4854     Mask = MLoad->getMask();
4855     PassThru = MLoad->getPassThru();
4856   }
4857 
4858   MVT XLenVT = Subtarget.getXLenVT();
4859 
4860   MVT ContainerVT = VT;
4861   if (VT.isFixedLengthVector()) {
4862     ContainerVT = getContainerForFixedLengthVector(VT);
4863     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4864 
4865     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4866     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4867   }
4868 
4869   if (!VL)
4870     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4871 
4872   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4873   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT);
4874   SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4875   SDValue Ops[] = {Chain, IntID, PassThru, BasePtr, Mask, VL, Policy};
4876   SDValue Result =
4877       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4878   Chain = Result.getValue(1);
4879 
4880   if (VT.isFixedLengthVector())
4881     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4882 
4883   return DAG.getMergeValues({Result, Chain}, DL);
4884 }
4885 
4886 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
4887                                               SelectionDAG &DAG) const {
4888   SDLoc DL(Op);
4889 
4890   const auto *MemSD = cast<MemSDNode>(Op);
4891   EVT MemVT = MemSD->getMemoryVT();
4892   MachineMemOperand *MMO = MemSD->getMemOperand();
4893   SDValue Chain = MemSD->getChain();
4894   SDValue BasePtr = MemSD->getBasePtr();
4895   SDValue Val, Mask, VL;
4896 
4897   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
4898     Val = VPStore->getValue();
4899     Mask = VPStore->getMask();
4900     VL = VPStore->getVectorLength();
4901   } else {
4902     const auto *MStore = cast<MaskedStoreSDNode>(Op);
4903     Val = MStore->getValue();
4904     Mask = MStore->getMask();
4905   }
4906 
4907   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4908 
4909   MVT VT = Val.getSimpleValueType();
4910   MVT XLenVT = Subtarget.getXLenVT();
4911 
4912   MVT ContainerVT = VT;
4913   if (VT.isFixedLengthVector()) {
4914     ContainerVT = getContainerForFixedLengthVector(VT);
4915 
4916     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4917     if (!IsUnmasked) {
4918       MVT MaskVT =
4919           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4920       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4921     }
4922   }
4923 
4924   if (!VL)
4925     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4926 
4927   unsigned IntID =
4928       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
4929   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4930   Ops.push_back(Val);
4931   Ops.push_back(BasePtr);
4932   if (!IsUnmasked)
4933     Ops.push_back(Mask);
4934   Ops.push_back(VL);
4935 
4936   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
4937                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
4938 }
4939 
4940 SDValue
4941 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4942                                                       SelectionDAG &DAG) const {
4943   MVT InVT = Op.getOperand(0).getSimpleValueType();
4944   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4945 
4946   MVT VT = Op.getSimpleValueType();
4947 
4948   SDValue Op1 =
4949       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4950   SDValue Op2 =
4951       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4952 
4953   SDLoc DL(Op);
4954   SDValue VL =
4955       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4956 
4957   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4958   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4959 
4960   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4961                             Op.getOperand(2), Mask, VL);
4962 
4963   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
4964 }
4965 
4966 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
4967     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
4968   MVT VT = Op.getSimpleValueType();
4969 
4970   if (VT.getVectorElementType() == MVT::i1)
4971     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
4972 
4973   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
4974 }
4975 
4976 SDValue
4977 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
4978                                                       SelectionDAG &DAG) const {
4979   unsigned Opc;
4980   switch (Op.getOpcode()) {
4981   default: llvm_unreachable("Unexpected opcode!");
4982   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
4983   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
4984   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
4985   }
4986 
4987   return lowerToScalableOp(Op, DAG, Opc);
4988 }
4989 
4990 // Lower vector ABS to smax(X, sub(0, X)).
4991 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
4992   SDLoc DL(Op);
4993   MVT VT = Op.getSimpleValueType();
4994   SDValue X = Op.getOperand(0);
4995 
4996   assert(VT.isFixedLengthVector() && "Unexpected type");
4997 
4998   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4999   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5000 
5001   SDValue Mask, VL;
5002   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5003 
5004   SDValue SplatZero =
5005       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5006                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5007   SDValue NegX =
5008       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5009   SDValue Max =
5010       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5011 
5012   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5013 }
5014 
5015 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5016     SDValue Op, SelectionDAG &DAG) const {
5017   SDLoc DL(Op);
5018   MVT VT = Op.getSimpleValueType();
5019   SDValue Mag = Op.getOperand(0);
5020   SDValue Sign = Op.getOperand(1);
5021   assert(Mag.getValueType() == Sign.getValueType() &&
5022          "Can only handle COPYSIGN with matching types.");
5023 
5024   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5025   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5026   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5027 
5028   SDValue Mask, VL;
5029   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5030 
5031   SDValue CopySign =
5032       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5033 
5034   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5035 }
5036 
5037 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5038     SDValue Op, SelectionDAG &DAG) const {
5039   MVT VT = Op.getSimpleValueType();
5040   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5041 
5042   MVT I1ContainerVT =
5043       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5044 
5045   SDValue CC =
5046       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5047   SDValue Op1 =
5048       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5049   SDValue Op2 =
5050       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5051 
5052   SDLoc DL(Op);
5053   SDValue Mask, VL;
5054   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5055 
5056   SDValue Select =
5057       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5058 
5059   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5060 }
5061 
5062 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5063                                                unsigned NewOpc,
5064                                                bool HasMask) const {
5065   MVT VT = Op.getSimpleValueType();
5066   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5067 
5068   // Create list of operands by converting existing ones to scalable types.
5069   SmallVector<SDValue, 6> Ops;
5070   for (const SDValue &V : Op->op_values()) {
5071     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5072 
5073     // Pass through non-vector operands.
5074     if (!V.getValueType().isVector()) {
5075       Ops.push_back(V);
5076       continue;
5077     }
5078 
5079     // "cast" fixed length vector to a scalable vector.
5080     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5081            "Only fixed length vectors are supported!");
5082     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5083   }
5084 
5085   SDLoc DL(Op);
5086   SDValue Mask, VL;
5087   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5088   if (HasMask)
5089     Ops.push_back(Mask);
5090   Ops.push_back(VL);
5091 
5092   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5093   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5094 }
5095 
5096 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5097 // * Operands of each node are assumed to be in the same order.
5098 // * The EVL operand is promoted from i32 to i64 on RV64.
5099 // * Fixed-length vectors are converted to their scalable-vector container
5100 //   types.
5101 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5102                                        unsigned RISCVISDOpc) const {
5103   SDLoc DL(Op);
5104   MVT VT = Op.getSimpleValueType();
5105   SmallVector<SDValue, 4> Ops;
5106 
5107   for (const auto &OpIdx : enumerate(Op->ops())) {
5108     SDValue V = OpIdx.value();
5109     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5110     // Pass through operands which aren't fixed-length vectors.
5111     if (!V.getValueType().isFixedLengthVector()) {
5112       Ops.push_back(V);
5113       continue;
5114     }
5115     // "cast" fixed length vector to a scalable vector.
5116     MVT OpVT = V.getSimpleValueType();
5117     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5118     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5119            "Only fixed length vectors are supported!");
5120     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5121   }
5122 
5123   if (!VT.isFixedLengthVector())
5124     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5125 
5126   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5127 
5128   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5129 
5130   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5131 }
5132 
5133 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5134 // matched to a RVV indexed load. The RVV indexed load instructions only
5135 // support the "unsigned unscaled" addressing mode; indices are implicitly
5136 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5137 // signed or scaled indexing is extended to the XLEN value type and scaled
5138 // accordingly.
5139 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5140                                                SelectionDAG &DAG) const {
5141   SDLoc DL(Op);
5142   MVT VT = Op.getSimpleValueType();
5143 
5144   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5145   EVT MemVT = MemSD->getMemoryVT();
5146   MachineMemOperand *MMO = MemSD->getMemOperand();
5147   SDValue Chain = MemSD->getChain();
5148   SDValue BasePtr = MemSD->getBasePtr();
5149 
5150   ISD::LoadExtType LoadExtType;
5151   SDValue Index, Mask, PassThru, VL;
5152 
5153   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5154     Index = VPGN->getIndex();
5155     Mask = VPGN->getMask();
5156     PassThru = DAG.getUNDEF(VT);
5157     VL = VPGN->getVectorLength();
5158     // VP doesn't support extending loads.
5159     LoadExtType = ISD::NON_EXTLOAD;
5160   } else {
5161     // Else it must be a MGATHER.
5162     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5163     Index = MGN->getIndex();
5164     Mask = MGN->getMask();
5165     PassThru = MGN->getPassThru();
5166     LoadExtType = MGN->getExtensionType();
5167   }
5168 
5169   MVT IndexVT = Index.getSimpleValueType();
5170   MVT XLenVT = Subtarget.getXLenVT();
5171 
5172   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5173          "Unexpected VTs!");
5174   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5175   // Targets have to explicitly opt-in for extending vector loads.
5176   assert(LoadExtType == ISD::NON_EXTLOAD &&
5177          "Unexpected extending MGATHER/VP_GATHER");
5178   (void)LoadExtType;
5179 
5180   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5181   // the selection of the masked intrinsics doesn't do this for us.
5182   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5183 
5184   MVT ContainerVT = VT;
5185   if (VT.isFixedLengthVector()) {
5186     // We need to use the larger of the result and index type to determine the
5187     // scalable type to use so we don't increase LMUL for any operand/result.
5188     if (VT.bitsGE(IndexVT)) {
5189       ContainerVT = getContainerForFixedLengthVector(VT);
5190       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5191                                  ContainerVT.getVectorElementCount());
5192     } else {
5193       IndexVT = getContainerForFixedLengthVector(IndexVT);
5194       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5195                                      IndexVT.getVectorElementCount());
5196     }
5197 
5198     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5199 
5200     if (!IsUnmasked) {
5201       MVT MaskVT =
5202           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5203       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5204       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5205     }
5206   }
5207 
5208   if (!VL)
5209     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5210 
5211   unsigned IntID =
5212       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5213   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5214   if (!IsUnmasked)
5215     Ops.push_back(PassThru);
5216   Ops.push_back(BasePtr);
5217   Ops.push_back(Index);
5218   if (!IsUnmasked)
5219     Ops.push_back(Mask);
5220   Ops.push_back(VL);
5221   if (!IsUnmasked)
5222     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5223 
5224   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5225   SDValue Result =
5226       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5227   Chain = Result.getValue(1);
5228 
5229   if (VT.isFixedLengthVector())
5230     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5231 
5232   return DAG.getMergeValues({Result, Chain}, DL);
5233 }
5234 
5235 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5236 // matched to a RVV indexed store. The RVV indexed store instructions only
5237 // support the "unsigned unscaled" addressing mode; indices are implicitly
5238 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5239 // signed or scaled indexing is extended to the XLEN value type and scaled
5240 // accordingly.
5241 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5242                                                 SelectionDAG &DAG) const {
5243   SDLoc DL(Op);
5244   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5245   EVT MemVT = MemSD->getMemoryVT();
5246   MachineMemOperand *MMO = MemSD->getMemOperand();
5247   SDValue Chain = MemSD->getChain();
5248   SDValue BasePtr = MemSD->getBasePtr();
5249 
5250   bool IsTruncatingStore = false;
5251   SDValue Index, Mask, Val, VL;
5252 
5253   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5254     Index = VPSN->getIndex();
5255     Mask = VPSN->getMask();
5256     Val = VPSN->getValue();
5257     VL = VPSN->getVectorLength();
5258     // VP doesn't support truncating stores.
5259     IsTruncatingStore = false;
5260   } else {
5261     // Else it must be a MSCATTER.
5262     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5263     Index = MSN->getIndex();
5264     Mask = MSN->getMask();
5265     Val = MSN->getValue();
5266     IsTruncatingStore = MSN->isTruncatingStore();
5267   }
5268 
5269   MVT VT = Val.getSimpleValueType();
5270   MVT IndexVT = Index.getSimpleValueType();
5271   MVT XLenVT = Subtarget.getXLenVT();
5272 
5273   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5274          "Unexpected VTs!");
5275   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5276   // Targets have to explicitly opt-in for extending vector loads and
5277   // truncating vector stores.
5278   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5279   (void)IsTruncatingStore;
5280 
5281   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5282   // the selection of the masked intrinsics doesn't do this for us.
5283   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5284 
5285   MVT ContainerVT = VT;
5286   if (VT.isFixedLengthVector()) {
5287     // We need to use the larger of the value and index type to determine the
5288     // scalable type to use so we don't increase LMUL for any operand/result.
5289     if (VT.bitsGE(IndexVT)) {
5290       ContainerVT = getContainerForFixedLengthVector(VT);
5291       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5292                                  ContainerVT.getVectorElementCount());
5293     } else {
5294       IndexVT = getContainerForFixedLengthVector(IndexVT);
5295       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5296                                      IndexVT.getVectorElementCount());
5297     }
5298 
5299     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5300     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5301 
5302     if (!IsUnmasked) {
5303       MVT MaskVT =
5304           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5305       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5306     }
5307   }
5308 
5309   if (!VL)
5310     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5311 
5312   unsigned IntID =
5313       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5314   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5315   Ops.push_back(Val);
5316   Ops.push_back(BasePtr);
5317   Ops.push_back(Index);
5318   if (!IsUnmasked)
5319     Ops.push_back(Mask);
5320   Ops.push_back(VL);
5321 
5322   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5323                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5324 }
5325 
5326 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5327                                                SelectionDAG &DAG) const {
5328   const MVT XLenVT = Subtarget.getXLenVT();
5329   SDLoc DL(Op);
5330   SDValue Chain = Op->getOperand(0);
5331   SDValue SysRegNo = DAG.getConstant(
5332       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5333   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5334   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5335 
5336   // Encoding used for rounding mode in RISCV differs from that used in
5337   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5338   // table, which consists of a sequence of 4-bit fields, each representing
5339   // corresponding FLT_ROUNDS mode.
5340   static const int Table =
5341       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5342       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5343       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5344       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5345       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5346 
5347   SDValue Shift =
5348       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5349   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5350                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5351   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5352                                DAG.getConstant(7, DL, XLenVT));
5353 
5354   return DAG.getMergeValues({Masked, Chain}, DL);
5355 }
5356 
5357 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5358                                                SelectionDAG &DAG) const {
5359   const MVT XLenVT = Subtarget.getXLenVT();
5360   SDLoc DL(Op);
5361   SDValue Chain = Op->getOperand(0);
5362   SDValue RMValue = Op->getOperand(1);
5363   SDValue SysRegNo = DAG.getConstant(
5364       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5365 
5366   // Encoding used for rounding mode in RISCV differs from that used in
5367   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5368   // a table, which consists of a sequence of 4-bit fields, each representing
5369   // corresponding RISCV mode.
5370   static const unsigned Table =
5371       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5372       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5373       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5374       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5375       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5376 
5377   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5378                               DAG.getConstant(2, DL, XLenVT));
5379   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5380                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5381   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5382                         DAG.getConstant(0x7, DL, XLenVT));
5383   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5384                      RMValue);
5385 }
5386 
5387 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5388 // form of the given Opcode.
5389 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5390   switch (Opcode) {
5391   default:
5392     llvm_unreachable("Unexpected opcode");
5393   case ISD::SHL:
5394     return RISCVISD::SLLW;
5395   case ISD::SRA:
5396     return RISCVISD::SRAW;
5397   case ISD::SRL:
5398     return RISCVISD::SRLW;
5399   case ISD::SDIV:
5400     return RISCVISD::DIVW;
5401   case ISD::UDIV:
5402     return RISCVISD::DIVUW;
5403   case ISD::UREM:
5404     return RISCVISD::REMUW;
5405   case ISD::ROTL:
5406     return RISCVISD::ROLW;
5407   case ISD::ROTR:
5408     return RISCVISD::RORW;
5409   case RISCVISD::GREV:
5410     return RISCVISD::GREVW;
5411   case RISCVISD::GORC:
5412     return RISCVISD::GORCW;
5413   }
5414 }
5415 
5416 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5417 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5418 // otherwise be promoted to i64, making it difficult to select the
5419 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5420 // type i8/i16/i32 is lost.
5421 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5422                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5423   SDLoc DL(N);
5424   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5425   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5426   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5427   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5428   // ReplaceNodeResults requires we maintain the same type for the return value.
5429   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5430 }
5431 
5432 // Converts the given 32-bit operation to a i64 operation with signed extension
5433 // semantic to reduce the signed extension instructions.
5434 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5435   SDLoc DL(N);
5436   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5437   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5438   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5439   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5440                                DAG.getValueType(MVT::i32));
5441   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5442 }
5443 
5444 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5445                                              SmallVectorImpl<SDValue> &Results,
5446                                              SelectionDAG &DAG) const {
5447   SDLoc DL(N);
5448   switch (N->getOpcode()) {
5449   default:
5450     llvm_unreachable("Don't know how to custom type legalize this operation!");
5451   case ISD::STRICT_FP_TO_SINT:
5452   case ISD::STRICT_FP_TO_UINT:
5453   case ISD::FP_TO_SINT:
5454   case ISD::FP_TO_UINT: {
5455     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5456            "Unexpected custom legalisation");
5457     bool IsStrict = N->isStrictFPOpcode();
5458     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5459                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5460     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5461     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5462         TargetLowering::TypeSoftenFloat) {
5463       // FIXME: Support strict FP.
5464       if (IsStrict)
5465         return;
5466       if (!isTypeLegal(Op0.getValueType()))
5467         return;
5468       unsigned Opc =
5469           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5470       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5471       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5472       return;
5473     }
5474     // If the FP type needs to be softened, emit a library call using the 'si'
5475     // version. If we left it to default legalization we'd end up with 'di'. If
5476     // the FP type doesn't need to be softened just let generic type
5477     // legalization promote the result type.
5478     RTLIB::Libcall LC;
5479     if (IsSigned)
5480       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5481     else
5482       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5483     MakeLibCallOptions CallOptions;
5484     EVT OpVT = Op0.getValueType();
5485     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5486     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5487     SDValue Result;
5488     std::tie(Result, Chain) =
5489         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5490     Results.push_back(Result);
5491     if (IsStrict)
5492       Results.push_back(Chain);
5493     break;
5494   }
5495   case ISD::READCYCLECOUNTER: {
5496     assert(!Subtarget.is64Bit() &&
5497            "READCYCLECOUNTER only has custom type legalization on riscv32");
5498 
5499     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5500     SDValue RCW =
5501         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5502 
5503     Results.push_back(
5504         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5505     Results.push_back(RCW.getValue(2));
5506     break;
5507   }
5508   case ISD::MUL: {
5509     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5510     unsigned XLen = Subtarget.getXLen();
5511     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5512     if (Size > XLen) {
5513       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5514       SDValue LHS = N->getOperand(0);
5515       SDValue RHS = N->getOperand(1);
5516       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5517 
5518       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5519       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5520       // We need exactly one side to be unsigned.
5521       if (LHSIsU == RHSIsU)
5522         return;
5523 
5524       auto MakeMULPair = [&](SDValue S, SDValue U) {
5525         MVT XLenVT = Subtarget.getXLenVT();
5526         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5527         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5528         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5529         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5530         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5531       };
5532 
5533       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5534       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5535 
5536       // The other operand should be signed, but still prefer MULH when
5537       // possible.
5538       if (RHSIsU && LHSIsS && !RHSIsS)
5539         Results.push_back(MakeMULPair(LHS, RHS));
5540       else if (LHSIsU && RHSIsS && !LHSIsS)
5541         Results.push_back(MakeMULPair(RHS, LHS));
5542 
5543       return;
5544     }
5545     LLVM_FALLTHROUGH;
5546   }
5547   case ISD::ADD:
5548   case ISD::SUB:
5549     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5550            "Unexpected custom legalisation");
5551     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5552     break;
5553   case ISD::SHL:
5554   case ISD::SRA:
5555   case ISD::SRL:
5556     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5557            "Unexpected custom legalisation");
5558     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5559       Results.push_back(customLegalizeToWOp(N, DAG));
5560       break;
5561     }
5562 
5563     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5564     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5565     // shift amount.
5566     if (N->getOpcode() == ISD::SHL) {
5567       SDLoc DL(N);
5568       SDValue NewOp0 =
5569           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5570       SDValue NewOp1 =
5571           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5572       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5573       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5574                                    DAG.getValueType(MVT::i32));
5575       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5576     }
5577 
5578     break;
5579   case ISD::ROTL:
5580   case ISD::ROTR:
5581     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5582            "Unexpected custom legalisation");
5583     Results.push_back(customLegalizeToWOp(N, DAG));
5584     break;
5585   case ISD::CTTZ:
5586   case ISD::CTTZ_ZERO_UNDEF:
5587   case ISD::CTLZ:
5588   case ISD::CTLZ_ZERO_UNDEF: {
5589     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5590            "Unexpected custom legalisation");
5591 
5592     SDValue NewOp0 =
5593         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5594     bool IsCTZ =
5595         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5596     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5597     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5598     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5599     return;
5600   }
5601   case ISD::SDIV:
5602   case ISD::UDIV:
5603   case ISD::UREM: {
5604     MVT VT = N->getSimpleValueType(0);
5605     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5606            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5607            "Unexpected custom legalisation");
5608     // Don't promote division/remainder by constant since we should expand those
5609     // to multiply by magic constant.
5610     // FIXME: What if the expansion is disabled for minsize.
5611     if (N->getOperand(1).getOpcode() == ISD::Constant)
5612       return;
5613 
5614     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5615     // the upper 32 bits. For other types we need to sign or zero extend
5616     // based on the opcode.
5617     unsigned ExtOpc = ISD::ANY_EXTEND;
5618     if (VT != MVT::i32)
5619       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5620                                            : ISD::ZERO_EXTEND;
5621 
5622     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5623     break;
5624   }
5625   case ISD::UADDO:
5626   case ISD::USUBO: {
5627     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5628            "Unexpected custom legalisation");
5629     bool IsAdd = N->getOpcode() == ISD::UADDO;
5630     // Create an ADDW or SUBW.
5631     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5632     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5633     SDValue Res =
5634         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5635     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5636                       DAG.getValueType(MVT::i32));
5637 
5638     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5639     // Since the inputs are sign extended from i32, this is equivalent to
5640     // comparing the lower 32 bits.
5641     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5642     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5643                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5644 
5645     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5646     Results.push_back(Overflow);
5647     return;
5648   }
5649   case ISD::UADDSAT:
5650   case ISD::USUBSAT: {
5651     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5652            "Unexpected custom legalisation");
5653     if (Subtarget.hasStdExtZbb()) {
5654       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5655       // sign extend allows overflow of the lower 32 bits to be detected on
5656       // the promoted size.
5657       SDValue LHS =
5658           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5659       SDValue RHS =
5660           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5661       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5662       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5663       return;
5664     }
5665 
5666     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5667     // promotion for UADDO/USUBO.
5668     Results.push_back(expandAddSubSat(N, DAG));
5669     return;
5670   }
5671   case ISD::BITCAST: {
5672     EVT VT = N->getValueType(0);
5673     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5674     SDValue Op0 = N->getOperand(0);
5675     EVT Op0VT = Op0.getValueType();
5676     MVT XLenVT = Subtarget.getXLenVT();
5677     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5678       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5679       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5680     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5681                Subtarget.hasStdExtF()) {
5682       SDValue FPConv =
5683           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5684       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5685     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5686                isTypeLegal(Op0VT)) {
5687       // Custom-legalize bitcasts from fixed-length vector types to illegal
5688       // scalar types in order to improve codegen. Bitcast the vector to a
5689       // one-element vector type whose element type is the same as the result
5690       // type, and extract the first element.
5691       LLVMContext &Context = *DAG.getContext();
5692       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5693       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5694                                     DAG.getConstant(0, DL, XLenVT)));
5695     }
5696     break;
5697   }
5698   case RISCVISD::GREV:
5699   case RISCVISD::GORC: {
5700     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5701            "Unexpected custom legalisation");
5702     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5703     // This is similar to customLegalizeToWOp, except that we pass the second
5704     // operand (a TargetConstant) straight through: it is already of type
5705     // XLenVT.
5706     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5707     SDValue NewOp0 =
5708         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5709     SDValue NewOp1 =
5710         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5711     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5712     // ReplaceNodeResults requires we maintain the same type for the return
5713     // value.
5714     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5715     break;
5716   }
5717   case RISCVISD::SHFL: {
5718     // There is no SHFLIW instruction, but we can just promote the operation.
5719     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5720            "Unexpected custom legalisation");
5721     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5722     SDValue NewOp0 =
5723         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5724     SDValue NewOp1 =
5725         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5726     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5727     // ReplaceNodeResults requires we maintain the same type for the return
5728     // value.
5729     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5730     break;
5731   }
5732   case ISD::BSWAP:
5733   case ISD::BITREVERSE: {
5734     MVT VT = N->getSimpleValueType(0);
5735     MVT XLenVT = Subtarget.getXLenVT();
5736     assert((VT == MVT::i8 || VT == MVT::i16 ||
5737             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5738            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5739     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5740     unsigned Imm = VT.getSizeInBits() - 1;
5741     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5742     if (N->getOpcode() == ISD::BSWAP)
5743       Imm &= ~0x7U;
5744     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5745     SDValue GREVI =
5746         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5747     // ReplaceNodeResults requires we maintain the same type for the return
5748     // value.
5749     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5750     break;
5751   }
5752   case ISD::FSHL:
5753   case ISD::FSHR: {
5754     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5755            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5756     SDValue NewOp0 =
5757         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5758     SDValue NewOp1 =
5759         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5760     SDValue NewOp2 =
5761         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5762     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5763     // Mask the shift amount to 5 bits.
5764     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5765                          DAG.getConstant(0x1f, DL, MVT::i64));
5766     unsigned Opc =
5767         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5768     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5769     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5770     break;
5771   }
5772   case ISD::EXTRACT_VECTOR_ELT: {
5773     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5774     // type is illegal (currently only vXi64 RV32).
5775     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5776     // transferred to the destination register. We issue two of these from the
5777     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5778     // first element.
5779     SDValue Vec = N->getOperand(0);
5780     SDValue Idx = N->getOperand(1);
5781 
5782     // The vector type hasn't been legalized yet so we can't issue target
5783     // specific nodes if it needs legalization.
5784     // FIXME: We would manually legalize if it's important.
5785     if (!isTypeLegal(Vec.getValueType()))
5786       return;
5787 
5788     MVT VecVT = Vec.getSimpleValueType();
5789 
5790     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5791            VecVT.getVectorElementType() == MVT::i64 &&
5792            "Unexpected EXTRACT_VECTOR_ELT legalization");
5793 
5794     // If this is a fixed vector, we need to convert it to a scalable vector.
5795     MVT ContainerVT = VecVT;
5796     if (VecVT.isFixedLengthVector()) {
5797       ContainerVT = getContainerForFixedLengthVector(VecVT);
5798       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5799     }
5800 
5801     MVT XLenVT = Subtarget.getXLenVT();
5802 
5803     // Use a VL of 1 to avoid processing more elements than we need.
5804     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5805     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5806     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5807 
5808     // Unless the index is known to be 0, we must slide the vector down to get
5809     // the desired element into index 0.
5810     if (!isNullConstant(Idx)) {
5811       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5812                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5813     }
5814 
5815     // Extract the lower XLEN bits of the correct vector element.
5816     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5817 
5818     // To extract the upper XLEN bits of the vector element, shift the first
5819     // element right by 32 bits and re-extract the lower XLEN bits.
5820     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5821                                      DAG.getConstant(32, DL, XLenVT), VL);
5822     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5823                                  ThirtyTwoV, Mask, VL);
5824 
5825     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5826 
5827     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5828     break;
5829   }
5830   case ISD::INTRINSIC_WO_CHAIN: {
5831     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5832     switch (IntNo) {
5833     default:
5834       llvm_unreachable(
5835           "Don't know how to custom type legalize this intrinsic!");
5836     case Intrinsic::riscv_orc_b: {
5837       // Lower to the GORCI encoding for orc.b with the operand extended.
5838       SDValue NewOp =
5839           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5840       // If Zbp is enabled, use GORCIW which will sign extend the result.
5841       unsigned Opc =
5842           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5843       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5844                                 DAG.getConstant(7, DL, MVT::i64));
5845       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5846       return;
5847     }
5848     case Intrinsic::riscv_grev:
5849     case Intrinsic::riscv_gorc: {
5850       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5851              "Unexpected custom legalisation");
5852       SDValue NewOp1 =
5853           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5854       SDValue NewOp2 =
5855           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5856       unsigned Opc =
5857           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5858       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5859       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5860       break;
5861     }
5862     case Intrinsic::riscv_shfl:
5863     case Intrinsic::riscv_unshfl: {
5864       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5865              "Unexpected custom legalisation");
5866       SDValue NewOp1 =
5867           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5868       SDValue NewOp2 =
5869           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5870       unsigned Opc =
5871           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5872       if (isa<ConstantSDNode>(N->getOperand(2))) {
5873         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5874                              DAG.getConstant(0xf, DL, MVT::i64));
5875         Opc =
5876             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5877       }
5878       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5879       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5880       break;
5881     }
5882     case Intrinsic::riscv_bcompress:
5883     case Intrinsic::riscv_bdecompress: {
5884       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5885              "Unexpected custom legalisation");
5886       SDValue NewOp1 =
5887           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5888       SDValue NewOp2 =
5889           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5890       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5891                          ? RISCVISD::BCOMPRESSW
5892                          : RISCVISD::BDECOMPRESSW;
5893       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5894       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5895       break;
5896     }
5897     case Intrinsic::riscv_vmv_x_s: {
5898       EVT VT = N->getValueType(0);
5899       MVT XLenVT = Subtarget.getXLenVT();
5900       if (VT.bitsLT(XLenVT)) {
5901         // Simple case just extract using vmv.x.s and truncate.
5902         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5903                                       Subtarget.getXLenVT(), N->getOperand(1));
5904         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5905         return;
5906       }
5907 
5908       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5909              "Unexpected custom legalization");
5910 
5911       // We need to do the move in two steps.
5912       SDValue Vec = N->getOperand(1);
5913       MVT VecVT = Vec.getSimpleValueType();
5914 
5915       // First extract the lower XLEN bits of the element.
5916       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5917 
5918       // To extract the upper XLEN bits of the vector element, shift the first
5919       // element right by 32 bits and re-extract the lower XLEN bits.
5920       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5921       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5922       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5923       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5924                                        DAG.getConstant(32, DL, XLenVT), VL);
5925       SDValue LShr32 =
5926           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5927       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5928 
5929       Results.push_back(
5930           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5931       break;
5932     }
5933     }
5934     break;
5935   }
5936   case ISD::VECREDUCE_ADD:
5937   case ISD::VECREDUCE_AND:
5938   case ISD::VECREDUCE_OR:
5939   case ISD::VECREDUCE_XOR:
5940   case ISD::VECREDUCE_SMAX:
5941   case ISD::VECREDUCE_UMAX:
5942   case ISD::VECREDUCE_SMIN:
5943   case ISD::VECREDUCE_UMIN:
5944     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5945       Results.push_back(V);
5946     break;
5947   case ISD::VP_REDUCE_ADD:
5948   case ISD::VP_REDUCE_AND:
5949   case ISD::VP_REDUCE_OR:
5950   case ISD::VP_REDUCE_XOR:
5951   case ISD::VP_REDUCE_SMAX:
5952   case ISD::VP_REDUCE_UMAX:
5953   case ISD::VP_REDUCE_SMIN:
5954   case ISD::VP_REDUCE_UMIN:
5955     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
5956       Results.push_back(V);
5957     break;
5958   case ISD::FLT_ROUNDS_: {
5959     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5960     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5961     Results.push_back(Res.getValue(0));
5962     Results.push_back(Res.getValue(1));
5963     break;
5964   }
5965   }
5966 }
5967 
5968 // A structure to hold one of the bit-manipulation patterns below. Together, a
5969 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
5970 //   (or (and (shl x, 1), 0xAAAAAAAA),
5971 //       (and (srl x, 1), 0x55555555))
5972 struct RISCVBitmanipPat {
5973   SDValue Op;
5974   unsigned ShAmt;
5975   bool IsSHL;
5976 
5977   bool formsPairWith(const RISCVBitmanipPat &Other) const {
5978     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
5979   }
5980 };
5981 
5982 // Matches patterns of the form
5983 //   (and (shl x, C2), (C1 << C2))
5984 //   (and (srl x, C2), C1)
5985 //   (shl (and x, C1), C2)
5986 //   (srl (and x, (C1 << C2)), C2)
5987 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
5988 // The expected masks for each shift amount are specified in BitmanipMasks where
5989 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
5990 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
5991 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
5992 // XLen is 64.
5993 static Optional<RISCVBitmanipPat>
5994 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
5995   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
5996          "Unexpected number of masks");
5997   Optional<uint64_t> Mask;
5998   // Optionally consume a mask around the shift operation.
5999   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6000     Mask = Op.getConstantOperandVal(1);
6001     Op = Op.getOperand(0);
6002   }
6003   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6004     return None;
6005   bool IsSHL = Op.getOpcode() == ISD::SHL;
6006 
6007   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6008     return None;
6009   uint64_t ShAmt = Op.getConstantOperandVal(1);
6010 
6011   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6012   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6013     return None;
6014   // If we don't have enough masks for 64 bit, then we must be trying to
6015   // match SHFL so we're only allowed to shift 1/4 of the width.
6016   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6017     return None;
6018 
6019   SDValue Src = Op.getOperand(0);
6020 
6021   // The expected mask is shifted left when the AND is found around SHL
6022   // patterns.
6023   //   ((x >> 1) & 0x55555555)
6024   //   ((x << 1) & 0xAAAAAAAA)
6025   bool SHLExpMask = IsSHL;
6026 
6027   if (!Mask) {
6028     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6029     // the mask is all ones: consume that now.
6030     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6031       Mask = Src.getConstantOperandVal(1);
6032       Src = Src.getOperand(0);
6033       // The expected mask is now in fact shifted left for SRL, so reverse the
6034       // decision.
6035       //   ((x & 0xAAAAAAAA) >> 1)
6036       //   ((x & 0x55555555) << 1)
6037       SHLExpMask = !SHLExpMask;
6038     } else {
6039       // Use a default shifted mask of all-ones if there's no AND, truncated
6040       // down to the expected width. This simplifies the logic later on.
6041       Mask = maskTrailingOnes<uint64_t>(Width);
6042       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6043     }
6044   }
6045 
6046   unsigned MaskIdx = Log2_32(ShAmt);
6047   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6048 
6049   if (SHLExpMask)
6050     ExpMask <<= ShAmt;
6051 
6052   if (Mask != ExpMask)
6053     return None;
6054 
6055   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6056 }
6057 
6058 // Matches any of the following bit-manipulation patterns:
6059 //   (and (shl x, 1), (0x55555555 << 1))
6060 //   (and (srl x, 1), 0x55555555)
6061 //   (shl (and x, 0x55555555), 1)
6062 //   (srl (and x, (0x55555555 << 1)), 1)
6063 // where the shift amount and mask may vary thus:
6064 //   [1]  = 0x55555555 / 0xAAAAAAAA
6065 //   [2]  = 0x33333333 / 0xCCCCCCCC
6066 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6067 //   [8]  = 0x00FF00FF / 0xFF00FF00
6068 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6069 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6070 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6071   // These are the unshifted masks which we use to match bit-manipulation
6072   // patterns. They may be shifted left in certain circumstances.
6073   static const uint64_t BitmanipMasks[] = {
6074       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6075       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6076 
6077   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6078 }
6079 
6080 // Match the following pattern as a GREVI(W) operation
6081 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6082 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6083                                const RISCVSubtarget &Subtarget) {
6084   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6085   EVT VT = Op.getValueType();
6086 
6087   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6088     auto LHS = matchGREVIPat(Op.getOperand(0));
6089     auto RHS = matchGREVIPat(Op.getOperand(1));
6090     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6091       SDLoc DL(Op);
6092       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6093                          DAG.getConstant(LHS->ShAmt, DL, VT));
6094     }
6095   }
6096   return SDValue();
6097 }
6098 
6099 // Matches any the following pattern as a GORCI(W) operation
6100 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6101 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6102 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6103 // Note that with the variant of 3.,
6104 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6105 // the inner pattern will first be matched as GREVI and then the outer
6106 // pattern will be matched to GORC via the first rule above.
6107 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6108 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6109                                const RISCVSubtarget &Subtarget) {
6110   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6111   EVT VT = Op.getValueType();
6112 
6113   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6114     SDLoc DL(Op);
6115     SDValue Op0 = Op.getOperand(0);
6116     SDValue Op1 = Op.getOperand(1);
6117 
6118     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6119       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6120           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6121           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6122         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6123       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6124       if ((Reverse.getOpcode() == ISD::ROTL ||
6125            Reverse.getOpcode() == ISD::ROTR) &&
6126           Reverse.getOperand(0) == X &&
6127           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6128         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6129         if (RotAmt == (VT.getSizeInBits() / 2))
6130           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6131                              DAG.getConstant(RotAmt, DL, VT));
6132       }
6133       return SDValue();
6134     };
6135 
6136     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6137     if (SDValue V = MatchOROfReverse(Op0, Op1))
6138       return V;
6139     if (SDValue V = MatchOROfReverse(Op1, Op0))
6140       return V;
6141 
6142     // OR is commutable so canonicalize its OR operand to the left
6143     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6144       std::swap(Op0, Op1);
6145     if (Op0.getOpcode() != ISD::OR)
6146       return SDValue();
6147     SDValue OrOp0 = Op0.getOperand(0);
6148     SDValue OrOp1 = Op0.getOperand(1);
6149     auto LHS = matchGREVIPat(OrOp0);
6150     // OR is commutable so swap the operands and try again: x might have been
6151     // on the left
6152     if (!LHS) {
6153       std::swap(OrOp0, OrOp1);
6154       LHS = matchGREVIPat(OrOp0);
6155     }
6156     auto RHS = matchGREVIPat(Op1);
6157     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6158       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6159                          DAG.getConstant(LHS->ShAmt, DL, VT));
6160     }
6161   }
6162   return SDValue();
6163 }
6164 
6165 // Matches any of the following bit-manipulation patterns:
6166 //   (and (shl x, 1), (0x22222222 << 1))
6167 //   (and (srl x, 1), 0x22222222)
6168 //   (shl (and x, 0x22222222), 1)
6169 //   (srl (and x, (0x22222222 << 1)), 1)
6170 // where the shift amount and mask may vary thus:
6171 //   [1]  = 0x22222222 / 0x44444444
6172 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6173 //   [4]  = 0x00F000F0 / 0x0F000F00
6174 //   [8]  = 0x0000FF00 / 0x00FF0000
6175 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6176 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6177   // These are the unshifted masks which we use to match bit-manipulation
6178   // patterns. They may be shifted left in certain circumstances.
6179   static const uint64_t BitmanipMasks[] = {
6180       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6181       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6182 
6183   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6184 }
6185 
6186 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6187 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6188                                const RISCVSubtarget &Subtarget) {
6189   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6190   EVT VT = Op.getValueType();
6191 
6192   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6193     return SDValue();
6194 
6195   SDValue Op0 = Op.getOperand(0);
6196   SDValue Op1 = Op.getOperand(1);
6197 
6198   // Or is commutable so canonicalize the second OR to the LHS.
6199   if (Op0.getOpcode() != ISD::OR)
6200     std::swap(Op0, Op1);
6201   if (Op0.getOpcode() != ISD::OR)
6202     return SDValue();
6203 
6204   // We found an inner OR, so our operands are the operands of the inner OR
6205   // and the other operand of the outer OR.
6206   SDValue A = Op0.getOperand(0);
6207   SDValue B = Op0.getOperand(1);
6208   SDValue C = Op1;
6209 
6210   auto Match1 = matchSHFLPat(A);
6211   auto Match2 = matchSHFLPat(B);
6212 
6213   // If neither matched, we failed.
6214   if (!Match1 && !Match2)
6215     return SDValue();
6216 
6217   // We had at least one match. if one failed, try the remaining C operand.
6218   if (!Match1) {
6219     std::swap(A, C);
6220     Match1 = matchSHFLPat(A);
6221     if (!Match1)
6222       return SDValue();
6223   } else if (!Match2) {
6224     std::swap(B, C);
6225     Match2 = matchSHFLPat(B);
6226     if (!Match2)
6227       return SDValue();
6228   }
6229   assert(Match1 && Match2);
6230 
6231   // Make sure our matches pair up.
6232   if (!Match1->formsPairWith(*Match2))
6233     return SDValue();
6234 
6235   // All the remains is to make sure C is an AND with the same input, that masks
6236   // out the bits that are being shuffled.
6237   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6238       C.getOperand(0) != Match1->Op)
6239     return SDValue();
6240 
6241   uint64_t Mask = C.getConstantOperandVal(1);
6242 
6243   static const uint64_t BitmanipMasks[] = {
6244       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6245       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6246   };
6247 
6248   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6249   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6250   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6251 
6252   if (Mask != ExpMask)
6253     return SDValue();
6254 
6255   SDLoc DL(Op);
6256   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6257                      DAG.getConstant(Match1->ShAmt, DL, VT));
6258 }
6259 
6260 // Optimize (add (shl x, c0), (shl y, c1)) ->
6261 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6262 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6263                                   const RISCVSubtarget &Subtarget) {
6264   // Perform this optimization only in the zba extension.
6265   if (!Subtarget.hasStdExtZba())
6266     return SDValue();
6267 
6268   // Skip for vector types and larger types.
6269   EVT VT = N->getValueType(0);
6270   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6271     return SDValue();
6272 
6273   // The two operand nodes must be SHL and have no other use.
6274   SDValue N0 = N->getOperand(0);
6275   SDValue N1 = N->getOperand(1);
6276   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6277       !N0->hasOneUse() || !N1->hasOneUse())
6278     return SDValue();
6279 
6280   // Check c0 and c1.
6281   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6282   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6283   if (!N0C || !N1C)
6284     return SDValue();
6285   int64_t C0 = N0C->getSExtValue();
6286   int64_t C1 = N1C->getSExtValue();
6287   if (C0 <= 0 || C1 <= 0)
6288     return SDValue();
6289 
6290   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6291   int64_t Bits = std::min(C0, C1);
6292   int64_t Diff = std::abs(C0 - C1);
6293   if (Diff != 1 && Diff != 2 && Diff != 3)
6294     return SDValue();
6295 
6296   // Build nodes.
6297   SDLoc DL(N);
6298   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6299   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6300   SDValue NA0 =
6301       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6302   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6303   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6304 }
6305 
6306 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6307 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6308 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6309 // not undo itself, but they are redundant.
6310 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6311   SDValue Src = N->getOperand(0);
6312 
6313   if (Src.getOpcode() != N->getOpcode())
6314     return SDValue();
6315 
6316   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6317       !isa<ConstantSDNode>(Src.getOperand(1)))
6318     return SDValue();
6319 
6320   unsigned ShAmt1 = N->getConstantOperandVal(1);
6321   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6322   Src = Src.getOperand(0);
6323 
6324   unsigned CombinedShAmt;
6325   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6326     CombinedShAmt = ShAmt1 | ShAmt2;
6327   else
6328     CombinedShAmt = ShAmt1 ^ ShAmt2;
6329 
6330   if (CombinedShAmt == 0)
6331     return Src;
6332 
6333   SDLoc DL(N);
6334   return DAG.getNode(
6335       N->getOpcode(), DL, N->getValueType(0), Src,
6336       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6337 }
6338 
6339 // Combine a constant select operand into its use:
6340 //
6341 // (and (select cond, -1, c), x)
6342 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6343 // (or  (select cond, 0, c), x)
6344 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6345 // (xor (select cond, 0, c), x)
6346 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6347 // (add (select cond, 0, c), x)
6348 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6349 // (sub x, (select cond, 0, c))
6350 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6351 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6352                                    SelectionDAG &DAG, bool AllOnes) {
6353   EVT VT = N->getValueType(0);
6354 
6355   // Skip vectors.
6356   if (VT.isVector())
6357     return SDValue();
6358 
6359   if ((Slct.getOpcode() != ISD::SELECT &&
6360        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6361       !Slct.hasOneUse())
6362     return SDValue();
6363 
6364   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6365     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6366   };
6367 
6368   bool SwapSelectOps;
6369   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6370   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6371   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6372   SDValue NonConstantVal;
6373   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6374     SwapSelectOps = false;
6375     NonConstantVal = FalseVal;
6376   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6377     SwapSelectOps = true;
6378     NonConstantVal = TrueVal;
6379   } else
6380     return SDValue();
6381 
6382   // Slct is now know to be the desired identity constant when CC is true.
6383   TrueVal = OtherOp;
6384   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6385   // Unless SwapSelectOps says the condition should be false.
6386   if (SwapSelectOps)
6387     std::swap(TrueVal, FalseVal);
6388 
6389   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6390     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6391                        {Slct.getOperand(0), Slct.getOperand(1),
6392                         Slct.getOperand(2), TrueVal, FalseVal});
6393 
6394   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6395                      {Slct.getOperand(0), TrueVal, FalseVal});
6396 }
6397 
6398 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6399 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6400                                               bool AllOnes) {
6401   SDValue N0 = N->getOperand(0);
6402   SDValue N1 = N->getOperand(1);
6403   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6404     return Result;
6405   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6406     return Result;
6407   return SDValue();
6408 }
6409 
6410 // Transform (add (mul x, c0), c1) ->
6411 //           (add (mul (add x, c1/c0), c0), c1%c0).
6412 // if c1/c0 and c1%c0 are simm12, while c1 is not.
6413 // Or transform (add (mul x, c0), c1) ->
6414 //              (mul (add x, c1/c0), c0).
6415 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6416 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6417                                      const RISCVSubtarget &Subtarget) {
6418   // Skip for vector types and larger types.
6419   EVT VT = N->getValueType(0);
6420   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6421     return SDValue();
6422   // The first operand node must be a MUL and has no other use.
6423   SDValue N0 = N->getOperand(0);
6424   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6425     return SDValue();
6426   // Check if c0 and c1 match above conditions.
6427   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6428   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6429   if (!N0C || !N1C)
6430     return SDValue();
6431   int64_t C0 = N0C->getSExtValue();
6432   int64_t C1 = N1C->getSExtValue();
6433   if (C0 == -1 || C0 == 0 || C0 == 1 || (C1 / C0) == 0 || isInt<12>(C1) ||
6434       !isInt<12>(C1 % C0) || !isInt<12>(C1 / C0))
6435     return SDValue();
6436   // If C0 * (C1 / C0) is a 12-bit integer, this transform will be reversed.
6437   if (isInt<12>(C0 * (C1 / C0)))
6438     return SDValue();
6439   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6440   SDLoc DL(N);
6441   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6442                              DAG.getConstant(C1 / C0, DL, VT));
6443   SDValue New1 =
6444       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6445   if ((C1 % C0) == 0)
6446     return New1;
6447   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(C1 % C0, DL, VT));
6448 }
6449 
6450 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6451                                  const RISCVSubtarget &Subtarget) {
6452   // Transform (add (mul x, c0), c1) ->
6453   //           (add (mul (add x, c1/c0), c0), c1%c0).
6454   // if c1/c0 and c1%c0 are simm12, while c1 is not.
6455   // Or transform (add (mul x, c0), c1) ->
6456   //              (mul (add x, c1/c0), c0).
6457   // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6458   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6459     return V;
6460   // Fold (add (shl x, c0), (shl y, c1)) ->
6461   //      (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6462   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6463     return V;
6464   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6465   //      (select lhs, rhs, cc, x, (add x, y))
6466   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6467 }
6468 
6469 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6470   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6471   //      (select lhs, rhs, cc, x, (sub x, y))
6472   SDValue N0 = N->getOperand(0);
6473   SDValue N1 = N->getOperand(1);
6474   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6475 }
6476 
6477 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6478   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6479   //      (select lhs, rhs, cc, x, (and x, y))
6480   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6481 }
6482 
6483 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6484                                 const RISCVSubtarget &Subtarget) {
6485   if (Subtarget.hasStdExtZbp()) {
6486     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6487       return GREV;
6488     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6489       return GORC;
6490     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6491       return SHFL;
6492   }
6493 
6494   // fold (or (select cond, 0, y), x) ->
6495   //      (select cond, x, (or x, y))
6496   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6497 }
6498 
6499 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6500   // fold (xor (select cond, 0, y), x) ->
6501   //      (select cond, x, (xor x, y))
6502   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6503 }
6504 
6505 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6506 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6507 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6508 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6509 // ADDW/SUBW/MULW.
6510 static SDValue performANY_EXTENDCombine(SDNode *N,
6511                                         TargetLowering::DAGCombinerInfo &DCI,
6512                                         const RISCVSubtarget &Subtarget) {
6513   if (!Subtarget.is64Bit())
6514     return SDValue();
6515 
6516   SelectionDAG &DAG = DCI.DAG;
6517 
6518   SDValue Src = N->getOperand(0);
6519   EVT VT = N->getValueType(0);
6520   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6521     return SDValue();
6522 
6523   // The opcode must be one that can implicitly sign_extend.
6524   // FIXME: Additional opcodes.
6525   switch (Src.getOpcode()) {
6526   default:
6527     return SDValue();
6528   case ISD::MUL:
6529     if (!Subtarget.hasStdExtM())
6530       return SDValue();
6531     LLVM_FALLTHROUGH;
6532   case ISD::ADD:
6533   case ISD::SUB:
6534     break;
6535   }
6536 
6537   // Only handle cases where the result is used by a CopyToReg. That likely
6538   // means the value is a liveout of the basic block. This helps prevent
6539   // infinite combine loops like PR51206.
6540   if (none_of(N->uses(),
6541               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6542     return SDValue();
6543 
6544   SmallVector<SDNode *, 4> SetCCs;
6545   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6546                             UE = Src.getNode()->use_end();
6547        UI != UE; ++UI) {
6548     SDNode *User = *UI;
6549     if (User == N)
6550       continue;
6551     if (UI.getUse().getResNo() != Src.getResNo())
6552       continue;
6553     // All i32 setccs are legalized by sign extending operands.
6554     if (User->getOpcode() == ISD::SETCC) {
6555       SetCCs.push_back(User);
6556       continue;
6557     }
6558     // We don't know if we can extend this user.
6559     break;
6560   }
6561 
6562   // If we don't have any SetCCs, this isn't worthwhile.
6563   if (SetCCs.empty())
6564     return SDValue();
6565 
6566   SDLoc DL(N);
6567   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6568   DCI.CombineTo(N, SExt);
6569 
6570   // Promote all the setccs.
6571   for (SDNode *SetCC : SetCCs) {
6572     SmallVector<SDValue, 4> Ops;
6573 
6574     for (unsigned j = 0; j != 2; ++j) {
6575       SDValue SOp = SetCC->getOperand(j);
6576       if (SOp == Src)
6577         Ops.push_back(SExt);
6578       else
6579         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6580     }
6581 
6582     Ops.push_back(SetCC->getOperand(2));
6583     DCI.CombineTo(SetCC,
6584                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6585   }
6586   return SDValue(N, 0);
6587 }
6588 
6589 // Try to form VWMUL or VWMULU.
6590 // FIXME: Support VWMULSU.
6591 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
6592                                     SelectionDAG &DAG) {
6593   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
6594   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6595   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6596   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
6597     return SDValue();
6598 
6599   SDValue Mask = N->getOperand(2);
6600   SDValue VL = N->getOperand(3);
6601 
6602   // Make sure the mask and VL match.
6603   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
6604     return SDValue();
6605 
6606   MVT VT = N->getSimpleValueType(0);
6607 
6608   // Determine the narrow size for a widening multiply.
6609   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
6610   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
6611                                   VT.getVectorElementCount());
6612 
6613   SDLoc DL(N);
6614 
6615   // See if the other operand is the same opcode.
6616   if (Op0.getOpcode() == Op1.getOpcode()) {
6617     if (!Op1.hasOneUse())
6618       return SDValue();
6619 
6620     // Make sure the mask and VL match.
6621     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
6622       return SDValue();
6623 
6624     Op1 = Op1.getOperand(0);
6625   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
6626     // The operand is a splat of a scalar.
6627 
6628     // The VL must be the same.
6629     if (Op1.getOperand(1) != VL)
6630       return SDValue();
6631 
6632     // Get the scalar value.
6633     Op1 = Op1.getOperand(0);
6634 
6635     // See if have enough sign bits or zero bits in the scalar to use a
6636     // widening multiply by splatting to smaller element size.
6637     unsigned EltBits = VT.getScalarSizeInBits();
6638     unsigned ScalarBits = Op1.getValueSizeInBits();
6639     // Make sure we're getting all element bits from the scalar register.
6640     // FIXME: Support implicit sign extension of vmv.v.x?
6641     if (ScalarBits < EltBits)
6642       return SDValue();
6643 
6644     if (IsSignExt) {
6645       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
6646         return SDValue();
6647     } else {
6648       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
6649       if (!DAG.MaskedValueIsZero(Op1, Mask))
6650         return SDValue();
6651     }
6652 
6653     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
6654   } else
6655     return SDValue();
6656 
6657   Op0 = Op0.getOperand(0);
6658 
6659   // Re-introduce narrower extends if needed.
6660   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6661   if (Op0.getValueType() != NarrowVT)
6662     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6663   if (Op1.getValueType() != NarrowVT)
6664     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6665 
6666   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6667   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6668 }
6669 
6670 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6671                                                DAGCombinerInfo &DCI) const {
6672   SelectionDAG &DAG = DCI.DAG;
6673 
6674   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6675   // bits are demanded. N will be added to the Worklist if it was not deleted.
6676   // Caller should return SDValue(N, 0) if this returns true.
6677   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6678     SDValue Op = N->getOperand(OpNo);
6679     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6680     if (!SimplifyDemandedBits(Op, Mask, DCI))
6681       return false;
6682 
6683     if (N->getOpcode() != ISD::DELETED_NODE)
6684       DCI.AddToWorklist(N);
6685     return true;
6686   };
6687 
6688   switch (N->getOpcode()) {
6689   default:
6690     break;
6691   case RISCVISD::SplitF64: {
6692     SDValue Op0 = N->getOperand(0);
6693     // If the input to SplitF64 is just BuildPairF64 then the operation is
6694     // redundant. Instead, use BuildPairF64's operands directly.
6695     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6696       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6697 
6698     SDLoc DL(N);
6699 
6700     // It's cheaper to materialise two 32-bit integers than to load a double
6701     // from the constant pool and transfer it to integer registers through the
6702     // stack.
6703     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6704       APInt V = C->getValueAPF().bitcastToAPInt();
6705       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6706       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6707       return DCI.CombineTo(N, Lo, Hi);
6708     }
6709 
6710     // This is a target-specific version of a DAGCombine performed in
6711     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6712     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6713     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6714     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6715         !Op0.getNode()->hasOneUse())
6716       break;
6717     SDValue NewSplitF64 =
6718         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6719                     Op0.getOperand(0));
6720     SDValue Lo = NewSplitF64.getValue(0);
6721     SDValue Hi = NewSplitF64.getValue(1);
6722     APInt SignBit = APInt::getSignMask(32);
6723     if (Op0.getOpcode() == ISD::FNEG) {
6724       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6725                                   DAG.getConstant(SignBit, DL, MVT::i32));
6726       return DCI.CombineTo(N, Lo, NewHi);
6727     }
6728     assert(Op0.getOpcode() == ISD::FABS);
6729     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6730                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6731     return DCI.CombineTo(N, Lo, NewHi);
6732   }
6733   case RISCVISD::SLLW:
6734   case RISCVISD::SRAW:
6735   case RISCVISD::SRLW:
6736   case RISCVISD::ROLW:
6737   case RISCVISD::RORW: {
6738     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6739     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6740         SimplifyDemandedLowBitsHelper(1, 5))
6741       return SDValue(N, 0);
6742     break;
6743   }
6744   case RISCVISD::CLZW:
6745   case RISCVISD::CTZW: {
6746     // Only the lower 32 bits of the first operand are read
6747     if (SimplifyDemandedLowBitsHelper(0, 32))
6748       return SDValue(N, 0);
6749     break;
6750   }
6751   case RISCVISD::FSL:
6752   case RISCVISD::FSR: {
6753     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6754     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6755     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6756     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6757       return SDValue(N, 0);
6758     break;
6759   }
6760   case RISCVISD::FSLW:
6761   case RISCVISD::FSRW: {
6762     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6763     // read.
6764     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6765         SimplifyDemandedLowBitsHelper(1, 32) ||
6766         SimplifyDemandedLowBitsHelper(2, 6))
6767       return SDValue(N, 0);
6768     break;
6769   }
6770   case RISCVISD::GREV:
6771   case RISCVISD::GORC: {
6772     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6773     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6774     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6775     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6776       return SDValue(N, 0);
6777 
6778     return combineGREVI_GORCI(N, DCI.DAG);
6779   }
6780   case RISCVISD::GREVW:
6781   case RISCVISD::GORCW: {
6782     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6783     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6784         SimplifyDemandedLowBitsHelper(1, 5))
6785       return SDValue(N, 0);
6786 
6787     return combineGREVI_GORCI(N, DCI.DAG);
6788   }
6789   case RISCVISD::SHFL:
6790   case RISCVISD::UNSHFL: {
6791     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6792     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6793     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6794     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6795       return SDValue(N, 0);
6796 
6797     break;
6798   }
6799   case RISCVISD::SHFLW:
6800   case RISCVISD::UNSHFLW: {
6801     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6802     SDValue LHS = N->getOperand(0);
6803     SDValue RHS = N->getOperand(1);
6804     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6805     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6806     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6807         SimplifyDemandedLowBitsHelper(1, 4))
6808       return SDValue(N, 0);
6809 
6810     break;
6811   }
6812   case RISCVISD::BCOMPRESSW:
6813   case RISCVISD::BDECOMPRESSW: {
6814     // Only the lower 32 bits of LHS and RHS are read.
6815     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6816         SimplifyDemandedLowBitsHelper(1, 32))
6817       return SDValue(N, 0);
6818 
6819     break;
6820   }
6821   case RISCVISD::FMV_X_ANYEXTH:
6822   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6823     SDLoc DL(N);
6824     SDValue Op0 = N->getOperand(0);
6825     MVT VT = N->getSimpleValueType(0);
6826     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6827     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6828     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6829     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6830          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6831         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6832          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6833       assert(Op0.getOperand(0).getValueType() == VT &&
6834              "Unexpected value type!");
6835       return Op0.getOperand(0);
6836     }
6837 
6838     // This is a target-specific version of a DAGCombine performed in
6839     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6840     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6841     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6842     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6843         !Op0.getNode()->hasOneUse())
6844       break;
6845     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6846     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6847     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6848     if (Op0.getOpcode() == ISD::FNEG)
6849       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6850                          DAG.getConstant(SignBit, DL, VT));
6851 
6852     assert(Op0.getOpcode() == ISD::FABS);
6853     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6854                        DAG.getConstant(~SignBit, DL, VT));
6855   }
6856   case ISD::ADD:
6857     return performADDCombine(N, DAG, Subtarget);
6858   case ISD::SUB:
6859     return performSUBCombine(N, DAG);
6860   case ISD::AND:
6861     return performANDCombine(N, DAG);
6862   case ISD::OR:
6863     return performORCombine(N, DAG, Subtarget);
6864   case ISD::XOR:
6865     return performXORCombine(N, DAG);
6866   case ISD::ANY_EXTEND:
6867     return performANY_EXTENDCombine(N, DCI, Subtarget);
6868   case ISD::ZERO_EXTEND:
6869     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6870     // type legalization. This is safe because fp_to_uint produces poison if
6871     // it overflows.
6872     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6873         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6874         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6875       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6876                          N->getOperand(0).getOperand(0));
6877     return SDValue();
6878   case RISCVISD::SELECT_CC: {
6879     // Transform
6880     SDValue LHS = N->getOperand(0);
6881     SDValue RHS = N->getOperand(1);
6882     SDValue TrueV = N->getOperand(3);
6883     SDValue FalseV = N->getOperand(4);
6884 
6885     // If the True and False values are the same, we don't need a select_cc.
6886     if (TrueV == FalseV)
6887       return TrueV;
6888 
6889     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6890     if (!ISD::isIntEqualitySetCC(CCVal))
6891       break;
6892 
6893     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6894     //      (select_cc X, Y, lt, trueV, falseV)
6895     // Sometimes the setcc is introduced after select_cc has been formed.
6896     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6897         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6898       // If we're looking for eq 0 instead of ne 0, we need to invert the
6899       // condition.
6900       bool Invert = CCVal == ISD::SETEQ;
6901       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6902       if (Invert)
6903         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6904 
6905       SDLoc DL(N);
6906       RHS = LHS.getOperand(1);
6907       LHS = LHS.getOperand(0);
6908       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6909 
6910       SDValue TargetCC = DAG.getCondCode(CCVal);
6911       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6912                          {LHS, RHS, TargetCC, TrueV, FalseV});
6913     }
6914 
6915     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6916     //      (select_cc X, Y, eq/ne, trueV, falseV)
6917     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6918       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6919                          {LHS.getOperand(0), LHS.getOperand(1),
6920                           N->getOperand(2), TrueV, FalseV});
6921     // (select_cc X, 1, setne, trueV, falseV) ->
6922     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6923     // This can occur when legalizing some floating point comparisons.
6924     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6925     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6926       SDLoc DL(N);
6927       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6928       SDValue TargetCC = DAG.getCondCode(CCVal);
6929       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6930       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6931                          {LHS, RHS, TargetCC, TrueV, FalseV});
6932     }
6933 
6934     break;
6935   }
6936   case RISCVISD::BR_CC: {
6937     SDValue LHS = N->getOperand(1);
6938     SDValue RHS = N->getOperand(2);
6939     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6940     if (!ISD::isIntEqualitySetCC(CCVal))
6941       break;
6942 
6943     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6944     //      (br_cc X, Y, lt, dest)
6945     // Sometimes the setcc is introduced after br_cc has been formed.
6946     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6947         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6948       // If we're looking for eq 0 instead of ne 0, we need to invert the
6949       // condition.
6950       bool Invert = CCVal == ISD::SETEQ;
6951       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6952       if (Invert)
6953         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6954 
6955       SDLoc DL(N);
6956       RHS = LHS.getOperand(1);
6957       LHS = LHS.getOperand(0);
6958       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6959 
6960       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6961                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
6962                          N->getOperand(4));
6963     }
6964 
6965     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
6966     //      (br_cc X, Y, eq/ne, trueV, falseV)
6967     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6968       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
6969                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
6970                          N->getOperand(3), N->getOperand(4));
6971 
6972     // (br_cc X, 1, setne, br_cc) ->
6973     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
6974     // This can occur when legalizing some floating point comparisons.
6975     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6976     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6977       SDLoc DL(N);
6978       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6979       SDValue TargetCC = DAG.getCondCode(CCVal);
6980       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6981       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6982                          N->getOperand(0), LHS, RHS, TargetCC,
6983                          N->getOperand(4));
6984     }
6985     break;
6986   }
6987   case ISD::FCOPYSIGN: {
6988     EVT VT = N->getValueType(0);
6989     if (!VT.isVector())
6990       break;
6991     // There is a form of VFSGNJ which injects the negated sign of its second
6992     // operand. Try and bubble any FNEG up after the extend/round to produce
6993     // this optimized pattern. Avoid modifying cases where FP_ROUND and
6994     // TRUNC=1.
6995     SDValue In2 = N->getOperand(1);
6996     // Avoid cases where the extend/round has multiple uses, as duplicating
6997     // those is typically more expensive than removing a fneg.
6998     if (!In2.hasOneUse())
6999       break;
7000     if (In2.getOpcode() != ISD::FP_EXTEND &&
7001         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7002       break;
7003     In2 = In2.getOperand(0);
7004     if (In2.getOpcode() != ISD::FNEG)
7005       break;
7006     SDLoc DL(N);
7007     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7008     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7009                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7010   }
7011   case ISD::MGATHER:
7012   case ISD::MSCATTER:
7013   case ISD::VP_GATHER:
7014   case ISD::VP_SCATTER: {
7015     if (!DCI.isBeforeLegalize())
7016       break;
7017     SDValue Index, ScaleOp;
7018     bool IsIndexScaled = false;
7019     bool IsIndexSigned = false;
7020     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7021       Index = VPGSN->getIndex();
7022       ScaleOp = VPGSN->getScale();
7023       IsIndexScaled = VPGSN->isIndexScaled();
7024       IsIndexSigned = VPGSN->isIndexSigned();
7025     } else {
7026       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7027       Index = MGSN->getIndex();
7028       ScaleOp = MGSN->getScale();
7029       IsIndexScaled = MGSN->isIndexScaled();
7030       IsIndexSigned = MGSN->isIndexSigned();
7031     }
7032     EVT IndexVT = Index.getValueType();
7033     MVT XLenVT = Subtarget.getXLenVT();
7034     // RISCV indexed loads only support the "unsigned unscaled" addressing
7035     // mode, so anything else must be manually legalized.
7036     bool NeedsIdxLegalization =
7037         IsIndexScaled ||
7038         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7039     if (!NeedsIdxLegalization)
7040       break;
7041 
7042     SDLoc DL(N);
7043 
7044     // Any index legalization should first promote to XLenVT, so we don't lose
7045     // bits when scaling. This may create an illegal index type so we let
7046     // LLVM's legalization take care of the splitting.
7047     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7048     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7049       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7050       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7051                           DL, IndexVT, Index);
7052     }
7053 
7054     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7055     if (IsIndexScaled && Scale != 1) {
7056       // Manually scale the indices by the element size.
7057       // TODO: Sanitize the scale operand here?
7058       // TODO: For VP nodes, should we use VP_SHL here?
7059       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7060       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7061       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7062     }
7063 
7064     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7065     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7066       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7067                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7068                               VPGN->getScale(), VPGN->getMask(),
7069                               VPGN->getVectorLength()},
7070                              VPGN->getMemOperand(), NewIndexTy);
7071     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7072       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7073                               {VPSN->getChain(), VPSN->getValue(),
7074                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7075                                VPSN->getMask(), VPSN->getVectorLength()},
7076                               VPSN->getMemOperand(), NewIndexTy);
7077     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7078       return DAG.getMaskedGather(
7079           N->getVTList(), MGN->getMemoryVT(), DL,
7080           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7081            MGN->getBasePtr(), Index, MGN->getScale()},
7082           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7083     const auto *MSN = cast<MaskedScatterSDNode>(N);
7084     return DAG.getMaskedScatter(
7085         N->getVTList(), MSN->getMemoryVT(), DL,
7086         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7087          Index, MSN->getScale()},
7088         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7089   }
7090   case RISCVISD::SRA_VL:
7091   case RISCVISD::SRL_VL:
7092   case RISCVISD::SHL_VL: {
7093     SDValue ShAmt = N->getOperand(1);
7094     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7095       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7096       SDLoc DL(N);
7097       SDValue VL = N->getOperand(3);
7098       EVT VT = N->getValueType(0);
7099       ShAmt =
7100           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7101       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7102                          N->getOperand(2), N->getOperand(3));
7103     }
7104     break;
7105   }
7106   case ISD::SRA:
7107   case ISD::SRL:
7108   case ISD::SHL: {
7109     SDValue ShAmt = N->getOperand(1);
7110     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7111       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7112       SDLoc DL(N);
7113       EVT VT = N->getValueType(0);
7114       ShAmt =
7115           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7116       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7117     }
7118     break;
7119   }
7120   case RISCVISD::MUL_VL: {
7121     SDValue Op0 = N->getOperand(0);
7122     SDValue Op1 = N->getOperand(1);
7123     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7124       return V;
7125     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7126       return V;
7127     return SDValue();
7128   }
7129   case ISD::STORE: {
7130     auto *Store = cast<StoreSDNode>(N);
7131     SDValue Val = Store->getValue();
7132     // Combine store of vmv.x.s to vse with VL of 1.
7133     // FIXME: Support FP.
7134     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7135       SDValue Src = Val.getOperand(0);
7136       EVT VecVT = Src.getValueType();
7137       EVT MemVT = Store->getMemoryVT();
7138       // The memory VT and the element type must match.
7139       if (VecVT.getVectorElementType() == MemVT) {
7140         SDLoc DL(N);
7141         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7142         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7143                               DAG.getConstant(1, DL, MaskVT),
7144                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7145                               Store->getPointerInfo(),
7146                               Store->getOriginalAlign(),
7147                               Store->getMemOperand()->getFlags());
7148       }
7149     }
7150 
7151     break;
7152   }
7153   }
7154 
7155   return SDValue();
7156 }
7157 
7158 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7159     const SDNode *N, CombineLevel Level) const {
7160   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7161   // materialised in fewer instructions than `(OP _, c1)`:
7162   //
7163   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7164   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7165   SDValue N0 = N->getOperand(0);
7166   EVT Ty = N0.getValueType();
7167   if (Ty.isScalarInteger() &&
7168       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7169     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7170     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7171     if (C1 && C2) {
7172       const APInt &C1Int = C1->getAPIntValue();
7173       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7174 
7175       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7176       // and the combine should happen, to potentially allow further combines
7177       // later.
7178       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7179           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7180         return true;
7181 
7182       // We can materialise `c1` in an add immediate, so it's "free", and the
7183       // combine should be prevented.
7184       if (C1Int.getMinSignedBits() <= 64 &&
7185           isLegalAddImmediate(C1Int.getSExtValue()))
7186         return false;
7187 
7188       // Neither constant will fit into an immediate, so find materialisation
7189       // costs.
7190       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7191                                               Subtarget.getFeatureBits(),
7192                                               /*CompressionCost*/true);
7193       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7194           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7195           /*CompressionCost*/true);
7196 
7197       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7198       // combine should be prevented.
7199       if (C1Cost < ShiftedC1Cost)
7200         return false;
7201     }
7202   }
7203   return true;
7204 }
7205 
7206 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7207     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7208     TargetLoweringOpt &TLO) const {
7209   // Delay this optimization as late as possible.
7210   if (!TLO.LegalOps)
7211     return false;
7212 
7213   EVT VT = Op.getValueType();
7214   if (VT.isVector())
7215     return false;
7216 
7217   // Only handle AND for now.
7218   if (Op.getOpcode() != ISD::AND)
7219     return false;
7220 
7221   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7222   if (!C)
7223     return false;
7224 
7225   const APInt &Mask = C->getAPIntValue();
7226 
7227   // Clear all non-demanded bits initially.
7228   APInt ShrunkMask = Mask & DemandedBits;
7229 
7230   // Try to make a smaller immediate by setting undemanded bits.
7231 
7232   APInt ExpandedMask = Mask | ~DemandedBits;
7233 
7234   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7235     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7236   };
7237   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7238     if (NewMask == Mask)
7239       return true;
7240     SDLoc DL(Op);
7241     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7242     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7243     return TLO.CombineTo(Op, NewOp);
7244   };
7245 
7246   // If the shrunk mask fits in sign extended 12 bits, let the target
7247   // independent code apply it.
7248   if (ShrunkMask.isSignedIntN(12))
7249     return false;
7250 
7251   // Preserve (and X, 0xffff) when zext.h is supported.
7252   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7253     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7254     if (IsLegalMask(NewMask))
7255       return UseMask(NewMask);
7256   }
7257 
7258   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7259   if (VT == MVT::i64) {
7260     APInt NewMask = APInt(64, 0xffffffff);
7261     if (IsLegalMask(NewMask))
7262       return UseMask(NewMask);
7263   }
7264 
7265   // For the remaining optimizations, we need to be able to make a negative
7266   // number through a combination of mask and undemanded bits.
7267   if (!ExpandedMask.isNegative())
7268     return false;
7269 
7270   // What is the fewest number of bits we need to represent the negative number.
7271   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7272 
7273   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7274   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7275   APInt NewMask = ShrunkMask;
7276   if (MinSignedBits <= 12)
7277     NewMask.setBitsFrom(11);
7278   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7279     NewMask.setBitsFrom(31);
7280   else
7281     return false;
7282 
7283   // Sanity check that our new mask is a subset of the demanded mask.
7284   assert(IsLegalMask(NewMask));
7285   return UseMask(NewMask);
7286 }
7287 
7288 static void computeGREV(APInt &Src, unsigned ShAmt) {
7289   ShAmt &= Src.getBitWidth() - 1;
7290   uint64_t x = Src.getZExtValue();
7291   if (ShAmt & 1)
7292     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7293   if (ShAmt & 2)
7294     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7295   if (ShAmt & 4)
7296     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7297   if (ShAmt & 8)
7298     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7299   if (ShAmt & 16)
7300     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7301   if (ShAmt & 32)
7302     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7303   Src = x;
7304 }
7305 
7306 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7307                                                         KnownBits &Known,
7308                                                         const APInt &DemandedElts,
7309                                                         const SelectionDAG &DAG,
7310                                                         unsigned Depth) const {
7311   unsigned BitWidth = Known.getBitWidth();
7312   unsigned Opc = Op.getOpcode();
7313   assert((Opc >= ISD::BUILTIN_OP_END ||
7314           Opc == ISD::INTRINSIC_WO_CHAIN ||
7315           Opc == ISD::INTRINSIC_W_CHAIN ||
7316           Opc == ISD::INTRINSIC_VOID) &&
7317          "Should use MaskedValueIsZero if you don't know whether Op"
7318          " is a target node!");
7319 
7320   Known.resetAll();
7321   switch (Opc) {
7322   default: break;
7323   case RISCVISD::SELECT_CC: {
7324     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7325     // If we don't know any bits, early out.
7326     if (Known.isUnknown())
7327       break;
7328     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7329 
7330     // Only known if known in both the LHS and RHS.
7331     Known = KnownBits::commonBits(Known, Known2);
7332     break;
7333   }
7334   case RISCVISD::REMUW: {
7335     KnownBits Known2;
7336     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7337     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7338     // We only care about the lower 32 bits.
7339     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7340     // Restore the original width by sign extending.
7341     Known = Known.sext(BitWidth);
7342     break;
7343   }
7344   case RISCVISD::DIVUW: {
7345     KnownBits Known2;
7346     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7347     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7348     // We only care about the lower 32 bits.
7349     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7350     // Restore the original width by sign extending.
7351     Known = Known.sext(BitWidth);
7352     break;
7353   }
7354   case RISCVISD::CTZW: {
7355     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7356     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7357     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7358     Known.Zero.setBitsFrom(LowBits);
7359     break;
7360   }
7361   case RISCVISD::CLZW: {
7362     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7363     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7364     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7365     Known.Zero.setBitsFrom(LowBits);
7366     break;
7367   }
7368   case RISCVISD::GREV:
7369   case RISCVISD::GREVW: {
7370     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7371       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7372       if (Opc == RISCVISD::GREVW)
7373         Known = Known.trunc(32);
7374       unsigned ShAmt = C->getZExtValue();
7375       computeGREV(Known.Zero, ShAmt);
7376       computeGREV(Known.One, ShAmt);
7377       if (Opc == RISCVISD::GREVW)
7378         Known = Known.sext(BitWidth);
7379     }
7380     break;
7381   }
7382   case RISCVISD::READ_VLENB:
7383     // We assume VLENB is at least 16 bytes.
7384     Known.Zero.setLowBits(4);
7385     // We assume VLENB is no more than 65536 / 8 bytes.
7386     Known.Zero.setBitsFrom(14);
7387     break;
7388   case ISD::INTRINSIC_W_CHAIN: {
7389     unsigned IntNo = Op.getConstantOperandVal(1);
7390     switch (IntNo) {
7391     default:
7392       // We can't do anything for most intrinsics.
7393       break;
7394     case Intrinsic::riscv_vsetvli:
7395     case Intrinsic::riscv_vsetvlimax:
7396       // Assume that VL output is positive and would fit in an int32_t.
7397       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7398       if (BitWidth >= 32)
7399         Known.Zero.setBitsFrom(31);
7400       break;
7401     }
7402     break;
7403   }
7404   }
7405 }
7406 
7407 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7408     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7409     unsigned Depth) const {
7410   switch (Op.getOpcode()) {
7411   default:
7412     break;
7413   case RISCVISD::SELECT_CC: {
7414     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7415     if (Tmp == 1) return 1;  // Early out.
7416     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7417     return std::min(Tmp, Tmp2);
7418   }
7419   case RISCVISD::SLLW:
7420   case RISCVISD::SRAW:
7421   case RISCVISD::SRLW:
7422   case RISCVISD::DIVW:
7423   case RISCVISD::DIVUW:
7424   case RISCVISD::REMUW:
7425   case RISCVISD::ROLW:
7426   case RISCVISD::RORW:
7427   case RISCVISD::GREVW:
7428   case RISCVISD::GORCW:
7429   case RISCVISD::FSLW:
7430   case RISCVISD::FSRW:
7431   case RISCVISD::SHFLW:
7432   case RISCVISD::UNSHFLW:
7433   case RISCVISD::BCOMPRESSW:
7434   case RISCVISD::BDECOMPRESSW:
7435   case RISCVISD::FCVT_W_RTZ_RV64:
7436   case RISCVISD::FCVT_WU_RTZ_RV64:
7437     // TODO: As the result is sign-extended, this is conservatively correct. A
7438     // more precise answer could be calculated for SRAW depending on known
7439     // bits in the shift amount.
7440     return 33;
7441   case RISCVISD::SHFL:
7442   case RISCVISD::UNSHFL: {
7443     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7444     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7445     // will stay within the upper 32 bits. If there were more than 32 sign bits
7446     // before there will be at least 33 sign bits after.
7447     if (Op.getValueType() == MVT::i64 &&
7448         isa<ConstantSDNode>(Op.getOperand(1)) &&
7449         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7450       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7451       if (Tmp > 32)
7452         return 33;
7453     }
7454     break;
7455   }
7456   case RISCVISD::VMV_X_S:
7457     // The number of sign bits of the scalar result is computed by obtaining the
7458     // element type of the input vector operand, subtracting its width from the
7459     // XLEN, and then adding one (sign bit within the element type). If the
7460     // element type is wider than XLen, the least-significant XLEN bits are
7461     // taken.
7462     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7463       return 1;
7464     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
7465   }
7466 
7467   return 1;
7468 }
7469 
7470 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
7471                                                   MachineBasicBlock *BB) {
7472   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
7473 
7474   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
7475   // Should the count have wrapped while it was being read, we need to try
7476   // again.
7477   // ...
7478   // read:
7479   // rdcycleh x3 # load high word of cycle
7480   // rdcycle  x2 # load low word of cycle
7481   // rdcycleh x4 # load high word of cycle
7482   // bne x3, x4, read # check if high word reads match, otherwise try again
7483   // ...
7484 
7485   MachineFunction &MF = *BB->getParent();
7486   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7487   MachineFunction::iterator It = ++BB->getIterator();
7488 
7489   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7490   MF.insert(It, LoopMBB);
7491 
7492   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7493   MF.insert(It, DoneMBB);
7494 
7495   // Transfer the remainder of BB and its successor edges to DoneMBB.
7496   DoneMBB->splice(DoneMBB->begin(), BB,
7497                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7498   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
7499 
7500   BB->addSuccessor(LoopMBB);
7501 
7502   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7503   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7504   Register LoReg = MI.getOperand(0).getReg();
7505   Register HiReg = MI.getOperand(1).getReg();
7506   DebugLoc DL = MI.getDebugLoc();
7507 
7508   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
7509   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
7510       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7511       .addReg(RISCV::X0);
7512   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
7513       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
7514       .addReg(RISCV::X0);
7515   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7516       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7517       .addReg(RISCV::X0);
7518 
7519   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7520       .addReg(HiReg)
7521       .addReg(ReadAgainReg)
7522       .addMBB(LoopMBB);
7523 
7524   LoopMBB->addSuccessor(LoopMBB);
7525   LoopMBB->addSuccessor(DoneMBB);
7526 
7527   MI.eraseFromParent();
7528 
7529   return DoneMBB;
7530 }
7531 
7532 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7533                                              MachineBasicBlock *BB) {
7534   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7535 
7536   MachineFunction &MF = *BB->getParent();
7537   DebugLoc DL = MI.getDebugLoc();
7538   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7539   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7540   Register LoReg = MI.getOperand(0).getReg();
7541   Register HiReg = MI.getOperand(1).getReg();
7542   Register SrcReg = MI.getOperand(2).getReg();
7543   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7544   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7545 
7546   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7547                           RI);
7548   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7549   MachineMemOperand *MMOLo =
7550       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7551   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7552       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7553   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7554       .addFrameIndex(FI)
7555       .addImm(0)
7556       .addMemOperand(MMOLo);
7557   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7558       .addFrameIndex(FI)
7559       .addImm(4)
7560       .addMemOperand(MMOHi);
7561   MI.eraseFromParent(); // The pseudo instruction is gone now.
7562   return BB;
7563 }
7564 
7565 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7566                                                  MachineBasicBlock *BB) {
7567   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7568          "Unexpected instruction");
7569 
7570   MachineFunction &MF = *BB->getParent();
7571   DebugLoc DL = MI.getDebugLoc();
7572   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7573   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7574   Register DstReg = MI.getOperand(0).getReg();
7575   Register LoReg = MI.getOperand(1).getReg();
7576   Register HiReg = MI.getOperand(2).getReg();
7577   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7578   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7579 
7580   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7581   MachineMemOperand *MMOLo =
7582       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7583   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7584       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7585   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7586       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7587       .addFrameIndex(FI)
7588       .addImm(0)
7589       .addMemOperand(MMOLo);
7590   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7591       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7592       .addFrameIndex(FI)
7593       .addImm(4)
7594       .addMemOperand(MMOHi);
7595   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7596   MI.eraseFromParent(); // The pseudo instruction is gone now.
7597   return BB;
7598 }
7599 
7600 static bool isSelectPseudo(MachineInstr &MI) {
7601   switch (MI.getOpcode()) {
7602   default:
7603     return false;
7604   case RISCV::Select_GPR_Using_CC_GPR:
7605   case RISCV::Select_FPR16_Using_CC_GPR:
7606   case RISCV::Select_FPR32_Using_CC_GPR:
7607   case RISCV::Select_FPR64_Using_CC_GPR:
7608     return true;
7609   }
7610 }
7611 
7612 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7613                                            MachineBasicBlock *BB,
7614                                            const RISCVSubtarget &Subtarget) {
7615   // To "insert" Select_* instructions, we actually have to insert the triangle
7616   // control-flow pattern.  The incoming instructions know the destination vreg
7617   // to set, the condition code register to branch on, the true/false values to
7618   // select between, and the condcode to use to select the appropriate branch.
7619   //
7620   // We produce the following control flow:
7621   //     HeadMBB
7622   //     |  \
7623   //     |  IfFalseMBB
7624   //     | /
7625   //    TailMBB
7626   //
7627   // When we find a sequence of selects we attempt to optimize their emission
7628   // by sharing the control flow. Currently we only handle cases where we have
7629   // multiple selects with the exact same condition (same LHS, RHS and CC).
7630   // The selects may be interleaved with other instructions if the other
7631   // instructions meet some requirements we deem safe:
7632   // - They are debug instructions. Otherwise,
7633   // - They do not have side-effects, do not access memory and their inputs do
7634   //   not depend on the results of the select pseudo-instructions.
7635   // The TrueV/FalseV operands of the selects cannot depend on the result of
7636   // previous selects in the sequence.
7637   // These conditions could be further relaxed. See the X86 target for a
7638   // related approach and more information.
7639   Register LHS = MI.getOperand(1).getReg();
7640   Register RHS = MI.getOperand(2).getReg();
7641   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7642 
7643   SmallVector<MachineInstr *, 4> SelectDebugValues;
7644   SmallSet<Register, 4> SelectDests;
7645   SelectDests.insert(MI.getOperand(0).getReg());
7646 
7647   MachineInstr *LastSelectPseudo = &MI;
7648 
7649   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7650        SequenceMBBI != E; ++SequenceMBBI) {
7651     if (SequenceMBBI->isDebugInstr())
7652       continue;
7653     else if (isSelectPseudo(*SequenceMBBI)) {
7654       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7655           SequenceMBBI->getOperand(2).getReg() != RHS ||
7656           SequenceMBBI->getOperand(3).getImm() != CC ||
7657           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7658           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7659         break;
7660       LastSelectPseudo = &*SequenceMBBI;
7661       SequenceMBBI->collectDebugValues(SelectDebugValues);
7662       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7663     } else {
7664       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7665           SequenceMBBI->mayLoadOrStore())
7666         break;
7667       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7668             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7669           }))
7670         break;
7671     }
7672   }
7673 
7674   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7675   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7676   DebugLoc DL = MI.getDebugLoc();
7677   MachineFunction::iterator I = ++BB->getIterator();
7678 
7679   MachineBasicBlock *HeadMBB = BB;
7680   MachineFunction *F = BB->getParent();
7681   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7682   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7683 
7684   F->insert(I, IfFalseMBB);
7685   F->insert(I, TailMBB);
7686 
7687   // Transfer debug instructions associated with the selects to TailMBB.
7688   for (MachineInstr *DebugInstr : SelectDebugValues) {
7689     TailMBB->push_back(DebugInstr->removeFromParent());
7690   }
7691 
7692   // Move all instructions after the sequence to TailMBB.
7693   TailMBB->splice(TailMBB->end(), HeadMBB,
7694                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7695   // Update machine-CFG edges by transferring all successors of the current
7696   // block to the new block which will contain the Phi nodes for the selects.
7697   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7698   // Set the successors for HeadMBB.
7699   HeadMBB->addSuccessor(IfFalseMBB);
7700   HeadMBB->addSuccessor(TailMBB);
7701 
7702   // Insert appropriate branch.
7703   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7704     .addReg(LHS)
7705     .addReg(RHS)
7706     .addMBB(TailMBB);
7707 
7708   // IfFalseMBB just falls through to TailMBB.
7709   IfFalseMBB->addSuccessor(TailMBB);
7710 
7711   // Create PHIs for all of the select pseudo-instructions.
7712   auto SelectMBBI = MI.getIterator();
7713   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7714   auto InsertionPoint = TailMBB->begin();
7715   while (SelectMBBI != SelectEnd) {
7716     auto Next = std::next(SelectMBBI);
7717     if (isSelectPseudo(*SelectMBBI)) {
7718       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7719       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7720               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7721           .addReg(SelectMBBI->getOperand(4).getReg())
7722           .addMBB(HeadMBB)
7723           .addReg(SelectMBBI->getOperand(5).getReg())
7724           .addMBB(IfFalseMBB);
7725       SelectMBBI->eraseFromParent();
7726     }
7727     SelectMBBI = Next;
7728   }
7729 
7730   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7731   return TailMBB;
7732 }
7733 
7734 MachineBasicBlock *
7735 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7736                                                  MachineBasicBlock *BB) const {
7737   switch (MI.getOpcode()) {
7738   default:
7739     llvm_unreachable("Unexpected instr type to insert");
7740   case RISCV::ReadCycleWide:
7741     assert(!Subtarget.is64Bit() &&
7742            "ReadCycleWrite is only to be used on riscv32");
7743     return emitReadCycleWidePseudo(MI, BB);
7744   case RISCV::Select_GPR_Using_CC_GPR:
7745   case RISCV::Select_FPR16_Using_CC_GPR:
7746   case RISCV::Select_FPR32_Using_CC_GPR:
7747   case RISCV::Select_FPR64_Using_CC_GPR:
7748     return emitSelectPseudo(MI, BB, Subtarget);
7749   case RISCV::BuildPairF64Pseudo:
7750     return emitBuildPairF64Pseudo(MI, BB);
7751   case RISCV::SplitF64Pseudo:
7752     return emitSplitF64Pseudo(MI, BB);
7753   }
7754 }
7755 
7756 // Calling Convention Implementation.
7757 // The expectations for frontend ABI lowering vary from target to target.
7758 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7759 // details, but this is a longer term goal. For now, we simply try to keep the
7760 // role of the frontend as simple and well-defined as possible. The rules can
7761 // be summarised as:
7762 // * Never split up large scalar arguments. We handle them here.
7763 // * If a hardfloat calling convention is being used, and the struct may be
7764 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7765 // available, then pass as two separate arguments. If either the GPRs or FPRs
7766 // are exhausted, then pass according to the rule below.
7767 // * If a struct could never be passed in registers or directly in a stack
7768 // slot (as it is larger than 2*XLEN and the floating point rules don't
7769 // apply), then pass it using a pointer with the byval attribute.
7770 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7771 // word-sized array or a 2*XLEN scalar (depending on alignment).
7772 // * The frontend can determine whether a struct is returned by reference or
7773 // not based on its size and fields. If it will be returned by reference, the
7774 // frontend must modify the prototype so a pointer with the sret annotation is
7775 // passed as the first argument. This is not necessary for large scalar
7776 // returns.
7777 // * Struct return values and varargs should be coerced to structs containing
7778 // register-size fields in the same situations they would be for fixed
7779 // arguments.
7780 
7781 static const MCPhysReg ArgGPRs[] = {
7782   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7783   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7784 };
7785 static const MCPhysReg ArgFPR16s[] = {
7786   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7787   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7788 };
7789 static const MCPhysReg ArgFPR32s[] = {
7790   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7791   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7792 };
7793 static const MCPhysReg ArgFPR64s[] = {
7794   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7795   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7796 };
7797 // This is an interim calling convention and it may be changed in the future.
7798 static const MCPhysReg ArgVRs[] = {
7799     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7800     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7801     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7802 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7803                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7804                                      RISCV::V20M2, RISCV::V22M2};
7805 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7806                                      RISCV::V20M4};
7807 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7808 
7809 // Pass a 2*XLEN argument that has been split into two XLEN values through
7810 // registers or the stack as necessary.
7811 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7812                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7813                                 MVT ValVT2, MVT LocVT2,
7814                                 ISD::ArgFlagsTy ArgFlags2) {
7815   unsigned XLenInBytes = XLen / 8;
7816   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7817     // At least one half can be passed via register.
7818     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7819                                      VA1.getLocVT(), CCValAssign::Full));
7820   } else {
7821     // Both halves must be passed on the stack, with proper alignment.
7822     Align StackAlign =
7823         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7824     State.addLoc(
7825         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7826                             State.AllocateStack(XLenInBytes, StackAlign),
7827                             VA1.getLocVT(), CCValAssign::Full));
7828     State.addLoc(CCValAssign::getMem(
7829         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7830         LocVT2, CCValAssign::Full));
7831     return false;
7832   }
7833 
7834   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7835     // The second half can also be passed via register.
7836     State.addLoc(
7837         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7838   } else {
7839     // The second half is passed via the stack, without additional alignment.
7840     State.addLoc(CCValAssign::getMem(
7841         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7842         LocVT2, CCValAssign::Full));
7843   }
7844 
7845   return false;
7846 }
7847 
7848 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7849                                Optional<unsigned> FirstMaskArgument,
7850                                CCState &State, const RISCVTargetLowering &TLI) {
7851   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7852   if (RC == &RISCV::VRRegClass) {
7853     // Assign the first mask argument to V0.
7854     // This is an interim calling convention and it may be changed in the
7855     // future.
7856     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7857       return State.AllocateReg(RISCV::V0);
7858     return State.AllocateReg(ArgVRs);
7859   }
7860   if (RC == &RISCV::VRM2RegClass)
7861     return State.AllocateReg(ArgVRM2s);
7862   if (RC == &RISCV::VRM4RegClass)
7863     return State.AllocateReg(ArgVRM4s);
7864   if (RC == &RISCV::VRM8RegClass)
7865     return State.AllocateReg(ArgVRM8s);
7866   llvm_unreachable("Unhandled register class for ValueType");
7867 }
7868 
7869 // Implements the RISC-V calling convention. Returns true upon failure.
7870 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7871                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7872                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7873                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7874                      Optional<unsigned> FirstMaskArgument) {
7875   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7876   assert(XLen == 32 || XLen == 64);
7877   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7878 
7879   // Any return value split in to more than two values can't be returned
7880   // directly. Vectors are returned via the available vector registers.
7881   if (!LocVT.isVector() && IsRet && ValNo > 1)
7882     return true;
7883 
7884   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7885   // variadic argument, or if no F16/F32 argument registers are available.
7886   bool UseGPRForF16_F32 = true;
7887   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7888   // variadic argument, or if no F64 argument registers are available.
7889   bool UseGPRForF64 = true;
7890 
7891   switch (ABI) {
7892   default:
7893     llvm_unreachable("Unexpected ABI");
7894   case RISCVABI::ABI_ILP32:
7895   case RISCVABI::ABI_LP64:
7896     break;
7897   case RISCVABI::ABI_ILP32F:
7898   case RISCVABI::ABI_LP64F:
7899     UseGPRForF16_F32 = !IsFixed;
7900     break;
7901   case RISCVABI::ABI_ILP32D:
7902   case RISCVABI::ABI_LP64D:
7903     UseGPRForF16_F32 = !IsFixed;
7904     UseGPRForF64 = !IsFixed;
7905     break;
7906   }
7907 
7908   // FPR16, FPR32, and FPR64 alias each other.
7909   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7910     UseGPRForF16_F32 = true;
7911     UseGPRForF64 = true;
7912   }
7913 
7914   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7915   // similar local variables rather than directly checking against the target
7916   // ABI.
7917 
7918   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7919     LocVT = XLenVT;
7920     LocInfo = CCValAssign::BCvt;
7921   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7922     LocVT = MVT::i64;
7923     LocInfo = CCValAssign::BCvt;
7924   }
7925 
7926   // If this is a variadic argument, the RISC-V calling convention requires
7927   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7928   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7929   // be used regardless of whether the original argument was split during
7930   // legalisation or not. The argument will not be passed by registers if the
7931   // original type is larger than 2*XLEN, so the register alignment rule does
7932   // not apply.
7933   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7934   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7935       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7936     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7937     // Skip 'odd' register if necessary.
7938     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7939       State.AllocateReg(ArgGPRs);
7940   }
7941 
7942   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7943   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7944       State.getPendingArgFlags();
7945 
7946   assert(PendingLocs.size() == PendingArgFlags.size() &&
7947          "PendingLocs and PendingArgFlags out of sync");
7948 
7949   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7950   // registers are exhausted.
7951   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
7952     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
7953            "Can't lower f64 if it is split");
7954     // Depending on available argument GPRS, f64 may be passed in a pair of
7955     // GPRs, split between a GPR and the stack, or passed completely on the
7956     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
7957     // cases.
7958     Register Reg = State.AllocateReg(ArgGPRs);
7959     LocVT = MVT::i32;
7960     if (!Reg) {
7961       unsigned StackOffset = State.AllocateStack(8, Align(8));
7962       State.addLoc(
7963           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7964       return false;
7965     }
7966     if (!State.AllocateReg(ArgGPRs))
7967       State.AllocateStack(4, Align(4));
7968     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7969     return false;
7970   }
7971 
7972   // Fixed-length vectors are located in the corresponding scalable-vector
7973   // container types.
7974   if (ValVT.isFixedLengthVector())
7975     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7976 
7977   // Split arguments might be passed indirectly, so keep track of the pending
7978   // values. Split vectors are passed via a mix of registers and indirectly, so
7979   // treat them as we would any other argument.
7980   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
7981     LocVT = XLenVT;
7982     LocInfo = CCValAssign::Indirect;
7983     PendingLocs.push_back(
7984         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
7985     PendingArgFlags.push_back(ArgFlags);
7986     if (!ArgFlags.isSplitEnd()) {
7987       return false;
7988     }
7989   }
7990 
7991   // If the split argument only had two elements, it should be passed directly
7992   // in registers or on the stack.
7993   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
7994       PendingLocs.size() <= 2) {
7995     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
7996     // Apply the normal calling convention rules to the first half of the
7997     // split argument.
7998     CCValAssign VA = PendingLocs[0];
7999     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8000     PendingLocs.clear();
8001     PendingArgFlags.clear();
8002     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8003                                ArgFlags);
8004   }
8005 
8006   // Allocate to a register if possible, or else a stack slot.
8007   Register Reg;
8008   unsigned StoreSizeBytes = XLen / 8;
8009   Align StackAlign = Align(XLen / 8);
8010 
8011   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8012     Reg = State.AllocateReg(ArgFPR16s);
8013   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8014     Reg = State.AllocateReg(ArgFPR32s);
8015   else if (ValVT == MVT::f64 && !UseGPRForF64)
8016     Reg = State.AllocateReg(ArgFPR64s);
8017   else if (ValVT.isVector()) {
8018     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8019     if (!Reg) {
8020       // For return values, the vector must be passed fully via registers or
8021       // via the stack.
8022       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8023       // but we're using all of them.
8024       if (IsRet)
8025         return true;
8026       // Try using a GPR to pass the address
8027       if ((Reg = State.AllocateReg(ArgGPRs))) {
8028         LocVT = XLenVT;
8029         LocInfo = CCValAssign::Indirect;
8030       } else if (ValVT.isScalableVector()) {
8031         report_fatal_error("Unable to pass scalable vector types on the stack");
8032       } else {
8033         // Pass fixed-length vectors on the stack.
8034         LocVT = ValVT;
8035         StoreSizeBytes = ValVT.getStoreSize();
8036         // Align vectors to their element sizes, being careful for vXi1
8037         // vectors.
8038         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8039       }
8040     }
8041   } else {
8042     Reg = State.AllocateReg(ArgGPRs);
8043   }
8044 
8045   unsigned StackOffset =
8046       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8047 
8048   // If we reach this point and PendingLocs is non-empty, we must be at the
8049   // end of a split argument that must be passed indirectly.
8050   if (!PendingLocs.empty()) {
8051     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8052     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8053 
8054     for (auto &It : PendingLocs) {
8055       if (Reg)
8056         It.convertToReg(Reg);
8057       else
8058         It.convertToMem(StackOffset);
8059       State.addLoc(It);
8060     }
8061     PendingLocs.clear();
8062     PendingArgFlags.clear();
8063     return false;
8064   }
8065 
8066   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8067           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
8068          "Expected an XLenVT or vector types at this stage");
8069 
8070   if (Reg) {
8071     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8072     return false;
8073   }
8074 
8075   // When a floating-point value is passed on the stack, no bit-conversion is
8076   // needed.
8077   if (ValVT.isFloatingPoint()) {
8078     LocVT = ValVT;
8079     LocInfo = CCValAssign::Full;
8080   }
8081   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8082   return false;
8083 }
8084 
8085 template <typename ArgTy>
8086 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8087   for (const auto &ArgIdx : enumerate(Args)) {
8088     MVT ArgVT = ArgIdx.value().VT;
8089     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8090       return ArgIdx.index();
8091   }
8092   return None;
8093 }
8094 
8095 void RISCVTargetLowering::analyzeInputArgs(
8096     MachineFunction &MF, CCState &CCInfo,
8097     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8098     RISCVCCAssignFn Fn) const {
8099   unsigned NumArgs = Ins.size();
8100   FunctionType *FType = MF.getFunction().getFunctionType();
8101 
8102   Optional<unsigned> FirstMaskArgument;
8103   if (Subtarget.hasStdExtV())
8104     FirstMaskArgument = preAssignMask(Ins);
8105 
8106   for (unsigned i = 0; i != NumArgs; ++i) {
8107     MVT ArgVT = Ins[i].VT;
8108     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8109 
8110     Type *ArgTy = nullptr;
8111     if (IsRet)
8112       ArgTy = FType->getReturnType();
8113     else if (Ins[i].isOrigArg())
8114       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8115 
8116     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8117     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8118            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8119            FirstMaskArgument)) {
8120       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8121                         << EVT(ArgVT).getEVTString() << '\n');
8122       llvm_unreachable(nullptr);
8123     }
8124   }
8125 }
8126 
8127 void RISCVTargetLowering::analyzeOutputArgs(
8128     MachineFunction &MF, CCState &CCInfo,
8129     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8130     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8131   unsigned NumArgs = Outs.size();
8132 
8133   Optional<unsigned> FirstMaskArgument;
8134   if (Subtarget.hasStdExtV())
8135     FirstMaskArgument = preAssignMask(Outs);
8136 
8137   for (unsigned i = 0; i != NumArgs; i++) {
8138     MVT ArgVT = Outs[i].VT;
8139     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8140     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8141 
8142     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8143     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8144            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8145            FirstMaskArgument)) {
8146       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8147                         << EVT(ArgVT).getEVTString() << "\n");
8148       llvm_unreachable(nullptr);
8149     }
8150   }
8151 }
8152 
8153 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8154 // values.
8155 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8156                                    const CCValAssign &VA, const SDLoc &DL,
8157                                    const RISCVSubtarget &Subtarget) {
8158   switch (VA.getLocInfo()) {
8159   default:
8160     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8161   case CCValAssign::Full:
8162     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8163       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8164     break;
8165   case CCValAssign::BCvt:
8166     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8167       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8168     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8169       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8170     else
8171       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8172     break;
8173   }
8174   return Val;
8175 }
8176 
8177 // The caller is responsible for loading the full value if the argument is
8178 // passed with CCValAssign::Indirect.
8179 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8180                                 const CCValAssign &VA, const SDLoc &DL,
8181                                 const RISCVTargetLowering &TLI) {
8182   MachineFunction &MF = DAG.getMachineFunction();
8183   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8184   EVT LocVT = VA.getLocVT();
8185   SDValue Val;
8186   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8187   Register VReg = RegInfo.createVirtualRegister(RC);
8188   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8189   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8190 
8191   if (VA.getLocInfo() == CCValAssign::Indirect)
8192     return Val;
8193 
8194   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8195 }
8196 
8197 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8198                                    const CCValAssign &VA, const SDLoc &DL,
8199                                    const RISCVSubtarget &Subtarget) {
8200   EVT LocVT = VA.getLocVT();
8201 
8202   switch (VA.getLocInfo()) {
8203   default:
8204     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8205   case CCValAssign::Full:
8206     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8207       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8208     break;
8209   case CCValAssign::BCvt:
8210     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8211       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8212     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8213       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8214     else
8215       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8216     break;
8217   }
8218   return Val;
8219 }
8220 
8221 // The caller is responsible for loading the full value if the argument is
8222 // passed with CCValAssign::Indirect.
8223 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8224                                 const CCValAssign &VA, const SDLoc &DL) {
8225   MachineFunction &MF = DAG.getMachineFunction();
8226   MachineFrameInfo &MFI = MF.getFrameInfo();
8227   EVT LocVT = VA.getLocVT();
8228   EVT ValVT = VA.getValVT();
8229   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8230   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8231                                  /*Immutable=*/true);
8232   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8233   SDValue Val;
8234 
8235   ISD::LoadExtType ExtType;
8236   switch (VA.getLocInfo()) {
8237   default:
8238     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8239   case CCValAssign::Full:
8240   case CCValAssign::Indirect:
8241   case CCValAssign::BCvt:
8242     ExtType = ISD::NON_EXTLOAD;
8243     break;
8244   }
8245   Val = DAG.getExtLoad(
8246       ExtType, DL, LocVT, Chain, FIN,
8247       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8248   return Val;
8249 }
8250 
8251 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8252                                        const CCValAssign &VA, const SDLoc &DL) {
8253   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8254          "Unexpected VA");
8255   MachineFunction &MF = DAG.getMachineFunction();
8256   MachineFrameInfo &MFI = MF.getFrameInfo();
8257   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8258 
8259   if (VA.isMemLoc()) {
8260     // f64 is passed on the stack.
8261     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
8262     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8263     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8264                        MachinePointerInfo::getFixedStack(MF, FI));
8265   }
8266 
8267   assert(VA.isRegLoc() && "Expected register VA assignment");
8268 
8269   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8270   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8271   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8272   SDValue Hi;
8273   if (VA.getLocReg() == RISCV::X17) {
8274     // Second half of f64 is passed on the stack.
8275     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
8276     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8277     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8278                      MachinePointerInfo::getFixedStack(MF, FI));
8279   } else {
8280     // Second half of f64 is passed in another GPR.
8281     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8282     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8283     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8284   }
8285   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8286 }
8287 
8288 // FastCC has less than 1% performance improvement for some particular
8289 // benchmark. But theoretically, it may has benenfit for some cases.
8290 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8291                             unsigned ValNo, MVT ValVT, MVT LocVT,
8292                             CCValAssign::LocInfo LocInfo,
8293                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8294                             bool IsFixed, bool IsRet, Type *OrigTy,
8295                             const RISCVTargetLowering &TLI,
8296                             Optional<unsigned> FirstMaskArgument) {
8297 
8298   // X5 and X6 might be used for save-restore libcall.
8299   static const MCPhysReg GPRList[] = {
8300       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8301       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8302       RISCV::X29, RISCV::X30, RISCV::X31};
8303 
8304   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8305     if (unsigned Reg = State.AllocateReg(GPRList)) {
8306       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8307       return false;
8308     }
8309   }
8310 
8311   if (LocVT == MVT::f16) {
8312     static const MCPhysReg FPR16List[] = {
8313         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8314         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8315         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8316         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8317     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8318       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8319       return false;
8320     }
8321   }
8322 
8323   if (LocVT == MVT::f32) {
8324     static const MCPhysReg FPR32List[] = {
8325         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8326         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8327         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8328         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8329     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8330       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8331       return false;
8332     }
8333   }
8334 
8335   if (LocVT == MVT::f64) {
8336     static const MCPhysReg FPR64List[] = {
8337         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8338         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8339         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8340         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8341     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8342       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8343       return false;
8344     }
8345   }
8346 
8347   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8348     unsigned Offset4 = State.AllocateStack(4, Align(4));
8349     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8350     return false;
8351   }
8352 
8353   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8354     unsigned Offset5 = State.AllocateStack(8, Align(8));
8355     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8356     return false;
8357   }
8358 
8359   if (LocVT.isVector()) {
8360     if (unsigned Reg =
8361             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8362       // Fixed-length vectors are located in the corresponding scalable-vector
8363       // container types.
8364       if (ValVT.isFixedLengthVector())
8365         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8366       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8367     } else {
8368       // Try and pass the address via a "fast" GPR.
8369       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8370         LocInfo = CCValAssign::Indirect;
8371         LocVT = TLI.getSubtarget().getXLenVT();
8372         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8373       } else if (ValVT.isFixedLengthVector()) {
8374         auto StackAlign =
8375             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8376         unsigned StackOffset =
8377             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8378         State.addLoc(
8379             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8380       } else {
8381         // Can't pass scalable vectors on the stack.
8382         return true;
8383       }
8384     }
8385 
8386     return false;
8387   }
8388 
8389   return true; // CC didn't match.
8390 }
8391 
8392 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
8393                          CCValAssign::LocInfo LocInfo,
8394                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
8395 
8396   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8397     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
8398     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
8399     static const MCPhysReg GPRList[] = {
8400         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
8401         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
8402     if (unsigned Reg = State.AllocateReg(GPRList)) {
8403       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8404       return false;
8405     }
8406   }
8407 
8408   if (LocVT == MVT::f32) {
8409     // Pass in STG registers: F1, ..., F6
8410     //                        fs0 ... fs5
8411     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
8412                                           RISCV::F18_F, RISCV::F19_F,
8413                                           RISCV::F20_F, RISCV::F21_F};
8414     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8415       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8416       return false;
8417     }
8418   }
8419 
8420   if (LocVT == MVT::f64) {
8421     // Pass in STG registers: D1, ..., D6
8422     //                        fs6 ... fs11
8423     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
8424                                           RISCV::F24_D, RISCV::F25_D,
8425                                           RISCV::F26_D, RISCV::F27_D};
8426     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8427       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8428       return false;
8429     }
8430   }
8431 
8432   report_fatal_error("No registers left in GHC calling convention");
8433   return true;
8434 }
8435 
8436 // Transform physical registers into virtual registers.
8437 SDValue RISCVTargetLowering::LowerFormalArguments(
8438     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
8439     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
8440     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
8441 
8442   MachineFunction &MF = DAG.getMachineFunction();
8443 
8444   switch (CallConv) {
8445   default:
8446     report_fatal_error("Unsupported calling convention");
8447   case CallingConv::C:
8448   case CallingConv::Fast:
8449     break;
8450   case CallingConv::GHC:
8451     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
8452         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
8453       report_fatal_error(
8454         "GHC calling convention requires the F and D instruction set extensions");
8455   }
8456 
8457   const Function &Func = MF.getFunction();
8458   if (Func.hasFnAttribute("interrupt")) {
8459     if (!Func.arg_empty())
8460       report_fatal_error(
8461         "Functions with the interrupt attribute cannot have arguments!");
8462 
8463     StringRef Kind =
8464       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8465 
8466     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
8467       report_fatal_error(
8468         "Function interrupt attribute argument not supported!");
8469   }
8470 
8471   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8472   MVT XLenVT = Subtarget.getXLenVT();
8473   unsigned XLenInBytes = Subtarget.getXLen() / 8;
8474   // Used with vargs to acumulate store chains.
8475   std::vector<SDValue> OutChains;
8476 
8477   // Assign locations to all of the incoming arguments.
8478   SmallVector<CCValAssign, 16> ArgLocs;
8479   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8480 
8481   if (CallConv == CallingConv::GHC)
8482     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
8483   else
8484     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
8485                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8486                                                    : CC_RISCV);
8487 
8488   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
8489     CCValAssign &VA = ArgLocs[i];
8490     SDValue ArgValue;
8491     // Passing f64 on RV32D with a soft float ABI must be handled as a special
8492     // case.
8493     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
8494       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
8495     else if (VA.isRegLoc())
8496       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
8497     else
8498       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
8499 
8500     if (VA.getLocInfo() == CCValAssign::Indirect) {
8501       // If the original argument was split and passed by reference (e.g. i128
8502       // on RV32), we need to load all parts of it here (using the same
8503       // address). Vectors may be partly split to registers and partly to the
8504       // stack, in which case the base address is partly offset and subsequent
8505       // stores are relative to that.
8506       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
8507                                    MachinePointerInfo()));
8508       unsigned ArgIndex = Ins[i].OrigArgIndex;
8509       unsigned ArgPartOffset = Ins[i].PartOffset;
8510       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8511       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
8512         CCValAssign &PartVA = ArgLocs[i + 1];
8513         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
8514         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8515         if (PartVA.getValVT().isScalableVector())
8516           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8517         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8518         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8519                                      MachinePointerInfo()));
8520         ++i;
8521       }
8522       continue;
8523     }
8524     InVals.push_back(ArgValue);
8525   }
8526 
8527   if (IsVarArg) {
8528     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8529     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8530     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8531     MachineFrameInfo &MFI = MF.getFrameInfo();
8532     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8533     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8534 
8535     // Offset of the first variable argument from stack pointer, and size of
8536     // the vararg save area. For now, the varargs save area is either zero or
8537     // large enough to hold a0-a7.
8538     int VaArgOffset, VarArgsSaveSize;
8539 
8540     // If all registers are allocated, then all varargs must be passed on the
8541     // stack and we don't need to save any argregs.
8542     if (ArgRegs.size() == Idx) {
8543       VaArgOffset = CCInfo.getNextStackOffset();
8544       VarArgsSaveSize = 0;
8545     } else {
8546       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8547       VaArgOffset = -VarArgsSaveSize;
8548     }
8549 
8550     // Record the frame index of the first variable argument
8551     // which is a value necessary to VASTART.
8552     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8553     RVFI->setVarArgsFrameIndex(FI);
8554 
8555     // If saving an odd number of registers then create an extra stack slot to
8556     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8557     // offsets to even-numbered registered remain 2*XLEN-aligned.
8558     if (Idx % 2) {
8559       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8560       VarArgsSaveSize += XLenInBytes;
8561     }
8562 
8563     // Copy the integer registers that may have been used for passing varargs
8564     // to the vararg save area.
8565     for (unsigned I = Idx; I < ArgRegs.size();
8566          ++I, VaArgOffset += XLenInBytes) {
8567       const Register Reg = RegInfo.createVirtualRegister(RC);
8568       RegInfo.addLiveIn(ArgRegs[I], Reg);
8569       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8570       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8571       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8572       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8573                                    MachinePointerInfo::getFixedStack(MF, FI));
8574       cast<StoreSDNode>(Store.getNode())
8575           ->getMemOperand()
8576           ->setValue((Value *)nullptr);
8577       OutChains.push_back(Store);
8578     }
8579     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8580   }
8581 
8582   // All stores are grouped in one node to allow the matching between
8583   // the size of Ins and InVals. This only happens for vararg functions.
8584   if (!OutChains.empty()) {
8585     OutChains.push_back(Chain);
8586     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8587   }
8588 
8589   return Chain;
8590 }
8591 
8592 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8593 /// for tail call optimization.
8594 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8595 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8596     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8597     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8598 
8599   auto &Callee = CLI.Callee;
8600   auto CalleeCC = CLI.CallConv;
8601   auto &Outs = CLI.Outs;
8602   auto &Caller = MF.getFunction();
8603   auto CallerCC = Caller.getCallingConv();
8604 
8605   // Exception-handling functions need a special set of instructions to
8606   // indicate a return to the hardware. Tail-calling another function would
8607   // probably break this.
8608   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8609   // should be expanded as new function attributes are introduced.
8610   if (Caller.hasFnAttribute("interrupt"))
8611     return false;
8612 
8613   // Do not tail call opt if the stack is used to pass parameters.
8614   if (CCInfo.getNextStackOffset() != 0)
8615     return false;
8616 
8617   // Do not tail call opt if any parameters need to be passed indirectly.
8618   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8619   // passed indirectly. So the address of the value will be passed in a
8620   // register, or if not available, then the address is put on the stack. In
8621   // order to pass indirectly, space on the stack often needs to be allocated
8622   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8623   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8624   // are passed CCValAssign::Indirect.
8625   for (auto &VA : ArgLocs)
8626     if (VA.getLocInfo() == CCValAssign::Indirect)
8627       return false;
8628 
8629   // Do not tail call opt if either caller or callee uses struct return
8630   // semantics.
8631   auto IsCallerStructRet = Caller.hasStructRetAttr();
8632   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8633   if (IsCallerStructRet || IsCalleeStructRet)
8634     return false;
8635 
8636   // Externally-defined functions with weak linkage should not be
8637   // tail-called. The behaviour of branch instructions in this situation (as
8638   // used for tail calls) is implementation-defined, so we cannot rely on the
8639   // linker replacing the tail call with a return.
8640   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8641     const GlobalValue *GV = G->getGlobal();
8642     if (GV->hasExternalWeakLinkage())
8643       return false;
8644   }
8645 
8646   // The callee has to preserve all registers the caller needs to preserve.
8647   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8648   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8649   if (CalleeCC != CallerCC) {
8650     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8651     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8652       return false;
8653   }
8654 
8655   // Byval parameters hand the function a pointer directly into the stack area
8656   // we want to reuse during a tail call. Working around this *is* possible
8657   // but less efficient and uglier in LowerCall.
8658   for (auto &Arg : Outs)
8659     if (Arg.Flags.isByVal())
8660       return false;
8661 
8662   return true;
8663 }
8664 
8665 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8666   return DAG.getDataLayout().getPrefTypeAlign(
8667       VT.getTypeForEVT(*DAG.getContext()));
8668 }
8669 
8670 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8671 // and output parameter nodes.
8672 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8673                                        SmallVectorImpl<SDValue> &InVals) const {
8674   SelectionDAG &DAG = CLI.DAG;
8675   SDLoc &DL = CLI.DL;
8676   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8677   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8678   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8679   SDValue Chain = CLI.Chain;
8680   SDValue Callee = CLI.Callee;
8681   bool &IsTailCall = CLI.IsTailCall;
8682   CallingConv::ID CallConv = CLI.CallConv;
8683   bool IsVarArg = CLI.IsVarArg;
8684   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8685   MVT XLenVT = Subtarget.getXLenVT();
8686 
8687   MachineFunction &MF = DAG.getMachineFunction();
8688 
8689   // Analyze the operands of the call, assigning locations to each operand.
8690   SmallVector<CCValAssign, 16> ArgLocs;
8691   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8692 
8693   if (CallConv == CallingConv::GHC)
8694     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8695   else
8696     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8697                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8698                                                     : CC_RISCV);
8699 
8700   // Check if it's really possible to do a tail call.
8701   if (IsTailCall)
8702     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8703 
8704   if (IsTailCall)
8705     ++NumTailCalls;
8706   else if (CLI.CB && CLI.CB->isMustTailCall())
8707     report_fatal_error("failed to perform tail call elimination on a call "
8708                        "site marked musttail");
8709 
8710   // Get a count of how many bytes are to be pushed on the stack.
8711   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8712 
8713   // Create local copies for byval args
8714   SmallVector<SDValue, 8> ByValArgs;
8715   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8716     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8717     if (!Flags.isByVal())
8718       continue;
8719 
8720     SDValue Arg = OutVals[i];
8721     unsigned Size = Flags.getByValSize();
8722     Align Alignment = Flags.getNonZeroByValAlign();
8723 
8724     int FI =
8725         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8726     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8727     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8728 
8729     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8730                           /*IsVolatile=*/false,
8731                           /*AlwaysInline=*/false, IsTailCall,
8732                           MachinePointerInfo(), MachinePointerInfo());
8733     ByValArgs.push_back(FIPtr);
8734   }
8735 
8736   if (!IsTailCall)
8737     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8738 
8739   // Copy argument values to their designated locations.
8740   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8741   SmallVector<SDValue, 8> MemOpChains;
8742   SDValue StackPtr;
8743   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8744     CCValAssign &VA = ArgLocs[i];
8745     SDValue ArgValue = OutVals[i];
8746     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8747 
8748     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8749     bool IsF64OnRV32DSoftABI =
8750         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8751     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8752       SDValue SplitF64 = DAG.getNode(
8753           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8754       SDValue Lo = SplitF64.getValue(0);
8755       SDValue Hi = SplitF64.getValue(1);
8756 
8757       Register RegLo = VA.getLocReg();
8758       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8759 
8760       if (RegLo == RISCV::X17) {
8761         // Second half of f64 is passed on the stack.
8762         // Work out the address of the stack slot.
8763         if (!StackPtr.getNode())
8764           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8765         // Emit the store.
8766         MemOpChains.push_back(
8767             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8768       } else {
8769         // Second half of f64 is passed in another GPR.
8770         assert(RegLo < RISCV::X31 && "Invalid register pair");
8771         Register RegHigh = RegLo + 1;
8772         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8773       }
8774       continue;
8775     }
8776 
8777     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8778     // as any other MemLoc.
8779 
8780     // Promote the value if needed.
8781     // For now, only handle fully promoted and indirect arguments.
8782     if (VA.getLocInfo() == CCValAssign::Indirect) {
8783       // Store the argument in a stack slot and pass its address.
8784       Align StackAlign =
8785           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8786                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8787       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8788       // If the original argument was split (e.g. i128), we need
8789       // to store the required parts of it here (and pass just one address).
8790       // Vectors may be partly split to registers and partly to the stack, in
8791       // which case the base address is partly offset and subsequent stores are
8792       // relative to that.
8793       unsigned ArgIndex = Outs[i].OrigArgIndex;
8794       unsigned ArgPartOffset = Outs[i].PartOffset;
8795       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8796       // Calculate the total size to store. We don't have access to what we're
8797       // actually storing other than performing the loop and collecting the
8798       // info.
8799       SmallVector<std::pair<SDValue, SDValue>> Parts;
8800       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8801         SDValue PartValue = OutVals[i + 1];
8802         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8803         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8804         EVT PartVT = PartValue.getValueType();
8805         if (PartVT.isScalableVector())
8806           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8807         StoredSize += PartVT.getStoreSize();
8808         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8809         Parts.push_back(std::make_pair(PartValue, Offset));
8810         ++i;
8811       }
8812       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8813       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8814       MemOpChains.push_back(
8815           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8816                        MachinePointerInfo::getFixedStack(MF, FI)));
8817       for (const auto &Part : Parts) {
8818         SDValue PartValue = Part.first;
8819         SDValue PartOffset = Part.second;
8820         SDValue Address =
8821             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8822         MemOpChains.push_back(
8823             DAG.getStore(Chain, DL, PartValue, Address,
8824                          MachinePointerInfo::getFixedStack(MF, FI)));
8825       }
8826       ArgValue = SpillSlot;
8827     } else {
8828       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8829     }
8830 
8831     // Use local copy if it is a byval arg.
8832     if (Flags.isByVal())
8833       ArgValue = ByValArgs[j++];
8834 
8835     if (VA.isRegLoc()) {
8836       // Queue up the argument copies and emit them at the end.
8837       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8838     } else {
8839       assert(VA.isMemLoc() && "Argument not register or memory");
8840       assert(!IsTailCall && "Tail call not allowed if stack is used "
8841                             "for passing parameters");
8842 
8843       // Work out the address of the stack slot.
8844       if (!StackPtr.getNode())
8845         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8846       SDValue Address =
8847           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8848                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8849 
8850       // Emit the store.
8851       MemOpChains.push_back(
8852           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8853     }
8854   }
8855 
8856   // Join the stores, which are independent of one another.
8857   if (!MemOpChains.empty())
8858     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8859 
8860   SDValue Glue;
8861 
8862   // Build a sequence of copy-to-reg nodes, chained and glued together.
8863   for (auto &Reg : RegsToPass) {
8864     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8865     Glue = Chain.getValue(1);
8866   }
8867 
8868   // Validate that none of the argument registers have been marked as
8869   // reserved, if so report an error. Do the same for the return address if this
8870   // is not a tailcall.
8871   validateCCReservedRegs(RegsToPass, MF);
8872   if (!IsTailCall &&
8873       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8874     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8875         MF.getFunction(),
8876         "Return address register required, but has been reserved."});
8877 
8878   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8879   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8880   // split it and then direct call can be matched by PseudoCALL.
8881   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8882     const GlobalValue *GV = S->getGlobal();
8883 
8884     unsigned OpFlags = RISCVII::MO_CALL;
8885     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8886       OpFlags = RISCVII::MO_PLT;
8887 
8888     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8889   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8890     unsigned OpFlags = RISCVII::MO_CALL;
8891 
8892     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8893                                                  nullptr))
8894       OpFlags = RISCVII::MO_PLT;
8895 
8896     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8897   }
8898 
8899   // The first call operand is the chain and the second is the target address.
8900   SmallVector<SDValue, 8> Ops;
8901   Ops.push_back(Chain);
8902   Ops.push_back(Callee);
8903 
8904   // Add argument registers to the end of the list so that they are
8905   // known live into the call.
8906   for (auto &Reg : RegsToPass)
8907     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8908 
8909   if (!IsTailCall) {
8910     // Add a register mask operand representing the call-preserved registers.
8911     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8912     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8913     assert(Mask && "Missing call preserved mask for calling convention");
8914     Ops.push_back(DAG.getRegisterMask(Mask));
8915   }
8916 
8917   // Glue the call to the argument copies, if any.
8918   if (Glue.getNode())
8919     Ops.push_back(Glue);
8920 
8921   // Emit the call.
8922   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8923 
8924   if (IsTailCall) {
8925     MF.getFrameInfo().setHasTailCall();
8926     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8927   }
8928 
8929   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8930   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8931   Glue = Chain.getValue(1);
8932 
8933   // Mark the end of the call, which is glued to the call itself.
8934   Chain = DAG.getCALLSEQ_END(Chain,
8935                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8936                              DAG.getConstant(0, DL, PtrVT, true),
8937                              Glue, DL);
8938   Glue = Chain.getValue(1);
8939 
8940   // Assign locations to each value returned by this call.
8941   SmallVector<CCValAssign, 16> RVLocs;
8942   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8943   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8944 
8945   // Copy all of the result registers out of their specified physreg.
8946   for (auto &VA : RVLocs) {
8947     // Copy the value out
8948     SDValue RetValue =
8949         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8950     // Glue the RetValue to the end of the call sequence
8951     Chain = RetValue.getValue(1);
8952     Glue = RetValue.getValue(2);
8953 
8954     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8955       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
8956       SDValue RetValue2 =
8957           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
8958       Chain = RetValue2.getValue(1);
8959       Glue = RetValue2.getValue(2);
8960       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
8961                              RetValue2);
8962     }
8963 
8964     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
8965 
8966     InVals.push_back(RetValue);
8967   }
8968 
8969   return Chain;
8970 }
8971 
8972 bool RISCVTargetLowering::CanLowerReturn(
8973     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
8974     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
8975   SmallVector<CCValAssign, 16> RVLocs;
8976   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
8977 
8978   Optional<unsigned> FirstMaskArgument;
8979   if (Subtarget.hasStdExtV())
8980     FirstMaskArgument = preAssignMask(Outs);
8981 
8982   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8983     MVT VT = Outs[i].VT;
8984     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8985     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8986     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
8987                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
8988                  *this, FirstMaskArgument))
8989       return false;
8990   }
8991   return true;
8992 }
8993 
8994 SDValue
8995 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
8996                                  bool IsVarArg,
8997                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
8998                                  const SmallVectorImpl<SDValue> &OutVals,
8999                                  const SDLoc &DL, SelectionDAG &DAG) const {
9000   const MachineFunction &MF = DAG.getMachineFunction();
9001   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9002 
9003   // Stores the assignment of the return value to a location.
9004   SmallVector<CCValAssign, 16> RVLocs;
9005 
9006   // Info about the registers and stack slot.
9007   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9008                  *DAG.getContext());
9009 
9010   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9011                     nullptr, CC_RISCV);
9012 
9013   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9014     report_fatal_error("GHC functions return void only");
9015 
9016   SDValue Glue;
9017   SmallVector<SDValue, 4> RetOps(1, Chain);
9018 
9019   // Copy the result values into the output registers.
9020   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9021     SDValue Val = OutVals[i];
9022     CCValAssign &VA = RVLocs[i];
9023     assert(VA.isRegLoc() && "Can only return in registers!");
9024 
9025     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9026       // Handle returning f64 on RV32D with a soft float ABI.
9027       assert(VA.isRegLoc() && "Expected return via registers");
9028       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9029                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9030       SDValue Lo = SplitF64.getValue(0);
9031       SDValue Hi = SplitF64.getValue(1);
9032       Register RegLo = VA.getLocReg();
9033       assert(RegLo < RISCV::X31 && "Invalid register pair");
9034       Register RegHi = RegLo + 1;
9035 
9036       if (STI.isRegisterReservedByUser(RegLo) ||
9037           STI.isRegisterReservedByUser(RegHi))
9038         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9039             MF.getFunction(),
9040             "Return value register required, but has been reserved."});
9041 
9042       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9043       Glue = Chain.getValue(1);
9044       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9045       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9046       Glue = Chain.getValue(1);
9047       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9048     } else {
9049       // Handle a 'normal' return.
9050       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9051       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9052 
9053       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9054         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9055             MF.getFunction(),
9056             "Return value register required, but has been reserved."});
9057 
9058       // Guarantee that all emitted copies are stuck together.
9059       Glue = Chain.getValue(1);
9060       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9061     }
9062   }
9063 
9064   RetOps[0] = Chain; // Update chain.
9065 
9066   // Add the glue node if we have it.
9067   if (Glue.getNode()) {
9068     RetOps.push_back(Glue);
9069   }
9070 
9071   unsigned RetOpc = RISCVISD::RET_FLAG;
9072   // Interrupt service routines use different return instructions.
9073   const Function &Func = DAG.getMachineFunction().getFunction();
9074   if (Func.hasFnAttribute("interrupt")) {
9075     if (!Func.getReturnType()->isVoidTy())
9076       report_fatal_error(
9077           "Functions with the interrupt attribute must have void return type!");
9078 
9079     MachineFunction &MF = DAG.getMachineFunction();
9080     StringRef Kind =
9081       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9082 
9083     if (Kind == "user")
9084       RetOpc = RISCVISD::URET_FLAG;
9085     else if (Kind == "supervisor")
9086       RetOpc = RISCVISD::SRET_FLAG;
9087     else
9088       RetOpc = RISCVISD::MRET_FLAG;
9089   }
9090 
9091   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9092 }
9093 
9094 void RISCVTargetLowering::validateCCReservedRegs(
9095     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9096     MachineFunction &MF) const {
9097   const Function &F = MF.getFunction();
9098   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9099 
9100   if (llvm::any_of(Regs, [&STI](auto Reg) {
9101         return STI.isRegisterReservedByUser(Reg.first);
9102       }))
9103     F.getContext().diagnose(DiagnosticInfoUnsupported{
9104         F, "Argument register required, but has been reserved."});
9105 }
9106 
9107 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9108   return CI->isTailCall();
9109 }
9110 
9111 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9112 #define NODE_NAME_CASE(NODE)                                                   \
9113   case RISCVISD::NODE:                                                         \
9114     return "RISCVISD::" #NODE;
9115   // clang-format off
9116   switch ((RISCVISD::NodeType)Opcode) {
9117   case RISCVISD::FIRST_NUMBER:
9118     break;
9119   NODE_NAME_CASE(RET_FLAG)
9120   NODE_NAME_CASE(URET_FLAG)
9121   NODE_NAME_CASE(SRET_FLAG)
9122   NODE_NAME_CASE(MRET_FLAG)
9123   NODE_NAME_CASE(CALL)
9124   NODE_NAME_CASE(SELECT_CC)
9125   NODE_NAME_CASE(BR_CC)
9126   NODE_NAME_CASE(BuildPairF64)
9127   NODE_NAME_CASE(SplitF64)
9128   NODE_NAME_CASE(TAIL)
9129   NODE_NAME_CASE(MULHSU)
9130   NODE_NAME_CASE(SLLW)
9131   NODE_NAME_CASE(SRAW)
9132   NODE_NAME_CASE(SRLW)
9133   NODE_NAME_CASE(DIVW)
9134   NODE_NAME_CASE(DIVUW)
9135   NODE_NAME_CASE(REMUW)
9136   NODE_NAME_CASE(ROLW)
9137   NODE_NAME_CASE(RORW)
9138   NODE_NAME_CASE(CLZW)
9139   NODE_NAME_CASE(CTZW)
9140   NODE_NAME_CASE(FSLW)
9141   NODE_NAME_CASE(FSRW)
9142   NODE_NAME_CASE(FSL)
9143   NODE_NAME_CASE(FSR)
9144   NODE_NAME_CASE(FMV_H_X)
9145   NODE_NAME_CASE(FMV_X_ANYEXTH)
9146   NODE_NAME_CASE(FMV_W_X_RV64)
9147   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9148   NODE_NAME_CASE(FCVT_X_RTZ)
9149   NODE_NAME_CASE(FCVT_XU_RTZ)
9150   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
9151   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
9152   NODE_NAME_CASE(READ_CYCLE_WIDE)
9153   NODE_NAME_CASE(GREV)
9154   NODE_NAME_CASE(GREVW)
9155   NODE_NAME_CASE(GORC)
9156   NODE_NAME_CASE(GORCW)
9157   NODE_NAME_CASE(SHFL)
9158   NODE_NAME_CASE(SHFLW)
9159   NODE_NAME_CASE(UNSHFL)
9160   NODE_NAME_CASE(UNSHFLW)
9161   NODE_NAME_CASE(BCOMPRESS)
9162   NODE_NAME_CASE(BCOMPRESSW)
9163   NODE_NAME_CASE(BDECOMPRESS)
9164   NODE_NAME_CASE(BDECOMPRESSW)
9165   NODE_NAME_CASE(VMV_V_X_VL)
9166   NODE_NAME_CASE(VFMV_V_F_VL)
9167   NODE_NAME_CASE(VMV_X_S)
9168   NODE_NAME_CASE(VMV_S_X_VL)
9169   NODE_NAME_CASE(VFMV_S_F_VL)
9170   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9171   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9172   NODE_NAME_CASE(READ_VLENB)
9173   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9174   NODE_NAME_CASE(VSLIDEUP_VL)
9175   NODE_NAME_CASE(VSLIDE1UP_VL)
9176   NODE_NAME_CASE(VSLIDEDOWN_VL)
9177   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9178   NODE_NAME_CASE(VID_VL)
9179   NODE_NAME_CASE(VFNCVT_ROD_VL)
9180   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9181   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9182   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9183   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9184   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9185   NODE_NAME_CASE(VECREDUCE_AND_VL)
9186   NODE_NAME_CASE(VECREDUCE_OR_VL)
9187   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9188   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9189   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9190   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9191   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9192   NODE_NAME_CASE(ADD_VL)
9193   NODE_NAME_CASE(AND_VL)
9194   NODE_NAME_CASE(MUL_VL)
9195   NODE_NAME_CASE(OR_VL)
9196   NODE_NAME_CASE(SDIV_VL)
9197   NODE_NAME_CASE(SHL_VL)
9198   NODE_NAME_CASE(SREM_VL)
9199   NODE_NAME_CASE(SRA_VL)
9200   NODE_NAME_CASE(SRL_VL)
9201   NODE_NAME_CASE(SUB_VL)
9202   NODE_NAME_CASE(UDIV_VL)
9203   NODE_NAME_CASE(UREM_VL)
9204   NODE_NAME_CASE(XOR_VL)
9205   NODE_NAME_CASE(SADDSAT_VL)
9206   NODE_NAME_CASE(UADDSAT_VL)
9207   NODE_NAME_CASE(SSUBSAT_VL)
9208   NODE_NAME_CASE(USUBSAT_VL)
9209   NODE_NAME_CASE(FADD_VL)
9210   NODE_NAME_CASE(FSUB_VL)
9211   NODE_NAME_CASE(FMUL_VL)
9212   NODE_NAME_CASE(FDIV_VL)
9213   NODE_NAME_CASE(FNEG_VL)
9214   NODE_NAME_CASE(FABS_VL)
9215   NODE_NAME_CASE(FSQRT_VL)
9216   NODE_NAME_CASE(FMA_VL)
9217   NODE_NAME_CASE(FCOPYSIGN_VL)
9218   NODE_NAME_CASE(SMIN_VL)
9219   NODE_NAME_CASE(SMAX_VL)
9220   NODE_NAME_CASE(UMIN_VL)
9221   NODE_NAME_CASE(UMAX_VL)
9222   NODE_NAME_CASE(FMINNUM_VL)
9223   NODE_NAME_CASE(FMAXNUM_VL)
9224   NODE_NAME_CASE(MULHS_VL)
9225   NODE_NAME_CASE(MULHU_VL)
9226   NODE_NAME_CASE(FP_TO_SINT_VL)
9227   NODE_NAME_CASE(FP_TO_UINT_VL)
9228   NODE_NAME_CASE(SINT_TO_FP_VL)
9229   NODE_NAME_CASE(UINT_TO_FP_VL)
9230   NODE_NAME_CASE(FP_EXTEND_VL)
9231   NODE_NAME_CASE(FP_ROUND_VL)
9232   NODE_NAME_CASE(VWMUL_VL)
9233   NODE_NAME_CASE(VWMULU_VL)
9234   NODE_NAME_CASE(SETCC_VL)
9235   NODE_NAME_CASE(VSELECT_VL)
9236   NODE_NAME_CASE(VMAND_VL)
9237   NODE_NAME_CASE(VMOR_VL)
9238   NODE_NAME_CASE(VMXOR_VL)
9239   NODE_NAME_CASE(VMCLR_VL)
9240   NODE_NAME_CASE(VMSET_VL)
9241   NODE_NAME_CASE(VRGATHER_VX_VL)
9242   NODE_NAME_CASE(VRGATHER_VV_VL)
9243   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9244   NODE_NAME_CASE(VSEXT_VL)
9245   NODE_NAME_CASE(VZEXT_VL)
9246   NODE_NAME_CASE(VPOPC_VL)
9247   NODE_NAME_CASE(VLE_VL)
9248   NODE_NAME_CASE(VSE_VL)
9249   NODE_NAME_CASE(READ_CSR)
9250   NODE_NAME_CASE(WRITE_CSR)
9251   NODE_NAME_CASE(SWAP_CSR)
9252   }
9253   // clang-format on
9254   return nullptr;
9255 #undef NODE_NAME_CASE
9256 }
9257 
9258 /// getConstraintType - Given a constraint letter, return the type of
9259 /// constraint it is for this target.
9260 RISCVTargetLowering::ConstraintType
9261 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9262   if (Constraint.size() == 1) {
9263     switch (Constraint[0]) {
9264     default:
9265       break;
9266     case 'f':
9267       return C_RegisterClass;
9268     case 'I':
9269     case 'J':
9270     case 'K':
9271       return C_Immediate;
9272     case 'A':
9273       return C_Memory;
9274     case 'S': // A symbolic address
9275       return C_Other;
9276     }
9277   } else {
9278     if (Constraint == "vr" || Constraint == "vm")
9279       return C_RegisterClass;
9280   }
9281   return TargetLowering::getConstraintType(Constraint);
9282 }
9283 
9284 std::pair<unsigned, const TargetRegisterClass *>
9285 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9286                                                   StringRef Constraint,
9287                                                   MVT VT) const {
9288   // First, see if this is a constraint that directly corresponds to a
9289   // RISCV register class.
9290   if (Constraint.size() == 1) {
9291     switch (Constraint[0]) {
9292     case 'r':
9293       return std::make_pair(0U, &RISCV::GPRRegClass);
9294     case 'f':
9295       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9296         return std::make_pair(0U, &RISCV::FPR16RegClass);
9297       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9298         return std::make_pair(0U, &RISCV::FPR32RegClass);
9299       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9300         return std::make_pair(0U, &RISCV::FPR64RegClass);
9301       break;
9302     default:
9303       break;
9304     }
9305   } else {
9306     if (Constraint == "vr") {
9307       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9308                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9309         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9310           return std::make_pair(0U, RC);
9311       }
9312     } else if (Constraint == "vm") {
9313       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9314         return std::make_pair(0U, &RISCV::VMRegClass);
9315     }
9316   }
9317 
9318   // Clang will correctly decode the usage of register name aliases into their
9319   // official names. However, other frontends like `rustc` do not. This allows
9320   // users of these frontends to use the ABI names for registers in LLVM-style
9321   // register constraints.
9322   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9323                                .Case("{zero}", RISCV::X0)
9324                                .Case("{ra}", RISCV::X1)
9325                                .Case("{sp}", RISCV::X2)
9326                                .Case("{gp}", RISCV::X3)
9327                                .Case("{tp}", RISCV::X4)
9328                                .Case("{t0}", RISCV::X5)
9329                                .Case("{t1}", RISCV::X6)
9330                                .Case("{t2}", RISCV::X7)
9331                                .Cases("{s0}", "{fp}", RISCV::X8)
9332                                .Case("{s1}", RISCV::X9)
9333                                .Case("{a0}", RISCV::X10)
9334                                .Case("{a1}", RISCV::X11)
9335                                .Case("{a2}", RISCV::X12)
9336                                .Case("{a3}", RISCV::X13)
9337                                .Case("{a4}", RISCV::X14)
9338                                .Case("{a5}", RISCV::X15)
9339                                .Case("{a6}", RISCV::X16)
9340                                .Case("{a7}", RISCV::X17)
9341                                .Case("{s2}", RISCV::X18)
9342                                .Case("{s3}", RISCV::X19)
9343                                .Case("{s4}", RISCV::X20)
9344                                .Case("{s5}", RISCV::X21)
9345                                .Case("{s6}", RISCV::X22)
9346                                .Case("{s7}", RISCV::X23)
9347                                .Case("{s8}", RISCV::X24)
9348                                .Case("{s9}", RISCV::X25)
9349                                .Case("{s10}", RISCV::X26)
9350                                .Case("{s11}", RISCV::X27)
9351                                .Case("{t3}", RISCV::X28)
9352                                .Case("{t4}", RISCV::X29)
9353                                .Case("{t5}", RISCV::X30)
9354                                .Case("{t6}", RISCV::X31)
9355                                .Default(RISCV::NoRegister);
9356   if (XRegFromAlias != RISCV::NoRegister)
9357     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9358 
9359   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9360   // TableGen record rather than the AsmName to choose registers for InlineAsm
9361   // constraints, plus we want to match those names to the widest floating point
9362   // register type available, manually select floating point registers here.
9363   //
9364   // The second case is the ABI name of the register, so that frontends can also
9365   // use the ABI names in register constraint lists.
9366   if (Subtarget.hasStdExtF()) {
9367     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9368                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9369                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9370                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9371                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9372                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9373                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9374                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9375                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9376                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9377                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9378                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9379                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9380                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9381                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9382                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9383                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9384                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9385                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9386                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9387                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
9388                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
9389                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
9390                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
9391                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
9392                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
9393                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
9394                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
9395                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
9396                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
9397                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
9398                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
9399                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
9400                         .Default(RISCV::NoRegister);
9401     if (FReg != RISCV::NoRegister) {
9402       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
9403       if (Subtarget.hasStdExtD()) {
9404         unsigned RegNo = FReg - RISCV::F0_F;
9405         unsigned DReg = RISCV::F0_D + RegNo;
9406         return std::make_pair(DReg, &RISCV::FPR64RegClass);
9407       }
9408       return std::make_pair(FReg, &RISCV::FPR32RegClass);
9409     }
9410   }
9411 
9412   if (Subtarget.hasStdExtV()) {
9413     Register VReg = StringSwitch<Register>(Constraint.lower())
9414                         .Case("{v0}", RISCV::V0)
9415                         .Case("{v1}", RISCV::V1)
9416                         .Case("{v2}", RISCV::V2)
9417                         .Case("{v3}", RISCV::V3)
9418                         .Case("{v4}", RISCV::V4)
9419                         .Case("{v5}", RISCV::V5)
9420                         .Case("{v6}", RISCV::V6)
9421                         .Case("{v7}", RISCV::V7)
9422                         .Case("{v8}", RISCV::V8)
9423                         .Case("{v9}", RISCV::V9)
9424                         .Case("{v10}", RISCV::V10)
9425                         .Case("{v11}", RISCV::V11)
9426                         .Case("{v12}", RISCV::V12)
9427                         .Case("{v13}", RISCV::V13)
9428                         .Case("{v14}", RISCV::V14)
9429                         .Case("{v15}", RISCV::V15)
9430                         .Case("{v16}", RISCV::V16)
9431                         .Case("{v17}", RISCV::V17)
9432                         .Case("{v18}", RISCV::V18)
9433                         .Case("{v19}", RISCV::V19)
9434                         .Case("{v20}", RISCV::V20)
9435                         .Case("{v21}", RISCV::V21)
9436                         .Case("{v22}", RISCV::V22)
9437                         .Case("{v23}", RISCV::V23)
9438                         .Case("{v24}", RISCV::V24)
9439                         .Case("{v25}", RISCV::V25)
9440                         .Case("{v26}", RISCV::V26)
9441                         .Case("{v27}", RISCV::V27)
9442                         .Case("{v28}", RISCV::V28)
9443                         .Case("{v29}", RISCV::V29)
9444                         .Case("{v30}", RISCV::V30)
9445                         .Case("{v31}", RISCV::V31)
9446                         .Default(RISCV::NoRegister);
9447     if (VReg != RISCV::NoRegister) {
9448       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
9449         return std::make_pair(VReg, &RISCV::VMRegClass);
9450       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
9451         return std::make_pair(VReg, &RISCV::VRRegClass);
9452       for (const auto *RC :
9453            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9454         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
9455           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
9456           return std::make_pair(VReg, RC);
9457         }
9458       }
9459     }
9460   }
9461 
9462   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9463 }
9464 
9465 unsigned
9466 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
9467   // Currently only support length 1 constraints.
9468   if (ConstraintCode.size() == 1) {
9469     switch (ConstraintCode[0]) {
9470     case 'A':
9471       return InlineAsm::Constraint_A;
9472     default:
9473       break;
9474     }
9475   }
9476 
9477   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
9478 }
9479 
9480 void RISCVTargetLowering::LowerAsmOperandForConstraint(
9481     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
9482     SelectionDAG &DAG) const {
9483   // Currently only support length 1 constraints.
9484   if (Constraint.length() == 1) {
9485     switch (Constraint[0]) {
9486     case 'I':
9487       // Validate & create a 12-bit signed immediate operand.
9488       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9489         uint64_t CVal = C->getSExtValue();
9490         if (isInt<12>(CVal))
9491           Ops.push_back(
9492               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9493       }
9494       return;
9495     case 'J':
9496       // Validate & create an integer zero operand.
9497       if (auto *C = dyn_cast<ConstantSDNode>(Op))
9498         if (C->getZExtValue() == 0)
9499           Ops.push_back(
9500               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
9501       return;
9502     case 'K':
9503       // Validate & create a 5-bit unsigned immediate operand.
9504       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
9505         uint64_t CVal = C->getZExtValue();
9506         if (isUInt<5>(CVal))
9507           Ops.push_back(
9508               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
9509       }
9510       return;
9511     case 'S':
9512       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9513         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
9514                                                  GA->getValueType(0)));
9515       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9516         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9517                                                 BA->getValueType(0)));
9518       }
9519       return;
9520     default:
9521       break;
9522     }
9523   }
9524   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9525 }
9526 
9527 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9528                                                    Instruction *Inst,
9529                                                    AtomicOrdering Ord) const {
9530   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9531     return Builder.CreateFence(Ord);
9532   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9533     return Builder.CreateFence(AtomicOrdering::Release);
9534   return nullptr;
9535 }
9536 
9537 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9538                                                     Instruction *Inst,
9539                                                     AtomicOrdering Ord) const {
9540   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9541     return Builder.CreateFence(AtomicOrdering::Acquire);
9542   return nullptr;
9543 }
9544 
9545 TargetLowering::AtomicExpansionKind
9546 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9547   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9548   // point operations can't be used in an lr/sc sequence without breaking the
9549   // forward-progress guarantee.
9550   if (AI->isFloatingPointOperation())
9551     return AtomicExpansionKind::CmpXChg;
9552 
9553   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9554   if (Size == 8 || Size == 16)
9555     return AtomicExpansionKind::MaskedIntrinsic;
9556   return AtomicExpansionKind::None;
9557 }
9558 
9559 static Intrinsic::ID
9560 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9561   if (XLen == 32) {
9562     switch (BinOp) {
9563     default:
9564       llvm_unreachable("Unexpected AtomicRMW BinOp");
9565     case AtomicRMWInst::Xchg:
9566       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9567     case AtomicRMWInst::Add:
9568       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9569     case AtomicRMWInst::Sub:
9570       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9571     case AtomicRMWInst::Nand:
9572       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9573     case AtomicRMWInst::Max:
9574       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9575     case AtomicRMWInst::Min:
9576       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9577     case AtomicRMWInst::UMax:
9578       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9579     case AtomicRMWInst::UMin:
9580       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9581     }
9582   }
9583 
9584   if (XLen == 64) {
9585     switch (BinOp) {
9586     default:
9587       llvm_unreachable("Unexpected AtomicRMW BinOp");
9588     case AtomicRMWInst::Xchg:
9589       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9590     case AtomicRMWInst::Add:
9591       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9592     case AtomicRMWInst::Sub:
9593       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9594     case AtomicRMWInst::Nand:
9595       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9596     case AtomicRMWInst::Max:
9597       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9598     case AtomicRMWInst::Min:
9599       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9600     case AtomicRMWInst::UMax:
9601       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9602     case AtomicRMWInst::UMin:
9603       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9604     }
9605   }
9606 
9607   llvm_unreachable("Unexpected XLen\n");
9608 }
9609 
9610 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9611     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9612     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9613   unsigned XLen = Subtarget.getXLen();
9614   Value *Ordering =
9615       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9616   Type *Tys[] = {AlignedAddr->getType()};
9617   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9618       AI->getModule(),
9619       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9620 
9621   if (XLen == 64) {
9622     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9623     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9624     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9625   }
9626 
9627   Value *Result;
9628 
9629   // Must pass the shift amount needed to sign extend the loaded value prior
9630   // to performing a signed comparison for min/max. ShiftAmt is the number of
9631   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9632   // is the number of bits to left+right shift the value in order to
9633   // sign-extend.
9634   if (AI->getOperation() == AtomicRMWInst::Min ||
9635       AI->getOperation() == AtomicRMWInst::Max) {
9636     const DataLayout &DL = AI->getModule()->getDataLayout();
9637     unsigned ValWidth =
9638         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9639     Value *SextShamt =
9640         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9641     Result = Builder.CreateCall(LrwOpScwLoop,
9642                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9643   } else {
9644     Result =
9645         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9646   }
9647 
9648   if (XLen == 64)
9649     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9650   return Result;
9651 }
9652 
9653 TargetLowering::AtomicExpansionKind
9654 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9655     AtomicCmpXchgInst *CI) const {
9656   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9657   if (Size == 8 || Size == 16)
9658     return AtomicExpansionKind::MaskedIntrinsic;
9659   return AtomicExpansionKind::None;
9660 }
9661 
9662 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9663     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9664     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9665   unsigned XLen = Subtarget.getXLen();
9666   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9667   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9668   if (XLen == 64) {
9669     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9670     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9671     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9672     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9673   }
9674   Type *Tys[] = {AlignedAddr->getType()};
9675   Function *MaskedCmpXchg =
9676       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9677   Value *Result = Builder.CreateCall(
9678       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9679   if (XLen == 64)
9680     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9681   return Result;
9682 }
9683 
9684 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9685   return false;
9686 }
9687 
9688 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9689                                                      EVT VT) const {
9690   VT = VT.getScalarType();
9691 
9692   if (!VT.isSimple())
9693     return false;
9694 
9695   switch (VT.getSimpleVT().SimpleTy) {
9696   case MVT::f16:
9697     return Subtarget.hasStdExtZfh();
9698   case MVT::f32:
9699     return Subtarget.hasStdExtF();
9700   case MVT::f64:
9701     return Subtarget.hasStdExtD();
9702   default:
9703     break;
9704   }
9705 
9706   return false;
9707 }
9708 
9709 Register RISCVTargetLowering::getExceptionPointerRegister(
9710     const Constant *PersonalityFn) const {
9711   return RISCV::X10;
9712 }
9713 
9714 Register RISCVTargetLowering::getExceptionSelectorRegister(
9715     const Constant *PersonalityFn) const {
9716   return RISCV::X11;
9717 }
9718 
9719 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9720   // Return false to suppress the unnecessary extensions if the LibCall
9721   // arguments or return value is f32 type for LP64 ABI.
9722   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9723   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9724     return false;
9725 
9726   return true;
9727 }
9728 
9729 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9730   if (Subtarget.is64Bit() && Type == MVT::i32)
9731     return true;
9732 
9733   return IsSigned;
9734 }
9735 
9736 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9737                                                  SDValue C) const {
9738   // Check integral scalar types.
9739   if (VT.isScalarInteger()) {
9740     // Omit the optimization if the sub target has the M extension and the data
9741     // size exceeds XLen.
9742     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9743       return false;
9744     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9745       // Break the MUL to a SLLI and an ADD/SUB.
9746       const APInt &Imm = ConstNode->getAPIntValue();
9747       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9748           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9749         return true;
9750       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9751       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9752           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9753            (Imm - 8).isPowerOf2()))
9754         return true;
9755       // Omit the following optimization if the sub target has the M extension
9756       // and the data size >= XLen.
9757       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9758         return false;
9759       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9760       // a pair of LUI/ADDI.
9761       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9762         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9763         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9764             (1 - ImmS).isPowerOf2())
9765         return true;
9766       }
9767     }
9768   }
9769 
9770   return false;
9771 }
9772 
9773 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9774     const SDValue &AddNode, const SDValue &ConstNode) const {
9775   // Let the DAGCombiner decide for vectors.
9776   EVT VT = AddNode.getValueType();
9777   if (VT.isVector())
9778     return true;
9779 
9780   // Let the DAGCombiner decide for larger types.
9781   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9782     return true;
9783 
9784   // It is worse if c1 is simm12 while c1*c2 is not.
9785   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9786   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9787   const APInt &C1 = C1Node->getAPIntValue();
9788   const APInt &C2 = C2Node->getAPIntValue();
9789   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9790     return false;
9791 
9792   // Default to true and let the DAGCombiner decide.
9793   return true;
9794 }
9795 
9796 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9797     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9798     bool *Fast) const {
9799   if (!VT.isVector())
9800     return false;
9801 
9802   EVT ElemVT = VT.getVectorElementType();
9803   if (Alignment >= ElemVT.getStoreSize()) {
9804     if (Fast)
9805       *Fast = true;
9806     return true;
9807   }
9808 
9809   return false;
9810 }
9811 
9812 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9813     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9814     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9815   bool IsABIRegCopy = CC.hasValue();
9816   EVT ValueVT = Val.getValueType();
9817   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9818     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9819     // and cast to f32.
9820     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9821     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9822     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9823                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9824     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9825     Parts[0] = Val;
9826     return true;
9827   }
9828 
9829   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9830     LLVMContext &Context = *DAG.getContext();
9831     EVT ValueEltVT = ValueVT.getVectorElementType();
9832     EVT PartEltVT = PartVT.getVectorElementType();
9833     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9834     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9835     if (PartVTBitSize % ValueVTBitSize == 0) {
9836       // If the element types are different, bitcast to the same element type of
9837       // PartVT first.
9838       if (ValueEltVT != PartEltVT) {
9839         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9840         assert(Count != 0 && "The number of element should not be zero.");
9841         EVT SameEltTypeVT =
9842             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9843         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9844       }
9845       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9846                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9847       Parts[0] = Val;
9848       return true;
9849     }
9850   }
9851   return false;
9852 }
9853 
9854 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9855     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9856     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9857   bool IsABIRegCopy = CC.hasValue();
9858   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9859     SDValue Val = Parts[0];
9860 
9861     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9862     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9863     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9864     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9865     return Val;
9866   }
9867 
9868   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9869     LLVMContext &Context = *DAG.getContext();
9870     SDValue Val = Parts[0];
9871     EVT ValueEltVT = ValueVT.getVectorElementType();
9872     EVT PartEltVT = PartVT.getVectorElementType();
9873     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9874     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9875     if (PartVTBitSize % ValueVTBitSize == 0) {
9876       EVT SameEltTypeVT = ValueVT;
9877       // If the element types are different, convert it to the same element type
9878       // of PartVT.
9879       if (ValueEltVT != PartEltVT) {
9880         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9881         assert(Count != 0 && "The number of element should not be zero.");
9882         SameEltTypeVT =
9883             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9884       }
9885       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9886                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9887       if (ValueEltVT != PartEltVT)
9888         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9889       return Val;
9890     }
9891   }
9892   return SDValue();
9893 }
9894 
9895 #define GET_REGISTER_MATCHER
9896 #include "RISCVGenAsmMatcher.inc"
9897 
9898 Register
9899 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9900                                        const MachineFunction &MF) const {
9901   Register Reg = MatchRegisterAltName(RegName);
9902   if (Reg == RISCV::NoRegister)
9903     Reg = MatchRegisterName(RegName);
9904   if (Reg == RISCV::NoRegister)
9905     report_fatal_error(
9906         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9907   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9908   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9909     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9910                              StringRef(RegName) + "\"."));
9911   return Reg;
9912 }
9913 
9914 namespace llvm {
9915 namespace RISCVVIntrinsicsTable {
9916 
9917 #define GET_RISCVVIntrinsicsTable_IMPL
9918 #include "RISCVGenSearchableTables.inc"
9919 
9920 } // namespace RISCVVIntrinsicsTable
9921 
9922 } // namespace llvm
9923