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/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/IntrinsicsRISCV.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/KnownBits.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "riscv-lower"
43 
44 STATISTIC(NumTailCalls, "Number of tail calls");
45 
46 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
47                                          const RISCVSubtarget &STI)
48     : TargetLowering(TM), Subtarget(STI) {
49 
50   if (Subtarget.isRV32E())
51     report_fatal_error("Codegen not yet implemented for RV32E");
52 
53   RISCVABI::ABI ABI = Subtarget.getTargetABI();
54   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
55 
56   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
57       !Subtarget.hasStdExtF()) {
58     errs() << "Hard-float 'f' ABI can't be used for a target that "
59                 "doesn't support the F instruction set extension (ignoring "
60                           "target-abi)\n";
61     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
62   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
63              !Subtarget.hasStdExtD()) {
64     errs() << "Hard-float 'd' ABI can't be used for a target that "
65               "doesn't support the D instruction set extension (ignoring "
66               "target-abi)\n";
67     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
68   }
69 
70   switch (ABI) {
71   default:
72     report_fatal_error("Don't know how to lower this ABI");
73   case RISCVABI::ABI_ILP32:
74   case RISCVABI::ABI_ILP32F:
75   case RISCVABI::ABI_ILP32D:
76   case RISCVABI::ABI_LP64:
77   case RISCVABI::ABI_LP64F:
78   case RISCVABI::ABI_LP64D:
79     break;
80   }
81 
82   MVT XLenVT = Subtarget.getXLenVT();
83 
84   // Set up the register classes.
85   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
86 
87   if (Subtarget.hasStdExtZfh())
88     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
89   if (Subtarget.hasStdExtF())
90     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
91   if (Subtarget.hasStdExtD())
92     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
93 
94   static const MVT::SimpleValueType BoolVecVTs[] = {
95       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
96       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
97   static const MVT::SimpleValueType IntVecVTs[] = {
98       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
99       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
100       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
101       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
102       MVT::nxv4i64, MVT::nxv8i64};
103   static const MVT::SimpleValueType F16VecVTs[] = {
104       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
105       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
106   static const MVT::SimpleValueType F32VecVTs[] = {
107       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
108   static const MVT::SimpleValueType F64VecVTs[] = {
109       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
110 
111   if (Subtarget.hasStdExtV()) {
112     auto addRegClassForRVV = [this](MVT VT) {
113       unsigned Size = VT.getSizeInBits().getKnownMinValue();
114       assert(Size <= 512 && isPowerOf2_32(Size));
115       const TargetRegisterClass *RC;
116       if (Size <= 64)
117         RC = &RISCV::VRRegClass;
118       else if (Size == 128)
119         RC = &RISCV::VRM2RegClass;
120       else if (Size == 256)
121         RC = &RISCV::VRM4RegClass;
122       else
123         RC = &RISCV::VRM8RegClass;
124 
125       addRegisterClass(VT, RC);
126     };
127 
128     for (MVT VT : BoolVecVTs)
129       addRegClassForRVV(VT);
130     for (MVT VT : IntVecVTs)
131       addRegClassForRVV(VT);
132 
133     if (Subtarget.hasStdExtZfh())
134       for (MVT VT : F16VecVTs)
135         addRegClassForRVV(VT);
136 
137     if (Subtarget.hasStdExtF())
138       for (MVT VT : F32VecVTs)
139         addRegClassForRVV(VT);
140 
141     if (Subtarget.hasStdExtD())
142       for (MVT VT : F64VecVTs)
143         addRegClassForRVV(VT);
144 
145     if (Subtarget.useRVVForFixedLengthVectors()) {
146       auto addRegClassForFixedVectors = [this](MVT VT) {
147         MVT ContainerVT = getContainerForFixedLengthVector(VT);
148         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
149         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
150         addRegisterClass(VT, TRI.getRegClass(RCID));
151       };
152       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
153         if (useRVVForFixedLengthVectorVT(VT))
154           addRegClassForFixedVectors(VT);
155 
156       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
157         if (useRVVForFixedLengthVectorVT(VT))
158           addRegClassForFixedVectors(VT);
159     }
160   }
161 
162   // Compute derived properties from the register classes.
163   computeRegisterProperties(STI.getRegisterInfo());
164 
165   setStackPointerRegisterToSaveRestore(RISCV::X2);
166 
167   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
168     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
169 
170   // TODO: add all necessary setOperationAction calls.
171   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
172 
173   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
174   setOperationAction(ISD::BR_CC, XLenVT, Expand);
175   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
176   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
177 
178   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
179   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
180 
181   setOperationAction(ISD::VASTART, MVT::Other, Custom);
182   setOperationAction(ISD::VAARG, MVT::Other, Expand);
183   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
184   setOperationAction(ISD::VAEND, MVT::Other, Expand);
185 
186   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
187   if (!Subtarget.hasStdExtZbb()) {
188     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
189     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
190   }
191 
192   if (Subtarget.is64Bit()) {
193     setOperationAction(ISD::ADD, MVT::i32, Custom);
194     setOperationAction(ISD::SUB, MVT::i32, Custom);
195     setOperationAction(ISD::SHL, MVT::i32, Custom);
196     setOperationAction(ISD::SRA, MVT::i32, Custom);
197     setOperationAction(ISD::SRL, MVT::i32, Custom);
198 
199     setOperationAction(ISD::UADDO, MVT::i32, Custom);
200     setOperationAction(ISD::USUBO, MVT::i32, Custom);
201     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
202     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
203   } else {
204     setLibcallName(RTLIB::SHL_I128, nullptr);
205     setLibcallName(RTLIB::SRL_I128, nullptr);
206     setLibcallName(RTLIB::SRA_I128, nullptr);
207     setLibcallName(RTLIB::MUL_I128, nullptr);
208     setLibcallName(RTLIB::MULO_I64, nullptr);
209   }
210 
211   if (!Subtarget.hasStdExtM()) {
212     setOperationAction(ISD::MUL, XLenVT, Expand);
213     setOperationAction(ISD::MULHS, XLenVT, Expand);
214     setOperationAction(ISD::MULHU, XLenVT, Expand);
215     setOperationAction(ISD::SDIV, XLenVT, Expand);
216     setOperationAction(ISD::UDIV, XLenVT, Expand);
217     setOperationAction(ISD::SREM, XLenVT, Expand);
218     setOperationAction(ISD::UREM, XLenVT, Expand);
219   } else {
220     if (Subtarget.is64Bit()) {
221       setOperationAction(ISD::MUL, MVT::i32, Custom);
222       setOperationAction(ISD::MUL, MVT::i128, Custom);
223 
224       setOperationAction(ISD::SDIV, MVT::i8, Custom);
225       setOperationAction(ISD::UDIV, MVT::i8, Custom);
226       setOperationAction(ISD::UREM, MVT::i8, Custom);
227       setOperationAction(ISD::SDIV, MVT::i16, Custom);
228       setOperationAction(ISD::UDIV, MVT::i16, Custom);
229       setOperationAction(ISD::UREM, MVT::i16, Custom);
230       setOperationAction(ISD::SDIV, MVT::i32, Custom);
231       setOperationAction(ISD::UDIV, MVT::i32, Custom);
232       setOperationAction(ISD::UREM, MVT::i32, Custom);
233     } else {
234       setOperationAction(ISD::MUL, MVT::i64, Custom);
235     }
236   }
237 
238   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
239   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
240   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
241   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
242 
243   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
244   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
245   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
246 
247   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
248     if (Subtarget.is64Bit()) {
249       setOperationAction(ISD::ROTL, MVT::i32, Custom);
250       setOperationAction(ISD::ROTR, MVT::i32, Custom);
251     }
252   } else {
253     setOperationAction(ISD::ROTL, XLenVT, Expand);
254     setOperationAction(ISD::ROTR, XLenVT, Expand);
255   }
256 
257   if (Subtarget.hasStdExtZbp()) {
258     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
259     // more combining.
260     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
261     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
262     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
263     // BSWAP i8 doesn't exist.
264     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
265     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
266 
267     if (Subtarget.is64Bit()) {
268       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
269       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
270     }
271   } else {
272     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
273     // pattern match it directly in isel.
274     setOperationAction(ISD::BSWAP, XLenVT,
275                        Subtarget.hasStdExtZbb() ? Legal : Expand);
276   }
277 
278   if (Subtarget.hasStdExtZbb()) {
279     setOperationAction(ISD::SMIN, XLenVT, Legal);
280     setOperationAction(ISD::SMAX, XLenVT, Legal);
281     setOperationAction(ISD::UMIN, XLenVT, Legal);
282     setOperationAction(ISD::UMAX, XLenVT, Legal);
283 
284     if (Subtarget.is64Bit()) {
285       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
286       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
287       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
288       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
289     }
290   } else {
291     setOperationAction(ISD::CTTZ, XLenVT, Expand);
292     setOperationAction(ISD::CTLZ, XLenVT, Expand);
293     setOperationAction(ISD::CTPOP, XLenVT, Expand);
294   }
295 
296   if (Subtarget.hasStdExtZbt()) {
297     setOperationAction(ISD::FSHL, XLenVT, Custom);
298     setOperationAction(ISD::FSHR, XLenVT, Custom);
299     setOperationAction(ISD::SELECT, XLenVT, Legal);
300 
301     if (Subtarget.is64Bit()) {
302       setOperationAction(ISD::FSHL, MVT::i32, Custom);
303       setOperationAction(ISD::FSHR, MVT::i32, Custom);
304     }
305   } else {
306     setOperationAction(ISD::SELECT, XLenVT, Custom);
307   }
308 
309   ISD::CondCode FPCCToExpand[] = {
310       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
311       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
312       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
313 
314   ISD::NodeType FPOpToExpand[] = {
315       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
316       ISD::FP_TO_FP16};
317 
318   if (Subtarget.hasStdExtZfh())
319     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
320 
321   if (Subtarget.hasStdExtZfh()) {
322     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
323     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
324     setOperationAction(ISD::LRINT, MVT::f16, Legal);
325     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
326     setOperationAction(ISD::LROUND, MVT::f16, Legal);
327     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
328     for (auto CC : FPCCToExpand)
329       setCondCodeAction(CC, MVT::f16, Expand);
330     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
331     setOperationAction(ISD::SELECT, MVT::f16, Custom);
332     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
333     for (auto Op : FPOpToExpand)
334       setOperationAction(Op, MVT::f16, Expand);
335   }
336 
337   if (Subtarget.hasStdExtF()) {
338     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
339     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
340     setOperationAction(ISD::LRINT, MVT::f32, Legal);
341     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
342     setOperationAction(ISD::LROUND, MVT::f32, Legal);
343     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
344     for (auto CC : FPCCToExpand)
345       setCondCodeAction(CC, MVT::f32, Expand);
346     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
347     setOperationAction(ISD::SELECT, MVT::f32, Custom);
348     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
349     for (auto Op : FPOpToExpand)
350       setOperationAction(Op, MVT::f32, Expand);
351     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
352     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
353   }
354 
355   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
356     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
357 
358   if (Subtarget.hasStdExtD()) {
359     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
360     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
361     setOperationAction(ISD::LRINT, MVT::f64, Legal);
362     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
363     setOperationAction(ISD::LROUND, MVT::f64, Legal);
364     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
365     for (auto CC : FPCCToExpand)
366       setCondCodeAction(CC, MVT::f64, Expand);
367     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
368     setOperationAction(ISD::SELECT, MVT::f64, Custom);
369     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
370     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
371     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
372     for (auto Op : FPOpToExpand)
373       setOperationAction(Op, MVT::f64, Expand);
374     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
375     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
376   }
377 
378   if (Subtarget.is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
381     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
382     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
383   }
384 
385   if (Subtarget.hasStdExtF()) {
386     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
387     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
388 
389     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
390     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
391   }
392 
393   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
394   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
395   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
396   setOperationAction(ISD::JumpTable, XLenVT, Custom);
397 
398   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
399 
400   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
401   // Unfortunately this can't be determined just from the ISA naming string.
402   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
403                      Subtarget.is64Bit() ? Legal : Custom);
404 
405   setOperationAction(ISD::TRAP, MVT::Other, Legal);
406   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408   if (Subtarget.is64Bit())
409     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
410 
411   if (Subtarget.hasStdExtA()) {
412     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
413     setMinCmpXchgSizeInBits(32);
414   } else {
415     setMaxAtomicSizeInBitsSupported(0);
416   }
417 
418   setBooleanContents(ZeroOrOneBooleanContent);
419 
420   if (Subtarget.hasStdExtV()) {
421     setBooleanVectorContents(ZeroOrOneBooleanContent);
422 
423     setOperationAction(ISD::VSCALE, XLenVT, Custom);
424 
425     // RVV intrinsics may have illegal operands.
426     // We also need to custom legalize vmv.x.s.
427     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
428     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
429     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
430     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
431     if (Subtarget.is64Bit()) {
432       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
433     } else {
434       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
435       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
436     }
437 
438     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
439 
440     static unsigned IntegerVPOps[] = {
441         ISD::VP_ADD,  ISD::VP_SUB,  ISD::VP_MUL, ISD::VP_SDIV, ISD::VP_UDIV,
442         ISD::VP_SREM, ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR,   ISD::VP_XOR,
443         ISD::VP_ASHR, ISD::VP_LSHR, ISD::VP_SHL};
444 
445     static unsigned FloatingPointVPOps[] = {ISD::VP_FADD, ISD::VP_FSUB,
446                                             ISD::VP_FMUL, ISD::VP_FDIV};
447 
448     if (!Subtarget.is64Bit()) {
449       // We must custom-lower certain vXi64 operations on RV32 due to the vector
450       // element type being illegal.
451       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
452       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
453 
454       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
455       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
456       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
457       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
458       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
459       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
460       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
461       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
462     }
463 
464     for (MVT VT : BoolVecVTs) {
465       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
466 
467       // Mask VTs are custom-expanded into a series of standard nodes
468       setOperationAction(ISD::TRUNCATE, VT, Custom);
469       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
470       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
471       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
472 
473       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
474       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
475 
476       setOperationAction(ISD::SELECT, VT, Custom);
477       setOperationAction(ISD::SELECT_CC, VT, Expand);
478       setOperationAction(ISD::VSELECT, VT, Expand);
479 
480       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
481       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
482       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
483 
484       // RVV has native int->float & float->int conversions where the
485       // element type sizes are within one power-of-two of each other. Any
486       // wider distances between type sizes have to be lowered as sequences
487       // which progressively narrow the gap in stages.
488       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
489       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
490       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
491       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
492 
493       // Expand all extending loads to types larger than this, and truncating
494       // stores from types larger than this.
495       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
496         setTruncStoreAction(OtherVT, VT, Expand);
497         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
498         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
499         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
500       }
501     }
502 
503     for (MVT VT : IntVecVTs) {
504       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
505       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
506 
507       setOperationAction(ISD::SMIN, VT, Legal);
508       setOperationAction(ISD::SMAX, VT, Legal);
509       setOperationAction(ISD::UMIN, VT, Legal);
510       setOperationAction(ISD::UMAX, VT, Legal);
511 
512       setOperationAction(ISD::ROTL, VT, Expand);
513       setOperationAction(ISD::ROTR, VT, Expand);
514 
515       // Custom-lower extensions and truncations from/to mask types.
516       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
517       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
518       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
519 
520       // RVV has native int->float & float->int conversions where the
521       // element type sizes are within one power-of-two of each other. Any
522       // wider distances between type sizes have to be lowered as sequences
523       // which progressively narrow the gap in stages.
524       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
525       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
526       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
527       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
528 
529       setOperationAction(ISD::SADDSAT, VT, Legal);
530       setOperationAction(ISD::UADDSAT, VT, Legal);
531       setOperationAction(ISD::SSUBSAT, VT, Legal);
532       setOperationAction(ISD::USUBSAT, VT, Legal);
533 
534       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
535       // nodes which truncate by one power of two at a time.
536       setOperationAction(ISD::TRUNCATE, VT, Custom);
537 
538       // Custom-lower insert/extract operations to simplify patterns.
539       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
540       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
541 
542       // Custom-lower reduction operations to set up the corresponding custom
543       // nodes' operands.
544       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
545       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
546       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
547       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
548       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
549       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
550       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
551       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
552 
553       for (unsigned VPOpc : IntegerVPOps)
554         setOperationAction(VPOpc, VT, Custom);
555 
556       setOperationAction(ISD::LOAD, VT, Custom);
557       setOperationAction(ISD::STORE, VT, Custom);
558 
559       setOperationAction(ISD::MLOAD, VT, Custom);
560       setOperationAction(ISD::MSTORE, VT, Custom);
561       setOperationAction(ISD::MGATHER, VT, Custom);
562       setOperationAction(ISD::MSCATTER, VT, Custom);
563 
564       setOperationAction(ISD::VP_LOAD, VT, Custom);
565       setOperationAction(ISD::VP_STORE, VT, Custom);
566       setOperationAction(ISD::VP_GATHER, VT, Custom);
567       setOperationAction(ISD::VP_SCATTER, VT, Custom);
568 
569       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
570       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
571       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
572 
573       setOperationAction(ISD::SELECT, VT, Custom);
574       setOperationAction(ISD::SELECT_CC, VT, Expand);
575 
576       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
577       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
578 
579       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
580         setTruncStoreAction(VT, OtherVT, Expand);
581         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
582         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
583         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
584       }
585     }
586 
587     // Expand various CCs to best match the RVV ISA, which natively supports UNE
588     // but no other unordered comparisons, and supports all ordered comparisons
589     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
590     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
591     // and we pattern-match those back to the "original", swapping operands once
592     // more. This way we catch both operations and both "vf" and "fv" forms with
593     // fewer patterns.
594     ISD::CondCode VFPCCToExpand[] = {
595         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
596         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
597         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
598     };
599 
600     // Sets common operation actions on RVV floating-point vector types.
601     const auto SetCommonVFPActions = [&](MVT VT) {
602       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
603       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
604       // sizes are within one power-of-two of each other. Therefore conversions
605       // between vXf16 and vXf64 must be lowered as sequences which convert via
606       // vXf32.
607       setOperationAction(ISD::FP_ROUND, VT, Custom);
608       setOperationAction(ISD::FP_EXTEND, VT, Custom);
609       // Custom-lower insert/extract operations to simplify patterns.
610       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
611       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
612       // Expand various condition codes (explained above).
613       for (auto CC : VFPCCToExpand)
614         setCondCodeAction(CC, VT, Expand);
615 
616       setOperationAction(ISD::FMINNUM, VT, Legal);
617       setOperationAction(ISD::FMAXNUM, VT, Legal);
618 
619       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
620       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
621       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
622       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
623       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
624 
625       setOperationAction(ISD::LOAD, VT, Custom);
626       setOperationAction(ISD::STORE, VT, Custom);
627 
628       setOperationAction(ISD::MLOAD, VT, Custom);
629       setOperationAction(ISD::MSTORE, VT, Custom);
630       setOperationAction(ISD::MGATHER, VT, Custom);
631       setOperationAction(ISD::MSCATTER, VT, Custom);
632 
633       setOperationAction(ISD::VP_LOAD, VT, Custom);
634       setOperationAction(ISD::VP_STORE, VT, Custom);
635       setOperationAction(ISD::VP_GATHER, VT, Custom);
636       setOperationAction(ISD::VP_SCATTER, VT, Custom);
637 
638       setOperationAction(ISD::SELECT, VT, Custom);
639       setOperationAction(ISD::SELECT_CC, VT, Expand);
640 
641       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
642       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
643       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
644 
645       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
646 
647       for (unsigned VPOpc : FloatingPointVPOps)
648         setOperationAction(VPOpc, VT, Custom);
649     };
650 
651     // Sets common extload/truncstore actions on RVV floating-point vector
652     // types.
653     const auto SetCommonVFPExtLoadTruncStoreActions =
654         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
655           for (auto SmallVT : SmallerVTs) {
656             setTruncStoreAction(VT, SmallVT, Expand);
657             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
658           }
659         };
660 
661     if (Subtarget.hasStdExtZfh())
662       for (MVT VT : F16VecVTs)
663         SetCommonVFPActions(VT);
664 
665     for (MVT VT : F32VecVTs) {
666       if (Subtarget.hasStdExtF())
667         SetCommonVFPActions(VT);
668       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
669     }
670 
671     for (MVT VT : F64VecVTs) {
672       if (Subtarget.hasStdExtD())
673         SetCommonVFPActions(VT);
674       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
675       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
676     }
677 
678     if (Subtarget.useRVVForFixedLengthVectors()) {
679       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
680         if (!useRVVForFixedLengthVectorVT(VT))
681           continue;
682 
683         // By default everything must be expanded.
684         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
685           setOperationAction(Op, VT, Expand);
686         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
687           setTruncStoreAction(VT, OtherVT, Expand);
688           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
689           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
690           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
691         }
692 
693         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
694         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
695         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
696 
697         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
698         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
699 
700         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
701         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
702 
703         setOperationAction(ISD::LOAD, VT, Custom);
704         setOperationAction(ISD::STORE, VT, Custom);
705 
706         setOperationAction(ISD::SETCC, VT, Custom);
707 
708         setOperationAction(ISD::SELECT, VT, Custom);
709 
710         setOperationAction(ISD::TRUNCATE, VT, Custom);
711 
712         setOperationAction(ISD::BITCAST, VT, Custom);
713 
714         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
715         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
716         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
717 
718         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
719         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
720         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
721         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
722 
723         // Operations below are different for between masks and other vectors.
724         if (VT.getVectorElementType() == MVT::i1) {
725           setOperationAction(ISD::AND, VT, Custom);
726           setOperationAction(ISD::OR, VT, Custom);
727           setOperationAction(ISD::XOR, VT, Custom);
728           continue;
729         }
730 
731         // Use SPLAT_VECTOR to prevent type legalization from destroying the
732         // splats when type legalizing i64 scalar on RV32.
733         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
734         // improvements first.
735         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
736           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
737           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
738         }
739 
740         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
741         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
742 
743         setOperationAction(ISD::MLOAD, VT, Custom);
744         setOperationAction(ISD::MSTORE, VT, Custom);
745         setOperationAction(ISD::MGATHER, VT, Custom);
746         setOperationAction(ISD::MSCATTER, VT, Custom);
747 
748         setOperationAction(ISD::VP_LOAD, VT, Custom);
749         setOperationAction(ISD::VP_STORE, VT, Custom);
750         setOperationAction(ISD::VP_GATHER, VT, Custom);
751         setOperationAction(ISD::VP_SCATTER, VT, Custom);
752 
753         setOperationAction(ISD::ADD, VT, Custom);
754         setOperationAction(ISD::MUL, VT, Custom);
755         setOperationAction(ISD::SUB, VT, Custom);
756         setOperationAction(ISD::AND, VT, Custom);
757         setOperationAction(ISD::OR, VT, Custom);
758         setOperationAction(ISD::XOR, VT, Custom);
759         setOperationAction(ISD::SDIV, VT, Custom);
760         setOperationAction(ISD::SREM, VT, Custom);
761         setOperationAction(ISD::UDIV, VT, Custom);
762         setOperationAction(ISD::UREM, VT, Custom);
763         setOperationAction(ISD::SHL, VT, Custom);
764         setOperationAction(ISD::SRA, VT, Custom);
765         setOperationAction(ISD::SRL, VT, Custom);
766 
767         setOperationAction(ISD::SMIN, VT, Custom);
768         setOperationAction(ISD::SMAX, VT, Custom);
769         setOperationAction(ISD::UMIN, VT, Custom);
770         setOperationAction(ISD::UMAX, VT, Custom);
771         setOperationAction(ISD::ABS,  VT, Custom);
772 
773         setOperationAction(ISD::MULHS, VT, Custom);
774         setOperationAction(ISD::MULHU, VT, Custom);
775 
776         setOperationAction(ISD::SADDSAT, VT, Custom);
777         setOperationAction(ISD::UADDSAT, VT, Custom);
778         setOperationAction(ISD::SSUBSAT, VT, Custom);
779         setOperationAction(ISD::USUBSAT, VT, Custom);
780 
781         setOperationAction(ISD::VSELECT, VT, Custom);
782         setOperationAction(ISD::SELECT_CC, VT, Expand);
783 
784         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
785         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
786         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
787 
788         // Custom-lower reduction operations to set up the corresponding custom
789         // nodes' operands.
790         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
791         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
792         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
793         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
794         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
795 
796         for (unsigned VPOpc : IntegerVPOps)
797           setOperationAction(VPOpc, VT, Custom);
798       }
799 
800       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
801         if (!useRVVForFixedLengthVectorVT(VT))
802           continue;
803 
804         // By default everything must be expanded.
805         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
806           setOperationAction(Op, VT, Expand);
807         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
808           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
809           setTruncStoreAction(VT, OtherVT, Expand);
810         }
811 
812         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
813         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
814         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
815 
816         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
817         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
818         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
819         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
820         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
821 
822         setOperationAction(ISD::LOAD, VT, Custom);
823         setOperationAction(ISD::STORE, VT, Custom);
824         setOperationAction(ISD::MLOAD, VT, Custom);
825         setOperationAction(ISD::MSTORE, VT, Custom);
826         setOperationAction(ISD::MGATHER, VT, Custom);
827         setOperationAction(ISD::MSCATTER, VT, Custom);
828 
829         setOperationAction(ISD::VP_LOAD, VT, Custom);
830         setOperationAction(ISD::VP_STORE, VT, Custom);
831         setOperationAction(ISD::VP_GATHER, VT, Custom);
832         setOperationAction(ISD::VP_SCATTER, VT, Custom);
833 
834         setOperationAction(ISD::FADD, VT, Custom);
835         setOperationAction(ISD::FSUB, VT, Custom);
836         setOperationAction(ISD::FMUL, VT, Custom);
837         setOperationAction(ISD::FDIV, VT, Custom);
838         setOperationAction(ISD::FNEG, VT, Custom);
839         setOperationAction(ISD::FABS, VT, Custom);
840         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
841         setOperationAction(ISD::FSQRT, VT, Custom);
842         setOperationAction(ISD::FMA, VT, Custom);
843         setOperationAction(ISD::FMINNUM, VT, Custom);
844         setOperationAction(ISD::FMAXNUM, VT, Custom);
845 
846         setOperationAction(ISD::FP_ROUND, VT, Custom);
847         setOperationAction(ISD::FP_EXTEND, VT, Custom);
848 
849         for (auto CC : VFPCCToExpand)
850           setCondCodeAction(CC, VT, Expand);
851 
852         setOperationAction(ISD::VSELECT, VT, Custom);
853         setOperationAction(ISD::SELECT, VT, Custom);
854         setOperationAction(ISD::SELECT_CC, VT, Expand);
855 
856         setOperationAction(ISD::BITCAST, VT, Custom);
857 
858         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
859         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
860         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
861         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
862 
863         for (unsigned VPOpc : FloatingPointVPOps)
864           setOperationAction(VPOpc, VT, Custom);
865       }
866 
867       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
868       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
869       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
870       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
871       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
872       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
873       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
874       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
875     }
876   }
877 
878   // Function alignments.
879   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
880   setMinFunctionAlignment(FunctionAlignment);
881   setPrefFunctionAlignment(FunctionAlignment);
882 
883   setMinimumJumpTableEntries(5);
884 
885   // Jumps are expensive, compared to logic
886   setJumpIsExpensive();
887 
888   // We can use any register for comparisons
889   setHasMultipleConditionRegisters();
890 
891   setTargetDAGCombine(ISD::ADD);
892   setTargetDAGCombine(ISD::SUB);
893   setTargetDAGCombine(ISD::AND);
894   setTargetDAGCombine(ISD::OR);
895   setTargetDAGCombine(ISD::XOR);
896   setTargetDAGCombine(ISD::ANY_EXTEND);
897   setTargetDAGCombine(ISD::ZERO_EXTEND);
898   if (Subtarget.hasStdExtV()) {
899     setTargetDAGCombine(ISD::FCOPYSIGN);
900     setTargetDAGCombine(ISD::MGATHER);
901     setTargetDAGCombine(ISD::MSCATTER);
902     setTargetDAGCombine(ISD::VP_GATHER);
903     setTargetDAGCombine(ISD::VP_SCATTER);
904     setTargetDAGCombine(ISD::SRA);
905     setTargetDAGCombine(ISD::SRL);
906     setTargetDAGCombine(ISD::SHL);
907   }
908 }
909 
910 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
911                                             LLVMContext &Context,
912                                             EVT VT) const {
913   if (!VT.isVector())
914     return getPointerTy(DL);
915   if (Subtarget.hasStdExtV() &&
916       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
917     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
918   return VT.changeVectorElementTypeToInteger();
919 }
920 
921 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
922   return Subtarget.getXLenVT();
923 }
924 
925 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
926                                              const CallInst &I,
927                                              MachineFunction &MF,
928                                              unsigned Intrinsic) const {
929   switch (Intrinsic) {
930   default:
931     return false;
932   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
933   case Intrinsic::riscv_masked_atomicrmw_add_i32:
934   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
935   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
936   case Intrinsic::riscv_masked_atomicrmw_max_i32:
937   case Intrinsic::riscv_masked_atomicrmw_min_i32:
938   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
939   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
940   case Intrinsic::riscv_masked_cmpxchg_i32: {
941     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
942     Info.opc = ISD::INTRINSIC_W_CHAIN;
943     Info.memVT = MVT::getVT(PtrTy->getElementType());
944     Info.ptrVal = I.getArgOperand(0);
945     Info.offset = 0;
946     Info.align = Align(4);
947     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
948                  MachineMemOperand::MOVolatile;
949     return true;
950   }
951   }
952 }
953 
954 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
955                                                 const AddrMode &AM, Type *Ty,
956                                                 unsigned AS,
957                                                 Instruction *I) const {
958   // No global is ever allowed as a base.
959   if (AM.BaseGV)
960     return false;
961 
962   // Require a 12-bit signed offset.
963   if (!isInt<12>(AM.BaseOffs))
964     return false;
965 
966   switch (AM.Scale) {
967   case 0: // "r+i" or just "i", depending on HasBaseReg.
968     break;
969   case 1:
970     if (!AM.HasBaseReg) // allow "r+i".
971       break;
972     return false; // disallow "r+r" or "r+r+i".
973   default:
974     return false;
975   }
976 
977   return true;
978 }
979 
980 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
981   return isInt<12>(Imm);
982 }
983 
984 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
985   return isInt<12>(Imm);
986 }
987 
988 // On RV32, 64-bit integers are split into their high and low parts and held
989 // in two different registers, so the trunc is free since the low register can
990 // just be used.
991 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
992   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
993     return false;
994   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
995   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
996   return (SrcBits == 64 && DestBits == 32);
997 }
998 
999 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1000   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1001       !SrcVT.isInteger() || !DstVT.isInteger())
1002     return false;
1003   unsigned SrcBits = SrcVT.getSizeInBits();
1004   unsigned DestBits = DstVT.getSizeInBits();
1005   return (SrcBits == 64 && DestBits == 32);
1006 }
1007 
1008 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1009   // Zexts are free if they can be combined with a load.
1010   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1011     EVT MemVT = LD->getMemoryVT();
1012     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
1013          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
1014         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1015          LD->getExtensionType() == ISD::ZEXTLOAD))
1016       return true;
1017   }
1018 
1019   return TargetLowering::isZExtFree(Val, VT2);
1020 }
1021 
1022 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1023   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1024 }
1025 
1026 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1027   return Subtarget.hasStdExtZbb();
1028 }
1029 
1030 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1031   return Subtarget.hasStdExtZbb();
1032 }
1033 
1034 /// Check if sinking \p I's operands to I's basic block is profitable, because
1035 /// the operands can be folded into a target instruction, e.g.
1036 /// splats of scalars can fold into vector instructions.
1037 bool RISCVTargetLowering::shouldSinkOperands(
1038     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1039   using namespace llvm::PatternMatch;
1040 
1041   if (!I->getType()->isVectorTy() || !Subtarget.hasStdExtV())
1042     return false;
1043 
1044   auto IsSinker = [&](Instruction *I, int Operand) {
1045     switch (I->getOpcode()) {
1046     case Instruction::Add:
1047     case Instruction::Sub:
1048     case Instruction::Mul:
1049       return true;
1050     case Instruction::Shl:
1051     case Instruction::LShr:
1052     case Instruction::AShr:
1053       return Operand == 1;
1054     default:
1055       return false;
1056     }
1057   };
1058 
1059   for (auto OpIdx : enumerate(I->operands())) {
1060     if (!IsSinker(I, OpIdx.index()))
1061       continue;
1062 
1063     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1064     // Make sure we are not already sinking this operand
1065     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1066       continue;
1067 
1068     // We are looking for a splat that can be sunk.
1069     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1070                              m_Undef(), m_ZeroMask())))
1071       continue;
1072 
1073     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1074     // and vector registers
1075     for (Use &U : Op->uses()) {
1076       Instruction *Insn = cast<Instruction>(U.getUser());
1077       if (!IsSinker(Insn, U.getOperandNo()))
1078         return false;
1079     }
1080 
1081     Ops.push_back(&Op->getOperandUse(0));
1082     Ops.push_back(&OpIdx.value());
1083   }
1084   return true;
1085 }
1086 
1087 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1088                                        bool ForCodeSize) const {
1089   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1090     return false;
1091   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1092     return false;
1093   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1094     return false;
1095   if (Imm.isNegZero())
1096     return false;
1097   return Imm.isZero();
1098 }
1099 
1100 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1101   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1102          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1103          (VT == MVT::f64 && Subtarget.hasStdExtD());
1104 }
1105 
1106 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1107                                                       CallingConv::ID CC,
1108                                                       EVT VT) const {
1109   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1110   // end up using a GPR but that will be decided based on ABI.
1111   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1112     return MVT::f32;
1113 
1114   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1115 }
1116 
1117 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1118                                                            CallingConv::ID CC,
1119                                                            EVT VT) const {
1120   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1121   // end up using a GPR but that will be decided based on ABI.
1122   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1123     return 1;
1124 
1125   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1126 }
1127 
1128 // Changes the condition code and swaps operands if necessary, so the SetCC
1129 // operation matches one of the comparisons supported directly by branches
1130 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1131 // with 1/-1.
1132 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1133                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1134   // Convert X > -1 to X >= 0.
1135   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1136     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1137     CC = ISD::SETGE;
1138     return;
1139   }
1140   // Convert X < 1 to 0 >= X.
1141   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1142     RHS = LHS;
1143     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1144     CC = ISD::SETGE;
1145     return;
1146   }
1147 
1148   switch (CC) {
1149   default:
1150     break;
1151   case ISD::SETGT:
1152   case ISD::SETLE:
1153   case ISD::SETUGT:
1154   case ISD::SETULE:
1155     CC = ISD::getSetCCSwappedOperands(CC);
1156     std::swap(LHS, RHS);
1157     break;
1158   }
1159 }
1160 
1161 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1162   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1163   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1164   if (VT.getVectorElementType() == MVT::i1)
1165     KnownSize *= 8;
1166 
1167   switch (KnownSize) {
1168   default:
1169     llvm_unreachable("Invalid LMUL.");
1170   case 8:
1171     return RISCVII::VLMUL::LMUL_F8;
1172   case 16:
1173     return RISCVII::VLMUL::LMUL_F4;
1174   case 32:
1175     return RISCVII::VLMUL::LMUL_F2;
1176   case 64:
1177     return RISCVII::VLMUL::LMUL_1;
1178   case 128:
1179     return RISCVII::VLMUL::LMUL_2;
1180   case 256:
1181     return RISCVII::VLMUL::LMUL_4;
1182   case 512:
1183     return RISCVII::VLMUL::LMUL_8;
1184   }
1185 }
1186 
1187 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1188   switch (LMul) {
1189   default:
1190     llvm_unreachable("Invalid LMUL.");
1191   case RISCVII::VLMUL::LMUL_F8:
1192   case RISCVII::VLMUL::LMUL_F4:
1193   case RISCVII::VLMUL::LMUL_F2:
1194   case RISCVII::VLMUL::LMUL_1:
1195     return RISCV::VRRegClassID;
1196   case RISCVII::VLMUL::LMUL_2:
1197     return RISCV::VRM2RegClassID;
1198   case RISCVII::VLMUL::LMUL_4:
1199     return RISCV::VRM4RegClassID;
1200   case RISCVII::VLMUL::LMUL_8:
1201     return RISCV::VRM8RegClassID;
1202   }
1203 }
1204 
1205 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1206   RISCVII::VLMUL LMUL = getLMUL(VT);
1207   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1208       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1209       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1210       LMUL == RISCVII::VLMUL::LMUL_1) {
1211     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1212                   "Unexpected subreg numbering");
1213     return RISCV::sub_vrm1_0 + Index;
1214   }
1215   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1216     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1217                   "Unexpected subreg numbering");
1218     return RISCV::sub_vrm2_0 + Index;
1219   }
1220   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1221     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1222                   "Unexpected subreg numbering");
1223     return RISCV::sub_vrm4_0 + Index;
1224   }
1225   llvm_unreachable("Invalid vector type.");
1226 }
1227 
1228 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1229   if (VT.getVectorElementType() == MVT::i1)
1230     return RISCV::VRRegClassID;
1231   return getRegClassIDForLMUL(getLMUL(VT));
1232 }
1233 
1234 // Attempt to decompose a subvector insert/extract between VecVT and
1235 // SubVecVT via subregister indices. Returns the subregister index that
1236 // can perform the subvector insert/extract with the given element index, as
1237 // well as the index corresponding to any leftover subvectors that must be
1238 // further inserted/extracted within the register class for SubVecVT.
1239 std::pair<unsigned, unsigned>
1240 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1241     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1242     const RISCVRegisterInfo *TRI) {
1243   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1244                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1245                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1246                 "Register classes not ordered");
1247   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1248   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1249   // Try to compose a subregister index that takes us from the incoming
1250   // LMUL>1 register class down to the outgoing one. At each step we half
1251   // the LMUL:
1252   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1253   // Note that this is not guaranteed to find a subregister index, such as
1254   // when we are extracting from one VR type to another.
1255   unsigned SubRegIdx = RISCV::NoSubRegister;
1256   for (const unsigned RCID :
1257        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1258     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1259       VecVT = VecVT.getHalfNumVectorElementsVT();
1260       bool IsHi =
1261           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1262       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1263                                             getSubregIndexByMVT(VecVT, IsHi));
1264       if (IsHi)
1265         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1266     }
1267   return {SubRegIdx, InsertExtractIdx};
1268 }
1269 
1270 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1271 // stores for those types.
1272 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1273   return !Subtarget.useRVVForFixedLengthVectors() ||
1274          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1275 }
1276 
1277 static bool useRVVForFixedLengthVectorVT(MVT VT,
1278                                          const RISCVSubtarget &Subtarget) {
1279   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1280   if (!Subtarget.useRVVForFixedLengthVectors())
1281     return false;
1282 
1283   // We only support a set of vector types with a consistent maximum fixed size
1284   // across all supported vector element types to avoid legalization issues.
1285   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1286   // fixed-length vector type we support is 1024 bytes.
1287   if (VT.getFixedSizeInBits() > 1024 * 8)
1288     return false;
1289 
1290   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1291 
1292   MVT EltVT = VT.getVectorElementType();
1293 
1294   // Don't use RVV for vectors we cannot scalarize if required.
1295   switch (EltVT.SimpleTy) {
1296   // i1 is supported but has different rules.
1297   default:
1298     return false;
1299   case MVT::i1:
1300     // Masks can only use a single register.
1301     if (VT.getVectorNumElements() > MinVLen)
1302       return false;
1303     MinVLen /= 8;
1304     break;
1305   case MVT::i8:
1306   case MVT::i16:
1307   case MVT::i32:
1308   case MVT::i64:
1309     break;
1310   case MVT::f16:
1311     if (!Subtarget.hasStdExtZfh())
1312       return false;
1313     break;
1314   case MVT::f32:
1315     if (!Subtarget.hasStdExtF())
1316       return false;
1317     break;
1318   case MVT::f64:
1319     if (!Subtarget.hasStdExtD())
1320       return false;
1321     break;
1322   }
1323 
1324   // Reject elements larger than ELEN.
1325   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1326     return false;
1327 
1328   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1329   // Don't use RVV for types that don't fit.
1330   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1331     return false;
1332 
1333   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1334   // the base fixed length RVV support in place.
1335   if (!VT.isPow2VectorType())
1336     return false;
1337 
1338   return true;
1339 }
1340 
1341 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1342   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1343 }
1344 
1345 // Return the largest legal scalable vector type that matches VT's element type.
1346 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1347                                             const RISCVSubtarget &Subtarget) {
1348   // This may be called before legal types are setup.
1349   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1350           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1351          "Expected legal fixed length vector!");
1352 
1353   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1354   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1355 
1356   MVT EltVT = VT.getVectorElementType();
1357   switch (EltVT.SimpleTy) {
1358   default:
1359     llvm_unreachable("unexpected element type for RVV container");
1360   case MVT::i1:
1361   case MVT::i8:
1362   case MVT::i16:
1363   case MVT::i32:
1364   case MVT::i64:
1365   case MVT::f16:
1366   case MVT::f32:
1367   case MVT::f64: {
1368     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1369     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1370     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1371     unsigned NumElts =
1372         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1373     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1374     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1375     return MVT::getScalableVectorVT(EltVT, NumElts);
1376   }
1377   }
1378 }
1379 
1380 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1381                                             const RISCVSubtarget &Subtarget) {
1382   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1383                                           Subtarget);
1384 }
1385 
1386 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1387   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1388 }
1389 
1390 // Grow V to consume an entire RVV register.
1391 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1392                                        const RISCVSubtarget &Subtarget) {
1393   assert(VT.isScalableVector() &&
1394          "Expected to convert into a scalable vector!");
1395   assert(V.getValueType().isFixedLengthVector() &&
1396          "Expected a fixed length vector operand!");
1397   SDLoc DL(V);
1398   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1399   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1400 }
1401 
1402 // Shrink V so it's just big enough to maintain a VT's worth of data.
1403 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1404                                          const RISCVSubtarget &Subtarget) {
1405   assert(VT.isFixedLengthVector() &&
1406          "Expected to convert into a fixed length vector!");
1407   assert(V.getValueType().isScalableVector() &&
1408          "Expected a scalable vector operand!");
1409   SDLoc DL(V);
1410   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1411   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1412 }
1413 
1414 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1415 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1416 // the vector type that it is contained in.
1417 static std::pair<SDValue, SDValue>
1418 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1419                 const RISCVSubtarget &Subtarget) {
1420   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1421   MVT XLenVT = Subtarget.getXLenVT();
1422   SDValue VL = VecVT.isFixedLengthVector()
1423                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1424                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1425   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1426   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1427   return {Mask, VL};
1428 }
1429 
1430 // As above but assuming the given type is a scalable vector type.
1431 static std::pair<SDValue, SDValue>
1432 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1433                         const RISCVSubtarget &Subtarget) {
1434   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1435   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1436 }
1437 
1438 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1439 // of either is (currently) supported. This can get us into an infinite loop
1440 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1441 // as a ..., etc.
1442 // Until either (or both) of these can reliably lower any node, reporting that
1443 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1444 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1445 // which is not desirable.
1446 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1447     EVT VT, unsigned DefinedValues) const {
1448   return false;
1449 }
1450 
1451 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1452   // Only splats are currently supported.
1453   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1454     return true;
1455 
1456   return false;
1457 }
1458 
1459 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1460   // RISCV FP-to-int conversions saturate to the destination register size, but
1461   // don't produce 0 for nan. We can use a conversion instruction and fix the
1462   // nan case with a compare and a select.
1463   SDValue Src = Op.getOperand(0);
1464 
1465   EVT DstVT = Op.getValueType();
1466   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1467 
1468   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1469   unsigned Opc;
1470   if (SatVT == DstVT)
1471     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1472   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1473     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1474   else
1475     return SDValue();
1476   // FIXME: Support other SatVTs by clamping before or after the conversion.
1477 
1478   SDLoc DL(Op);
1479   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1480 
1481   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1482   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1483 }
1484 
1485 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1486                                  const RISCVSubtarget &Subtarget) {
1487   MVT VT = Op.getSimpleValueType();
1488   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1489 
1490   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1491 
1492   SDLoc DL(Op);
1493   SDValue Mask, VL;
1494   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1495 
1496   unsigned Opc =
1497       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1498   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1499   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1500 }
1501 
1502 struct VIDSequence {
1503   int64_t StepNumerator;
1504   unsigned StepDenominator;
1505   int64_t Addend;
1506 };
1507 
1508 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1509 // to the (non-zero) step S and start value X. This can be then lowered as the
1510 // RVV sequence (VID * S) + X, for example.
1511 // The step S is represented as an integer numerator divided by a positive
1512 // denominator. Note that the implementation currently only identifies
1513 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1514 // cannot detect 2/3, for example.
1515 // Note that this method will also match potentially unappealing index
1516 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1517 // determine whether this is worth generating code for.
1518 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1519   unsigned NumElts = Op.getNumOperands();
1520   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1521   if (!Op.getValueType().isInteger())
1522     return None;
1523 
1524   Optional<unsigned> SeqStepDenom;
1525   Optional<int64_t> SeqStepNum, SeqAddend;
1526   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1527   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1528   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1529     // Assume undef elements match the sequence; we just have to be careful
1530     // when interpolating across them.
1531     if (Op.getOperand(Idx).isUndef())
1532       continue;
1533     // The BUILD_VECTOR must be all constants.
1534     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1535       return None;
1536 
1537     uint64_t Val = Op.getConstantOperandVal(Idx) &
1538                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1539 
1540     if (PrevElt) {
1541       // Calculate the step since the last non-undef element, and ensure
1542       // it's consistent across the entire sequence.
1543       unsigned IdxDiff = Idx - PrevElt->second;
1544       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1545 
1546       // A zero-value value difference means that we're somewhere in the middle
1547       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1548       // step change before evaluating the sequence.
1549       if (ValDiff != 0) {
1550         int64_t Remainder = ValDiff % IdxDiff;
1551         // Normalize the step if it's greater than 1.
1552         if (Remainder != ValDiff) {
1553           // The difference must cleanly divide the element span.
1554           if (Remainder != 0)
1555             return None;
1556           ValDiff /= IdxDiff;
1557           IdxDiff = 1;
1558         }
1559 
1560         if (!SeqStepNum)
1561           SeqStepNum = ValDiff;
1562         else if (ValDiff != SeqStepNum)
1563           return None;
1564 
1565         if (!SeqStepDenom)
1566           SeqStepDenom = IdxDiff;
1567         else if (IdxDiff != *SeqStepDenom)
1568           return None;
1569       }
1570     }
1571 
1572     // Record and/or check any addend.
1573     if (SeqStepNum && SeqStepDenom) {
1574       uint64_t ExpectedVal =
1575           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1576       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1577       if (!SeqAddend)
1578         SeqAddend = Addend;
1579       else if (SeqAddend != Addend)
1580         return None;
1581     }
1582 
1583     // Record this non-undef element for later.
1584     if (!PrevElt || PrevElt->first != Val)
1585       PrevElt = std::make_pair(Val, Idx);
1586   }
1587   // We need to have logged both a step and an addend for this to count as
1588   // a legal index sequence.
1589   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1590     return None;
1591 
1592   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1593 }
1594 
1595 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1596                                  const RISCVSubtarget &Subtarget) {
1597   MVT VT = Op.getSimpleValueType();
1598   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1599 
1600   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1601 
1602   SDLoc DL(Op);
1603   SDValue Mask, VL;
1604   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1605 
1606   MVT XLenVT = Subtarget.getXLenVT();
1607   unsigned NumElts = Op.getNumOperands();
1608 
1609   if (VT.getVectorElementType() == MVT::i1) {
1610     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1611       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1612       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1613     }
1614 
1615     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1616       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1617       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1618     }
1619 
1620     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1621     // scalar integer chunks whose bit-width depends on the number of mask
1622     // bits and XLEN.
1623     // First, determine the most appropriate scalar integer type to use. This
1624     // is at most XLenVT, but may be shrunk to a smaller vector element type
1625     // according to the size of the final vector - use i8 chunks rather than
1626     // XLenVT if we're producing a v8i1. This results in more consistent
1627     // codegen across RV32 and RV64.
1628     unsigned NumViaIntegerBits =
1629         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1630     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1631       // If we have to use more than one INSERT_VECTOR_ELT then this
1632       // optimization is likely to increase code size; avoid peforming it in
1633       // such a case. We can use a load from a constant pool in this case.
1634       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1635         return SDValue();
1636       // Now we can create our integer vector type. Note that it may be larger
1637       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1638       MVT IntegerViaVecVT =
1639           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1640                            divideCeil(NumElts, NumViaIntegerBits));
1641 
1642       uint64_t Bits = 0;
1643       unsigned BitPos = 0, IntegerEltIdx = 0;
1644       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1645 
1646       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1647         // Once we accumulate enough bits to fill our scalar type, insert into
1648         // our vector and clear our accumulated data.
1649         if (I != 0 && I % NumViaIntegerBits == 0) {
1650           if (NumViaIntegerBits <= 32)
1651             Bits = SignExtend64(Bits, 32);
1652           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1653           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1654                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1655           Bits = 0;
1656           BitPos = 0;
1657           IntegerEltIdx++;
1658         }
1659         SDValue V = Op.getOperand(I);
1660         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1661         Bits |= ((uint64_t)BitValue << BitPos);
1662       }
1663 
1664       // Insert the (remaining) scalar value into position in our integer
1665       // vector type.
1666       if (NumViaIntegerBits <= 32)
1667         Bits = SignExtend64(Bits, 32);
1668       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1669       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1670                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1671 
1672       if (NumElts < NumViaIntegerBits) {
1673         // If we're producing a smaller vector than our minimum legal integer
1674         // type, bitcast to the equivalent (known-legal) mask type, and extract
1675         // our final mask.
1676         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1677         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1678         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1679                           DAG.getConstant(0, DL, XLenVT));
1680       } else {
1681         // Else we must have produced an integer type with the same size as the
1682         // mask type; bitcast for the final result.
1683         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1684         Vec = DAG.getBitcast(VT, Vec);
1685       }
1686 
1687       return Vec;
1688     }
1689 
1690     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1691     // vector type, we have a legal equivalently-sized i8 type, so we can use
1692     // that.
1693     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1694     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1695 
1696     SDValue WideVec;
1697     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1698       // For a splat, perform a scalar truncate before creating the wider
1699       // vector.
1700       assert(Splat.getValueType() == XLenVT &&
1701              "Unexpected type for i1 splat value");
1702       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1703                           DAG.getConstant(1, DL, XLenVT));
1704       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1705     } else {
1706       SmallVector<SDValue, 8> Ops(Op->op_values());
1707       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1708       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1709       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1710     }
1711 
1712     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1713   }
1714 
1715   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1716     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1717                                         : RISCVISD::VMV_V_X_VL;
1718     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1719     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1720   }
1721 
1722   // Try and match index sequences, which we can lower to the vid instruction
1723   // with optional modifications. An all-undef vector is matched by
1724   // getSplatValue, above.
1725   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1726     int64_t StepNumerator = SimpleVID->StepNumerator;
1727     unsigned StepDenominator = SimpleVID->StepDenominator;
1728     int64_t Addend = SimpleVID->Addend;
1729     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1730     // threshold since it's the immediate value many RVV instructions accept.
1731     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1732         isInt<5>(Addend)) {
1733       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1734       // Convert right out of the scalable type so we can use standard ISD
1735       // nodes for the rest of the computation. If we used scalable types with
1736       // these, we'd lose the fixed-length vector info and generate worse
1737       // vsetvli code.
1738       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1739       assert(StepNumerator != 0 && "Invalid step");
1740       bool Negate = false;
1741       if (StepNumerator != 1) {
1742         int64_t SplatStepVal = StepNumerator;
1743         unsigned Opcode = ISD::MUL;
1744         if (isPowerOf2_64(std::abs(StepNumerator))) {
1745           Negate = StepNumerator < 0;
1746           Opcode = ISD::SHL;
1747           SplatStepVal = Log2_64(std::abs(StepNumerator));
1748         }
1749         SDValue SplatStep = DAG.getSplatVector(
1750             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1751         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1752       }
1753       if (StepDenominator != 1) {
1754         SDValue SplatStep = DAG.getSplatVector(
1755             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1756         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1757       }
1758       if (Addend != 0 || Negate) {
1759         SDValue SplatAddend =
1760             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1761         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1762       }
1763       return VID;
1764     }
1765   }
1766 
1767   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1768   // when re-interpreted as a vector with a larger element type. For example,
1769   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1770   // could be instead splat as
1771   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1772   // TODO: This optimization could also work on non-constant splats, but it
1773   // would require bit-manipulation instructions to construct the splat value.
1774   SmallVector<SDValue> Sequence;
1775   unsigned EltBitSize = VT.getScalarSizeInBits();
1776   const auto *BV = cast<BuildVectorSDNode>(Op);
1777   if (VT.isInteger() && EltBitSize < 64 &&
1778       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1779       BV->getRepeatedSequence(Sequence) &&
1780       (Sequence.size() * EltBitSize) <= 64) {
1781     unsigned SeqLen = Sequence.size();
1782     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1783     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1784     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1785             ViaIntVT == MVT::i64) &&
1786            "Unexpected sequence type");
1787 
1788     unsigned EltIdx = 0;
1789     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1790     uint64_t SplatValue = 0;
1791     // Construct the amalgamated value which can be splatted as this larger
1792     // vector type.
1793     for (const auto &SeqV : Sequence) {
1794       if (!SeqV.isUndef())
1795         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1796                        << (EltIdx * EltBitSize));
1797       EltIdx++;
1798     }
1799 
1800     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1801     // achieve better constant materializion.
1802     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1803       SplatValue = SignExtend64(SplatValue, 32);
1804 
1805     // Since we can't introduce illegal i64 types at this stage, we can only
1806     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1807     // way we can use RVV instructions to splat.
1808     assert((ViaIntVT.bitsLE(XLenVT) ||
1809             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1810            "Unexpected bitcast sequence");
1811     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1812       SDValue ViaVL =
1813           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1814       MVT ViaContainerVT =
1815           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1816       SDValue Splat =
1817           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1818                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1819       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1820       return DAG.getBitcast(VT, Splat);
1821     }
1822   }
1823 
1824   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1825   // which constitute a large proportion of the elements. In such cases we can
1826   // splat a vector with the dominant element and make up the shortfall with
1827   // INSERT_VECTOR_ELTs.
1828   // Note that this includes vectors of 2 elements by association. The
1829   // upper-most element is the "dominant" one, allowing us to use a splat to
1830   // "insert" the upper element, and an insert of the lower element at position
1831   // 0, which improves codegen.
1832   SDValue DominantValue;
1833   unsigned MostCommonCount = 0;
1834   DenseMap<SDValue, unsigned> ValueCounts;
1835   unsigned NumUndefElts =
1836       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1837 
1838   // Track the number of scalar loads we know we'd be inserting, estimated as
1839   // any non-zero floating-point constant. Other kinds of element are either
1840   // already in registers or are materialized on demand. The threshold at which
1841   // a vector load is more desirable than several scalar materializion and
1842   // vector-insertion instructions is not known.
1843   unsigned NumScalarLoads = 0;
1844 
1845   for (SDValue V : Op->op_values()) {
1846     if (V.isUndef())
1847       continue;
1848 
1849     ValueCounts.insert(std::make_pair(V, 0));
1850     unsigned &Count = ValueCounts[V];
1851 
1852     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1853       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1854 
1855     // Is this value dominant? In case of a tie, prefer the highest element as
1856     // it's cheaper to insert near the beginning of a vector than it is at the
1857     // end.
1858     if (++Count >= MostCommonCount) {
1859       DominantValue = V;
1860       MostCommonCount = Count;
1861     }
1862   }
1863 
1864   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1865   unsigned NumDefElts = NumElts - NumUndefElts;
1866   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1867 
1868   // Don't perform this optimization when optimizing for size, since
1869   // materializing elements and inserting them tends to cause code bloat.
1870   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1871       ((MostCommonCount > DominantValueCountThreshold) ||
1872        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1873     // Start by splatting the most common element.
1874     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1875 
1876     DenseSet<SDValue> Processed{DominantValue};
1877     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1878     for (const auto &OpIdx : enumerate(Op->ops())) {
1879       const SDValue &V = OpIdx.value();
1880       if (V.isUndef() || !Processed.insert(V).second)
1881         continue;
1882       if (ValueCounts[V] == 1) {
1883         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1884                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1885       } else {
1886         // Blend in all instances of this value using a VSELECT, using a
1887         // mask where each bit signals whether that element is the one
1888         // we're after.
1889         SmallVector<SDValue> Ops;
1890         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1891           return DAG.getConstant(V == V1, DL, XLenVT);
1892         });
1893         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
1894                           DAG.getBuildVector(SelMaskTy, DL, Ops),
1895                           DAG.getSplatBuildVector(VT, DL, V), Vec);
1896       }
1897     }
1898 
1899     return Vec;
1900   }
1901 
1902   return SDValue();
1903 }
1904 
1905 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
1906                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
1907   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
1908     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
1909     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
1910     // If Hi constant is all the same sign bit as Lo, lower this as a custom
1911     // node in order to try and match RVV vector/scalar instructions.
1912     if ((LoC >> 31) == HiC)
1913       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
1914   }
1915 
1916   // Fall back to a stack store and stride x0 vector load.
1917   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
1918 }
1919 
1920 // Called by type legalization to handle splat of i64 on RV32.
1921 // FIXME: We can optimize this when the type has sign or zero bits in one
1922 // of the halves.
1923 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
1924                                    SDValue VL, SelectionDAG &DAG) {
1925   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
1926   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1927                            DAG.getConstant(0, DL, MVT::i32));
1928   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1929                            DAG.getConstant(1, DL, MVT::i32));
1930   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
1931 }
1932 
1933 // This function lowers a splat of a scalar operand Splat with the vector
1934 // length VL. It ensures the final sequence is type legal, which is useful when
1935 // lowering a splat after type legalization.
1936 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
1937                                 SelectionDAG &DAG,
1938                                 const RISCVSubtarget &Subtarget) {
1939   if (VT.isFloatingPoint())
1940     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
1941 
1942   MVT XLenVT = Subtarget.getXLenVT();
1943 
1944   // Simplest case is that the operand needs to be promoted to XLenVT.
1945   if (Scalar.getValueType().bitsLE(XLenVT)) {
1946     // If the operand is a constant, sign extend to increase our chances
1947     // of being able to use a .vi instruction. ANY_EXTEND would become a
1948     // a zero extend and the simm5 check in isel would fail.
1949     // FIXME: Should we ignore the upper bits in isel instead?
1950     unsigned ExtOpc =
1951         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
1952     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
1953     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
1954   }
1955 
1956   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
1957          "Unexpected scalar for splat lowering!");
1958 
1959   // Otherwise use the more complicated splatting algorithm.
1960   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
1961 }
1962 
1963 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
1964                                    const RISCVSubtarget &Subtarget) {
1965   SDValue V1 = Op.getOperand(0);
1966   SDValue V2 = Op.getOperand(1);
1967   SDLoc DL(Op);
1968   MVT XLenVT = Subtarget.getXLenVT();
1969   MVT VT = Op.getSimpleValueType();
1970   unsigned NumElts = VT.getVectorNumElements();
1971   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
1972 
1973   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1974 
1975   SDValue TrueMask, VL;
1976   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1977 
1978   if (SVN->isSplat()) {
1979     const int Lane = SVN->getSplatIndex();
1980     if (Lane >= 0) {
1981       MVT SVT = VT.getVectorElementType();
1982 
1983       // Turn splatted vector load into a strided load with an X0 stride.
1984       SDValue V = V1;
1985       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
1986       // with undef.
1987       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
1988       int Offset = Lane;
1989       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
1990         int OpElements =
1991             V.getOperand(0).getSimpleValueType().getVectorNumElements();
1992         V = V.getOperand(Offset / OpElements);
1993         Offset %= OpElements;
1994       }
1995 
1996       // We need to ensure the load isn't atomic or volatile.
1997       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
1998         auto *Ld = cast<LoadSDNode>(V);
1999         Offset *= SVT.getStoreSize();
2000         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2001                                                    TypeSize::Fixed(Offset), DL);
2002 
2003         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2004         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2005           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2006           SDValue IntID =
2007               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2008           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2009                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2010           SDValue NewLoad = DAG.getMemIntrinsicNode(
2011               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2012               DAG.getMachineFunction().getMachineMemOperand(
2013                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2014           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2015           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2016         }
2017 
2018         // Otherwise use a scalar load and splat. This will give the best
2019         // opportunity to fold a splat into the operation. ISel can turn it into
2020         // the x0 strided load if we aren't able to fold away the select.
2021         if (SVT.isFloatingPoint())
2022           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2023                           Ld->getPointerInfo().getWithOffset(Offset),
2024                           Ld->getOriginalAlign(),
2025                           Ld->getMemOperand()->getFlags());
2026         else
2027           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2028                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2029                              Ld->getOriginalAlign(),
2030                              Ld->getMemOperand()->getFlags());
2031         DAG.makeEquivalentMemoryOrdering(Ld, V);
2032 
2033         unsigned Opc =
2034             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2035         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2036         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2037       }
2038 
2039       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2040       assert(Lane < (int)NumElts && "Unexpected lane!");
2041       SDValue Gather =
2042           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2043                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2044       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2045     }
2046   }
2047 
2048   // Detect shuffles which can be re-expressed as vector selects; these are
2049   // shuffles in which each element in the destination is taken from an element
2050   // at the corresponding index in either source vectors.
2051   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2052     int MaskIndex = MaskIdx.value();
2053     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2054   });
2055 
2056   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2057 
2058   SmallVector<SDValue> MaskVals;
2059   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2060   // merged with a second vrgather.
2061   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2062 
2063   // By default we preserve the original operand order, and use a mask to
2064   // select LHS as true and RHS as false. However, since RVV vector selects may
2065   // feature splats but only on the LHS, we may choose to invert our mask and
2066   // instead select between RHS and LHS.
2067   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2068   bool InvertMask = IsSelect == SwapOps;
2069 
2070   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2071   // half.
2072   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2073 
2074   // Now construct the mask that will be used by the vselect or blended
2075   // vrgather operation. For vrgathers, construct the appropriate indices into
2076   // each vector.
2077   for (int MaskIndex : SVN->getMask()) {
2078     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2079     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2080     if (!IsSelect) {
2081       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2082       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2083                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2084                                      : DAG.getUNDEF(XLenVT));
2085       GatherIndicesRHS.push_back(
2086           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2087                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2088       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2089         ++LHSIndexCounts[MaskIndex];
2090       if (!IsLHSOrUndefIndex)
2091         ++RHSIndexCounts[MaskIndex - NumElts];
2092     }
2093   }
2094 
2095   if (SwapOps) {
2096     std::swap(V1, V2);
2097     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2098   }
2099 
2100   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2101   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2102   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2103 
2104   if (IsSelect)
2105     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2106 
2107   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2108     // On such a large vector we're unable to use i8 as the index type.
2109     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2110     // may involve vector splitting if we're already at LMUL=8, or our
2111     // user-supplied maximum fixed-length LMUL.
2112     return SDValue();
2113   }
2114 
2115   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2116   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2117   MVT IndexVT = VT.changeTypeToInteger();
2118   // Since we can't introduce illegal index types at this stage, use i16 and
2119   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2120   // than XLenVT.
2121   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2122     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2123     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2124   }
2125 
2126   MVT IndexContainerVT =
2127       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2128 
2129   SDValue Gather;
2130   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2131   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2132   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2133     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2134   } else {
2135     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2136     // If only one index is used, we can use a "splat" vrgather.
2137     // TODO: We can splat the most-common index and fix-up any stragglers, if
2138     // that's beneficial.
2139     if (LHSIndexCounts.size() == 1) {
2140       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2141       Gather =
2142           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2143                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2144     } else {
2145       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2146       LHSIndices =
2147           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2148 
2149       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2150                            TrueMask, VL);
2151     }
2152   }
2153 
2154   // If a second vector operand is used by this shuffle, blend it in with an
2155   // additional vrgather.
2156   if (!V2.isUndef()) {
2157     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2158     // If only one index is used, we can use a "splat" vrgather.
2159     // TODO: We can splat the most-common index and fix-up any stragglers, if
2160     // that's beneficial.
2161     if (RHSIndexCounts.size() == 1) {
2162       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2163       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2164                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2165     } else {
2166       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2167       RHSIndices =
2168           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2169       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2170                        VL);
2171     }
2172 
2173     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2174     SelectMask =
2175         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2176 
2177     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2178                          Gather, VL);
2179   }
2180 
2181   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2182 }
2183 
2184 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2185                                      SDLoc DL, SelectionDAG &DAG,
2186                                      const RISCVSubtarget &Subtarget) {
2187   if (VT.isScalableVector())
2188     return DAG.getFPExtendOrRound(Op, DL, VT);
2189   assert(VT.isFixedLengthVector() &&
2190          "Unexpected value type for RVV FP extend/round lowering");
2191   SDValue Mask, VL;
2192   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2193   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2194                         ? RISCVISD::FP_EXTEND_VL
2195                         : RISCVISD::FP_ROUND_VL;
2196   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2197 }
2198 
2199 // While RVV has alignment restrictions, we should always be able to load as a
2200 // legal equivalently-sized byte-typed vector instead. This method is
2201 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2202 // the load is already correctly-aligned, it returns SDValue().
2203 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2204                                                     SelectionDAG &DAG) const {
2205   auto *Load = cast<LoadSDNode>(Op);
2206   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2207 
2208   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2209                                      Load->getMemoryVT(),
2210                                      *Load->getMemOperand()))
2211     return SDValue();
2212 
2213   SDLoc DL(Op);
2214   MVT VT = Op.getSimpleValueType();
2215   unsigned EltSizeBits = VT.getScalarSizeInBits();
2216   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2217          "Unexpected unaligned RVV load type");
2218   MVT NewVT =
2219       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2220   assert(NewVT.isValid() &&
2221          "Expecting equally-sized RVV vector types to be legal");
2222   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2223                           Load->getPointerInfo(), Load->getOriginalAlign(),
2224                           Load->getMemOperand()->getFlags());
2225   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2226 }
2227 
2228 // While RVV has alignment restrictions, we should always be able to store as a
2229 // legal equivalently-sized byte-typed vector instead. This method is
2230 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2231 // returns SDValue() if the store is already correctly aligned.
2232 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2233                                                      SelectionDAG &DAG) const {
2234   auto *Store = cast<StoreSDNode>(Op);
2235   assert(Store && Store->getValue().getValueType().isVector() &&
2236          "Expected vector store");
2237 
2238   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2239                                      Store->getMemoryVT(),
2240                                      *Store->getMemOperand()))
2241     return SDValue();
2242 
2243   SDLoc DL(Op);
2244   SDValue StoredVal = Store->getValue();
2245   MVT VT = StoredVal.getSimpleValueType();
2246   unsigned EltSizeBits = VT.getScalarSizeInBits();
2247   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2248          "Unexpected unaligned RVV store type");
2249   MVT NewVT =
2250       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2251   assert(NewVT.isValid() &&
2252          "Expecting equally-sized RVV vector types to be legal");
2253   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2254   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2255                       Store->getPointerInfo(), Store->getOriginalAlign(),
2256                       Store->getMemOperand()->getFlags());
2257 }
2258 
2259 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2260                                             SelectionDAG &DAG) const {
2261   switch (Op.getOpcode()) {
2262   default:
2263     report_fatal_error("unimplemented operand");
2264   case ISD::GlobalAddress:
2265     return lowerGlobalAddress(Op, DAG);
2266   case ISD::BlockAddress:
2267     return lowerBlockAddress(Op, DAG);
2268   case ISD::ConstantPool:
2269     return lowerConstantPool(Op, DAG);
2270   case ISD::JumpTable:
2271     return lowerJumpTable(Op, DAG);
2272   case ISD::GlobalTLSAddress:
2273     return lowerGlobalTLSAddress(Op, DAG);
2274   case ISD::SELECT:
2275     return lowerSELECT(Op, DAG);
2276   case ISD::BRCOND:
2277     return lowerBRCOND(Op, DAG);
2278   case ISD::VASTART:
2279     return lowerVASTART(Op, DAG);
2280   case ISD::FRAMEADDR:
2281     return lowerFRAMEADDR(Op, DAG);
2282   case ISD::RETURNADDR:
2283     return lowerRETURNADDR(Op, DAG);
2284   case ISD::SHL_PARTS:
2285     return lowerShiftLeftParts(Op, DAG);
2286   case ISD::SRA_PARTS:
2287     return lowerShiftRightParts(Op, DAG, true);
2288   case ISD::SRL_PARTS:
2289     return lowerShiftRightParts(Op, DAG, false);
2290   case ISD::BITCAST: {
2291     SDLoc DL(Op);
2292     EVT VT = Op.getValueType();
2293     SDValue Op0 = Op.getOperand(0);
2294     EVT Op0VT = Op0.getValueType();
2295     MVT XLenVT = Subtarget.getXLenVT();
2296     if (VT.isFixedLengthVector()) {
2297       // We can handle fixed length vector bitcasts with a simple replacement
2298       // in isel.
2299       if (Op0VT.isFixedLengthVector())
2300         return Op;
2301       // When bitcasting from scalar to fixed-length vector, insert the scalar
2302       // into a one-element vector of the result type, and perform a vector
2303       // bitcast.
2304       if (!Op0VT.isVector()) {
2305         auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2306         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2307                                               DAG.getUNDEF(BVT), Op0,
2308                                               DAG.getConstant(0, DL, XLenVT)));
2309       }
2310       return SDValue();
2311     }
2312     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2313     // thus: bitcast the vector to a one-element vector type whose element type
2314     // is the same as the result type, and extract the first element.
2315     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2316       LLVMContext &Context = *DAG.getContext();
2317       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
2318       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2319                          DAG.getConstant(0, DL, XLenVT));
2320     }
2321     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2322       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2323       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2324       return FPConv;
2325     }
2326     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2327         Subtarget.hasStdExtF()) {
2328       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2329       SDValue FPConv =
2330           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2331       return FPConv;
2332     }
2333     return SDValue();
2334   }
2335   case ISD::INTRINSIC_WO_CHAIN:
2336     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2337   case ISD::INTRINSIC_W_CHAIN:
2338     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2339   case ISD::BSWAP:
2340   case ISD::BITREVERSE: {
2341     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2342     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2343     MVT VT = Op.getSimpleValueType();
2344     SDLoc DL(Op);
2345     // Start with the maximum immediate value which is the bitwidth - 1.
2346     unsigned Imm = VT.getSizeInBits() - 1;
2347     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2348     if (Op.getOpcode() == ISD::BSWAP)
2349       Imm &= ~0x7U;
2350     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2351                        DAG.getConstant(Imm, DL, VT));
2352   }
2353   case ISD::FSHL:
2354   case ISD::FSHR: {
2355     MVT VT = Op.getSimpleValueType();
2356     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2357     SDLoc DL(Op);
2358     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2359       return Op;
2360     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2361     // use log(XLen) bits. Mask the shift amount accordingly.
2362     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2363     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2364                                 DAG.getConstant(ShAmtWidth, DL, VT));
2365     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2366     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2367   }
2368   case ISD::TRUNCATE: {
2369     SDLoc DL(Op);
2370     MVT VT = Op.getSimpleValueType();
2371     // Only custom-lower vector truncates
2372     if (!VT.isVector())
2373       return Op;
2374 
2375     // Truncates to mask types are handled differently
2376     if (VT.getVectorElementType() == MVT::i1)
2377       return lowerVectorMaskTrunc(Op, DAG);
2378 
2379     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2380     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2381     // truncate by one power of two at a time.
2382     MVT DstEltVT = VT.getVectorElementType();
2383 
2384     SDValue Src = Op.getOperand(0);
2385     MVT SrcVT = Src.getSimpleValueType();
2386     MVT SrcEltVT = SrcVT.getVectorElementType();
2387 
2388     assert(DstEltVT.bitsLT(SrcEltVT) &&
2389            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2390            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2391            "Unexpected vector truncate lowering");
2392 
2393     MVT ContainerVT = SrcVT;
2394     if (SrcVT.isFixedLengthVector()) {
2395       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2396       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2397     }
2398 
2399     SDValue Result = Src;
2400     SDValue Mask, VL;
2401     std::tie(Mask, VL) =
2402         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2403     LLVMContext &Context = *DAG.getContext();
2404     const ElementCount Count = ContainerVT.getVectorElementCount();
2405     do {
2406       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2407       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2408       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2409                            Mask, VL);
2410     } while (SrcEltVT != DstEltVT);
2411 
2412     if (SrcVT.isFixedLengthVector())
2413       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2414 
2415     return Result;
2416   }
2417   case ISD::ANY_EXTEND:
2418   case ISD::ZERO_EXTEND:
2419     if (Op.getOperand(0).getValueType().isVector() &&
2420         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2421       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2422     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2423   case ISD::SIGN_EXTEND:
2424     if (Op.getOperand(0).getValueType().isVector() &&
2425         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2426       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2427     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2428   case ISD::SPLAT_VECTOR_PARTS:
2429     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2430   case ISD::INSERT_VECTOR_ELT:
2431     return lowerINSERT_VECTOR_ELT(Op, DAG);
2432   case ISD::EXTRACT_VECTOR_ELT:
2433     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2434   case ISD::VSCALE: {
2435     MVT VT = Op.getSimpleValueType();
2436     SDLoc DL(Op);
2437     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2438     // We define our scalable vector types for lmul=1 to use a 64 bit known
2439     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2440     // vscale as VLENB / 8.
2441     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2442     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2443       // We assume VLENB is a multiple of 8. We manually choose the best shift
2444       // here because SimplifyDemandedBits isn't always able to simplify it.
2445       uint64_t Val = Op.getConstantOperandVal(0);
2446       if (isPowerOf2_64(Val)) {
2447         uint64_t Log2 = Log2_64(Val);
2448         if (Log2 < 3)
2449           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2450                              DAG.getConstant(3 - Log2, DL, VT));
2451         if (Log2 > 3)
2452           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2453                              DAG.getConstant(Log2 - 3, DL, VT));
2454         return VLENB;
2455       }
2456       // If the multiplier is a multiple of 8, scale it down to avoid needing
2457       // to shift the VLENB value.
2458       if ((Val % 8) == 0)
2459         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2460                            DAG.getConstant(Val / 8, DL, VT));
2461     }
2462 
2463     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2464                                  DAG.getConstant(3, DL, VT));
2465     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2466   }
2467   case ISD::FP_EXTEND: {
2468     // RVV can only do fp_extend to types double the size as the source. We
2469     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2470     // via f32.
2471     SDLoc DL(Op);
2472     MVT VT = Op.getSimpleValueType();
2473     SDValue Src = Op.getOperand(0);
2474     MVT SrcVT = Src.getSimpleValueType();
2475 
2476     // Prepare any fixed-length vector operands.
2477     MVT ContainerVT = VT;
2478     if (SrcVT.isFixedLengthVector()) {
2479       ContainerVT = getContainerForFixedLengthVector(VT);
2480       MVT SrcContainerVT =
2481           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2482       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2483     }
2484 
2485     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2486         SrcVT.getVectorElementType() != MVT::f16) {
2487       // For scalable vectors, we only need to close the gap between
2488       // vXf16->vXf64.
2489       if (!VT.isFixedLengthVector())
2490         return Op;
2491       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2492       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2493       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2494     }
2495 
2496     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2497     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2498     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2499         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2500 
2501     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2502                                            DL, DAG, Subtarget);
2503     if (VT.isFixedLengthVector())
2504       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2505     return Extend;
2506   }
2507   case ISD::FP_ROUND: {
2508     // RVV can only do fp_round to types half the size as the source. We
2509     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2510     // conversion instruction.
2511     SDLoc DL(Op);
2512     MVT VT = Op.getSimpleValueType();
2513     SDValue Src = Op.getOperand(0);
2514     MVT SrcVT = Src.getSimpleValueType();
2515 
2516     // Prepare any fixed-length vector operands.
2517     MVT ContainerVT = VT;
2518     if (VT.isFixedLengthVector()) {
2519       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2520       ContainerVT =
2521           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2522       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2523     }
2524 
2525     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2526         SrcVT.getVectorElementType() != MVT::f64) {
2527       // For scalable vectors, we only need to close the gap between
2528       // vXf64<->vXf16.
2529       if (!VT.isFixedLengthVector())
2530         return Op;
2531       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2532       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2533       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2534     }
2535 
2536     SDValue Mask, VL;
2537     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2538 
2539     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2540     SDValue IntermediateRound =
2541         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2542     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2543                                           DL, DAG, Subtarget);
2544 
2545     if (VT.isFixedLengthVector())
2546       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2547     return Round;
2548   }
2549   case ISD::FP_TO_SINT:
2550   case ISD::FP_TO_UINT:
2551   case ISD::SINT_TO_FP:
2552   case ISD::UINT_TO_FP: {
2553     // RVV can only do fp<->int conversions to types half/double the size as
2554     // the source. We custom-lower any conversions that do two hops into
2555     // sequences.
2556     MVT VT = Op.getSimpleValueType();
2557     if (!VT.isVector())
2558       return Op;
2559     SDLoc DL(Op);
2560     SDValue Src = Op.getOperand(0);
2561     MVT EltVT = VT.getVectorElementType();
2562     MVT SrcVT = Src.getSimpleValueType();
2563     MVT SrcEltVT = SrcVT.getVectorElementType();
2564     unsigned EltSize = EltVT.getSizeInBits();
2565     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2566     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2567            "Unexpected vector element types");
2568 
2569     bool IsInt2FP = SrcEltVT.isInteger();
2570     // Widening conversions
2571     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2572       if (IsInt2FP) {
2573         // Do a regular integer sign/zero extension then convert to float.
2574         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2575                                       VT.getVectorElementCount());
2576         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2577                                  ? ISD::ZERO_EXTEND
2578                                  : ISD::SIGN_EXTEND;
2579         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2580         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2581       }
2582       // FP2Int
2583       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2584       // Do one doubling fp_extend then complete the operation by converting
2585       // to int.
2586       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2587       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2588       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2589     }
2590 
2591     // Narrowing conversions
2592     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2593       if (IsInt2FP) {
2594         // One narrowing int_to_fp, then an fp_round.
2595         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2596         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2597         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2598         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2599       }
2600       // FP2Int
2601       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2602       // representable by the integer, the result is poison.
2603       MVT IVecVT =
2604           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2605                            VT.getVectorElementCount());
2606       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2607       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2608     }
2609 
2610     // Scalable vectors can exit here. Patterns will handle equally-sized
2611     // conversions halving/doubling ones.
2612     if (!VT.isFixedLengthVector())
2613       return Op;
2614 
2615     // For fixed-length vectors we lower to a custom "VL" node.
2616     unsigned RVVOpc = 0;
2617     switch (Op.getOpcode()) {
2618     default:
2619       llvm_unreachable("Impossible opcode");
2620     case ISD::FP_TO_SINT:
2621       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2622       break;
2623     case ISD::FP_TO_UINT:
2624       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2625       break;
2626     case ISD::SINT_TO_FP:
2627       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2628       break;
2629     case ISD::UINT_TO_FP:
2630       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2631       break;
2632     }
2633 
2634     MVT ContainerVT, SrcContainerVT;
2635     // Derive the reference container type from the larger vector type.
2636     if (SrcEltSize > EltSize) {
2637       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2638       ContainerVT =
2639           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2640     } else {
2641       ContainerVT = getContainerForFixedLengthVector(VT);
2642       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2643     }
2644 
2645     SDValue Mask, VL;
2646     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2647 
2648     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2649     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2650     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2651   }
2652   case ISD::FP_TO_SINT_SAT:
2653   case ISD::FP_TO_UINT_SAT:
2654     return lowerFP_TO_INT_SAT(Op, DAG);
2655   case ISD::VECREDUCE_ADD:
2656   case ISD::VECREDUCE_UMAX:
2657   case ISD::VECREDUCE_SMAX:
2658   case ISD::VECREDUCE_UMIN:
2659   case ISD::VECREDUCE_SMIN:
2660     return lowerVECREDUCE(Op, DAG);
2661   case ISD::VECREDUCE_AND:
2662   case ISD::VECREDUCE_OR:
2663   case ISD::VECREDUCE_XOR:
2664     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2665       return lowerVectorMaskVECREDUCE(Op, DAG);
2666     return lowerVECREDUCE(Op, DAG);
2667   case ISD::VECREDUCE_FADD:
2668   case ISD::VECREDUCE_SEQ_FADD:
2669   case ISD::VECREDUCE_FMIN:
2670   case ISD::VECREDUCE_FMAX:
2671     return lowerFPVECREDUCE(Op, DAG);
2672   case ISD::INSERT_SUBVECTOR:
2673     return lowerINSERT_SUBVECTOR(Op, DAG);
2674   case ISD::EXTRACT_SUBVECTOR:
2675     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2676   case ISD::STEP_VECTOR:
2677     return lowerSTEP_VECTOR(Op, DAG);
2678   case ISD::VECTOR_REVERSE:
2679     return lowerVECTOR_REVERSE(Op, DAG);
2680   case ISD::BUILD_VECTOR:
2681     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2682   case ISD::SPLAT_VECTOR:
2683     if (Op.getValueType().getVectorElementType() == MVT::i1)
2684       return lowerVectorMaskSplat(Op, DAG);
2685     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2686   case ISD::VECTOR_SHUFFLE:
2687     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2688   case ISD::CONCAT_VECTORS: {
2689     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2690     // better than going through the stack, as the default expansion does.
2691     SDLoc DL(Op);
2692     MVT VT = Op.getSimpleValueType();
2693     unsigned NumOpElts =
2694         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2695     SDValue Vec = DAG.getUNDEF(VT);
2696     for (const auto &OpIdx : enumerate(Op->ops()))
2697       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2698                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2699     return Vec;
2700   }
2701   case ISD::LOAD:
2702     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2703       return V;
2704     if (Op.getValueType().isFixedLengthVector())
2705       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2706     return Op;
2707   case ISD::STORE:
2708     if (auto V = expandUnalignedRVVStore(Op, DAG))
2709       return V;
2710     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2711       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2712     return Op;
2713   case ISD::MLOAD:
2714   case ISD::VP_LOAD:
2715     return lowerMaskedLoad(Op, DAG);
2716   case ISD::MSTORE:
2717   case ISD::VP_STORE:
2718     return lowerMaskedStore(Op, DAG);
2719   case ISD::SETCC:
2720     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2721   case ISD::ADD:
2722     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2723   case ISD::SUB:
2724     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2725   case ISD::MUL:
2726     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2727   case ISD::MULHS:
2728     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2729   case ISD::MULHU:
2730     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2731   case ISD::AND:
2732     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2733                                               RISCVISD::AND_VL);
2734   case ISD::OR:
2735     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2736                                               RISCVISD::OR_VL);
2737   case ISD::XOR:
2738     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2739                                               RISCVISD::XOR_VL);
2740   case ISD::SDIV:
2741     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2742   case ISD::SREM:
2743     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2744   case ISD::UDIV:
2745     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2746   case ISD::UREM:
2747     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2748   case ISD::SHL:
2749   case ISD::SRA:
2750   case ISD::SRL:
2751     if (Op.getSimpleValueType().isFixedLengthVector())
2752       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2753     // This can be called for an i32 shift amount that needs to be promoted.
2754     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2755            "Unexpected custom legalisation");
2756     return SDValue();
2757   case ISD::SADDSAT:
2758     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2759   case ISD::UADDSAT:
2760     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2761   case ISD::SSUBSAT:
2762     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2763   case ISD::USUBSAT:
2764     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2765   case ISD::FADD:
2766     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2767   case ISD::FSUB:
2768     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2769   case ISD::FMUL:
2770     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2771   case ISD::FDIV:
2772     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2773   case ISD::FNEG:
2774     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2775   case ISD::FABS:
2776     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2777   case ISD::FSQRT:
2778     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2779   case ISD::FMA:
2780     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2781   case ISD::SMIN:
2782     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2783   case ISD::SMAX:
2784     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2785   case ISD::UMIN:
2786     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2787   case ISD::UMAX:
2788     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2789   case ISD::FMINNUM:
2790     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2791   case ISD::FMAXNUM:
2792     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2793   case ISD::ABS:
2794     return lowerABS(Op, DAG);
2795   case ISD::VSELECT:
2796     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2797   case ISD::FCOPYSIGN:
2798     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2799   case ISD::MGATHER:
2800   case ISD::VP_GATHER:
2801     return lowerMaskedGather(Op, DAG);
2802   case ISD::MSCATTER:
2803   case ISD::VP_SCATTER:
2804     return lowerMaskedScatter(Op, DAG);
2805   case ISD::FLT_ROUNDS_:
2806     return lowerGET_ROUNDING(Op, DAG);
2807   case ISD::SET_ROUNDING:
2808     return lowerSET_ROUNDING(Op, DAG);
2809   case ISD::VP_ADD:
2810     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2811   case ISD::VP_SUB:
2812     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2813   case ISD::VP_MUL:
2814     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2815   case ISD::VP_SDIV:
2816     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2817   case ISD::VP_UDIV:
2818     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2819   case ISD::VP_SREM:
2820     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2821   case ISD::VP_UREM:
2822     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2823   case ISD::VP_AND:
2824     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2825   case ISD::VP_OR:
2826     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2827   case ISD::VP_XOR:
2828     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2829   case ISD::VP_ASHR:
2830     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2831   case ISD::VP_LSHR:
2832     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2833   case ISD::VP_SHL:
2834     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2835   case ISD::VP_FADD:
2836     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2837   case ISD::VP_FSUB:
2838     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2839   case ISD::VP_FMUL:
2840     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2841   case ISD::VP_FDIV:
2842     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2843   }
2844 }
2845 
2846 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2847                              SelectionDAG &DAG, unsigned Flags) {
2848   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2849 }
2850 
2851 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2852                              SelectionDAG &DAG, unsigned Flags) {
2853   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2854                                    Flags);
2855 }
2856 
2857 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2858                              SelectionDAG &DAG, unsigned Flags) {
2859   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2860                                    N->getOffset(), Flags);
2861 }
2862 
2863 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2864                              SelectionDAG &DAG, unsigned Flags) {
2865   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2866 }
2867 
2868 template <class NodeTy>
2869 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
2870                                      bool IsLocal) const {
2871   SDLoc DL(N);
2872   EVT Ty = getPointerTy(DAG.getDataLayout());
2873 
2874   if (isPositionIndependent()) {
2875     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2876     if (IsLocal)
2877       // Use PC-relative addressing to access the symbol. This generates the
2878       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
2879       // %pcrel_lo(auipc)).
2880       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2881 
2882     // Use PC-relative addressing to access the GOT for this symbol, then load
2883     // the address from the GOT. This generates the pattern (PseudoLA sym),
2884     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
2885     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
2886   }
2887 
2888   switch (getTargetMachine().getCodeModel()) {
2889   default:
2890     report_fatal_error("Unsupported code model for lowering");
2891   case CodeModel::Small: {
2892     // Generate a sequence for accessing addresses within the first 2 GiB of
2893     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
2894     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
2895     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
2896     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2897     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
2898   }
2899   case CodeModel::Medium: {
2900     // Generate a sequence for accessing addresses within any 2GiB range within
2901     // the address space. This generates the pattern (PseudoLLA sym), which
2902     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
2903     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2904     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2905   }
2906   }
2907 }
2908 
2909 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
2910                                                 SelectionDAG &DAG) const {
2911   SDLoc DL(Op);
2912   EVT Ty = Op.getValueType();
2913   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2914   int64_t Offset = N->getOffset();
2915   MVT XLenVT = Subtarget.getXLenVT();
2916 
2917   const GlobalValue *GV = N->getGlobal();
2918   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2919   SDValue Addr = getAddr(N, DAG, IsLocal);
2920 
2921   // In order to maximise the opportunity for common subexpression elimination,
2922   // emit a separate ADD node for the global address offset instead of folding
2923   // it in the global address node. Later peephole optimisations may choose to
2924   // fold it back in when profitable.
2925   if (Offset != 0)
2926     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
2927                        DAG.getConstant(Offset, DL, XLenVT));
2928   return Addr;
2929 }
2930 
2931 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
2932                                                SelectionDAG &DAG) const {
2933   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2934 
2935   return getAddr(N, DAG);
2936 }
2937 
2938 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
2939                                                SelectionDAG &DAG) const {
2940   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2941 
2942   return getAddr(N, DAG);
2943 }
2944 
2945 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
2946                                             SelectionDAG &DAG) const {
2947   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2948 
2949   return getAddr(N, DAG);
2950 }
2951 
2952 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
2953                                               SelectionDAG &DAG,
2954                                               bool UseGOT) const {
2955   SDLoc DL(N);
2956   EVT Ty = getPointerTy(DAG.getDataLayout());
2957   const GlobalValue *GV = N->getGlobal();
2958   MVT XLenVT = Subtarget.getXLenVT();
2959 
2960   if (UseGOT) {
2961     // Use PC-relative addressing to access the GOT for this TLS symbol, then
2962     // load the address from the GOT and add the thread pointer. This generates
2963     // the pattern (PseudoLA_TLS_IE sym), which expands to
2964     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
2965     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
2966     SDValue Load =
2967         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
2968 
2969     // Add the thread pointer.
2970     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
2971     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
2972   }
2973 
2974   // Generate a sequence for accessing the address relative to the thread
2975   // pointer, with the appropriate adjustment for the thread pointer offset.
2976   // This generates the pattern
2977   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
2978   SDValue AddrHi =
2979       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
2980   SDValue AddrAdd =
2981       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
2982   SDValue AddrLo =
2983       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
2984 
2985   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2986   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
2987   SDValue MNAdd = SDValue(
2988       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
2989       0);
2990   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
2991 }
2992 
2993 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
2994                                                SelectionDAG &DAG) const {
2995   SDLoc DL(N);
2996   EVT Ty = getPointerTy(DAG.getDataLayout());
2997   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
2998   const GlobalValue *GV = N->getGlobal();
2999 
3000   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3001   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3002   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3003   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3004   SDValue Load =
3005       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3006 
3007   // Prepare argument list to generate call.
3008   ArgListTy Args;
3009   ArgListEntry Entry;
3010   Entry.Node = Load;
3011   Entry.Ty = CallTy;
3012   Args.push_back(Entry);
3013 
3014   // Setup call to __tls_get_addr.
3015   TargetLowering::CallLoweringInfo CLI(DAG);
3016   CLI.setDebugLoc(DL)
3017       .setChain(DAG.getEntryNode())
3018       .setLibCallee(CallingConv::C, CallTy,
3019                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3020                     std::move(Args));
3021 
3022   return LowerCallTo(CLI).first;
3023 }
3024 
3025 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3026                                                    SelectionDAG &DAG) const {
3027   SDLoc DL(Op);
3028   EVT Ty = Op.getValueType();
3029   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3030   int64_t Offset = N->getOffset();
3031   MVT XLenVT = Subtarget.getXLenVT();
3032 
3033   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3034 
3035   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3036       CallingConv::GHC)
3037     report_fatal_error("In GHC calling convention TLS is not supported");
3038 
3039   SDValue Addr;
3040   switch (Model) {
3041   case TLSModel::LocalExec:
3042     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3043     break;
3044   case TLSModel::InitialExec:
3045     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3046     break;
3047   case TLSModel::LocalDynamic:
3048   case TLSModel::GeneralDynamic:
3049     Addr = getDynamicTLSAddr(N, DAG);
3050     break;
3051   }
3052 
3053   // In order to maximise the opportunity for common subexpression elimination,
3054   // emit a separate ADD node for the global address offset instead of folding
3055   // it in the global address node. Later peephole optimisations may choose to
3056   // fold it back in when profitable.
3057   if (Offset != 0)
3058     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3059                        DAG.getConstant(Offset, DL, XLenVT));
3060   return Addr;
3061 }
3062 
3063 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3064   SDValue CondV = Op.getOperand(0);
3065   SDValue TrueV = Op.getOperand(1);
3066   SDValue FalseV = Op.getOperand(2);
3067   SDLoc DL(Op);
3068   MVT VT = Op.getSimpleValueType();
3069   MVT XLenVT = Subtarget.getXLenVT();
3070 
3071   // Lower vector SELECTs to VSELECTs by splatting the condition.
3072   if (VT.isVector()) {
3073     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3074     SDValue CondSplat = VT.isScalableVector()
3075                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3076                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3077     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3078   }
3079 
3080   // If the result type is XLenVT and CondV is the output of a SETCC node
3081   // which also operated on XLenVT inputs, then merge the SETCC node into the
3082   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3083   // compare+branch instructions. i.e.:
3084   // (select (setcc lhs, rhs, cc), truev, falsev)
3085   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3086   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3087       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3088     SDValue LHS = CondV.getOperand(0);
3089     SDValue RHS = CondV.getOperand(1);
3090     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3091     ISD::CondCode CCVal = CC->get();
3092 
3093     // Special case for a select of 2 constants that have a diffence of 1.
3094     // Normally this is done by DAGCombine, but if the select is introduced by
3095     // type legalization or op legalization, we miss it. Restricting to SETLT
3096     // case for now because that is what signed saturating add/sub need.
3097     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3098     // but we would probably want to swap the true/false values if the condition
3099     // is SETGE/SETLE to avoid an XORI.
3100     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3101         CCVal == ISD::SETLT) {
3102       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3103       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3104       if (TrueVal - 1 == FalseVal)
3105         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3106       if (TrueVal + 1 == FalseVal)
3107         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3108     }
3109 
3110     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3111 
3112     SDValue TargetCC = DAG.getCondCode(CCVal);
3113     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3114     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3115   }
3116 
3117   // Otherwise:
3118   // (select condv, truev, falsev)
3119   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3120   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3121   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3122 
3123   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3124 
3125   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3126 }
3127 
3128 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3129   SDValue CondV = Op.getOperand(1);
3130   SDLoc DL(Op);
3131   MVT XLenVT = Subtarget.getXLenVT();
3132 
3133   if (CondV.getOpcode() == ISD::SETCC &&
3134       CondV.getOperand(0).getValueType() == XLenVT) {
3135     SDValue LHS = CondV.getOperand(0);
3136     SDValue RHS = CondV.getOperand(1);
3137     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3138 
3139     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3140 
3141     SDValue TargetCC = DAG.getCondCode(CCVal);
3142     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3143                        LHS, RHS, TargetCC, Op.getOperand(2));
3144   }
3145 
3146   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3147                      CondV, DAG.getConstant(0, DL, XLenVT),
3148                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3149 }
3150 
3151 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3152   MachineFunction &MF = DAG.getMachineFunction();
3153   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3154 
3155   SDLoc DL(Op);
3156   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3157                                  getPointerTy(MF.getDataLayout()));
3158 
3159   // vastart just stores the address of the VarArgsFrameIndex slot into the
3160   // memory location argument.
3161   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3162   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3163                       MachinePointerInfo(SV));
3164 }
3165 
3166 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3167                                             SelectionDAG &DAG) const {
3168   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3169   MachineFunction &MF = DAG.getMachineFunction();
3170   MachineFrameInfo &MFI = MF.getFrameInfo();
3171   MFI.setFrameAddressIsTaken(true);
3172   Register FrameReg = RI.getFrameRegister(MF);
3173   int XLenInBytes = Subtarget.getXLen() / 8;
3174 
3175   EVT VT = Op.getValueType();
3176   SDLoc DL(Op);
3177   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3178   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3179   while (Depth--) {
3180     int Offset = -(XLenInBytes * 2);
3181     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3182                               DAG.getIntPtrConstant(Offset, DL));
3183     FrameAddr =
3184         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3185   }
3186   return FrameAddr;
3187 }
3188 
3189 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3190                                              SelectionDAG &DAG) const {
3191   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3192   MachineFunction &MF = DAG.getMachineFunction();
3193   MachineFrameInfo &MFI = MF.getFrameInfo();
3194   MFI.setReturnAddressIsTaken(true);
3195   MVT XLenVT = Subtarget.getXLenVT();
3196   int XLenInBytes = Subtarget.getXLen() / 8;
3197 
3198   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3199     return SDValue();
3200 
3201   EVT VT = Op.getValueType();
3202   SDLoc DL(Op);
3203   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3204   if (Depth) {
3205     int Off = -XLenInBytes;
3206     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3207     SDValue Offset = DAG.getConstant(Off, DL, VT);
3208     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3209                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3210                        MachinePointerInfo());
3211   }
3212 
3213   // Return the value of the return address register, marking it an implicit
3214   // live-in.
3215   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3216   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3217 }
3218 
3219 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3220                                                  SelectionDAG &DAG) const {
3221   SDLoc DL(Op);
3222   SDValue Lo = Op.getOperand(0);
3223   SDValue Hi = Op.getOperand(1);
3224   SDValue Shamt = Op.getOperand(2);
3225   EVT VT = Lo.getValueType();
3226 
3227   // if Shamt-XLEN < 0: // Shamt < XLEN
3228   //   Lo = Lo << Shamt
3229   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3230   // else:
3231   //   Lo = 0
3232   //   Hi = Lo << (Shamt-XLEN)
3233 
3234   SDValue Zero = DAG.getConstant(0, DL, VT);
3235   SDValue One = DAG.getConstant(1, DL, VT);
3236   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3237   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3238   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3239   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3240 
3241   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3242   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3243   SDValue ShiftRightLo =
3244       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3245   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3246   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3247   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3248 
3249   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3250 
3251   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3252   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3253 
3254   SDValue Parts[2] = {Lo, Hi};
3255   return DAG.getMergeValues(Parts, DL);
3256 }
3257 
3258 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3259                                                   bool IsSRA) const {
3260   SDLoc DL(Op);
3261   SDValue Lo = Op.getOperand(0);
3262   SDValue Hi = Op.getOperand(1);
3263   SDValue Shamt = Op.getOperand(2);
3264   EVT VT = Lo.getValueType();
3265 
3266   // SRA expansion:
3267   //   if Shamt-XLEN < 0: // Shamt < XLEN
3268   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3269   //     Hi = Hi >>s Shamt
3270   //   else:
3271   //     Lo = Hi >>s (Shamt-XLEN);
3272   //     Hi = Hi >>s (XLEN-1)
3273   //
3274   // SRL expansion:
3275   //   if Shamt-XLEN < 0: // Shamt < XLEN
3276   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3277   //     Hi = Hi >>u Shamt
3278   //   else:
3279   //     Lo = Hi >>u (Shamt-XLEN);
3280   //     Hi = 0;
3281 
3282   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3283 
3284   SDValue Zero = DAG.getConstant(0, DL, VT);
3285   SDValue One = DAG.getConstant(1, DL, VT);
3286   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3287   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3288   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3289   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3290 
3291   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3292   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3293   SDValue ShiftLeftHi =
3294       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3295   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3296   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3297   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3298   SDValue HiFalse =
3299       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3300 
3301   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3302 
3303   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3304   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3305 
3306   SDValue Parts[2] = {Lo, Hi};
3307   return DAG.getMergeValues(Parts, DL);
3308 }
3309 
3310 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3311 // legal equivalently-sized i8 type, so we can use that as a go-between.
3312 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3313                                                   SelectionDAG &DAG) const {
3314   SDLoc DL(Op);
3315   MVT VT = Op.getSimpleValueType();
3316   SDValue SplatVal = Op.getOperand(0);
3317   // All-zeros or all-ones splats are handled specially.
3318   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3319     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3320     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3321   }
3322   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3323     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3324     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3325   }
3326   MVT XLenVT = Subtarget.getXLenVT();
3327   assert(SplatVal.getValueType() == XLenVT &&
3328          "Unexpected type for i1 splat value");
3329   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3330   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3331                          DAG.getConstant(1, DL, XLenVT));
3332   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3333   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3334   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3335 }
3336 
3337 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3338 // illegal (currently only vXi64 RV32).
3339 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3340 // them to SPLAT_VECTOR_I64
3341 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3342                                                      SelectionDAG &DAG) const {
3343   SDLoc DL(Op);
3344   MVT VecVT = Op.getSimpleValueType();
3345   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3346          "Unexpected SPLAT_VECTOR_PARTS lowering");
3347 
3348   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3349   SDValue Lo = Op.getOperand(0);
3350   SDValue Hi = Op.getOperand(1);
3351 
3352   if (VecVT.isFixedLengthVector()) {
3353     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3354     SDLoc DL(Op);
3355     SDValue Mask, VL;
3356     std::tie(Mask, VL) =
3357         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3358 
3359     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3360     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3361   }
3362 
3363   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3364     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3365     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3366     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3367     // node in order to try and match RVV vector/scalar instructions.
3368     if ((LoC >> 31) == HiC)
3369       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3370   }
3371 
3372   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3373   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3374       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3375       Hi.getConstantOperandVal(1) == 31)
3376     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3377 
3378   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3379   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3380                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3381 }
3382 
3383 // Custom-lower extensions from mask vectors by using a vselect either with 1
3384 // for zero/any-extension or -1 for sign-extension:
3385 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3386 // Note that any-extension is lowered identically to zero-extension.
3387 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3388                                                 int64_t ExtTrueVal) const {
3389   SDLoc DL(Op);
3390   MVT VecVT = Op.getSimpleValueType();
3391   SDValue Src = Op.getOperand(0);
3392   // Only custom-lower extensions from mask types
3393   assert(Src.getValueType().isVector() &&
3394          Src.getValueType().getVectorElementType() == MVT::i1);
3395 
3396   MVT XLenVT = Subtarget.getXLenVT();
3397   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3398   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3399 
3400   if (VecVT.isScalableVector()) {
3401     // Be careful not to introduce illegal scalar types at this stage, and be
3402     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3403     // illegal and must be expanded. Since we know that the constants are
3404     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3405     bool IsRV32E64 =
3406         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3407 
3408     if (!IsRV32E64) {
3409       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3410       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3411     } else {
3412       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3413       SplatTrueVal =
3414           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3415     }
3416 
3417     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3418   }
3419 
3420   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3421   MVT I1ContainerVT =
3422       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3423 
3424   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3425 
3426   SDValue Mask, VL;
3427   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3428 
3429   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3430   SplatTrueVal =
3431       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3432   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3433                                SplatTrueVal, SplatZero, VL);
3434 
3435   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3436 }
3437 
3438 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3439     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3440   MVT ExtVT = Op.getSimpleValueType();
3441   // Only custom-lower extensions from fixed-length vector types.
3442   if (!ExtVT.isFixedLengthVector())
3443     return Op;
3444   MVT VT = Op.getOperand(0).getSimpleValueType();
3445   // Grab the canonical container type for the extended type. Infer the smaller
3446   // type from that to ensure the same number of vector elements, as we know
3447   // the LMUL will be sufficient to hold the smaller type.
3448   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3449   // Get the extended container type manually to ensure the same number of
3450   // vector elements between source and dest.
3451   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3452                                      ContainerExtVT.getVectorElementCount());
3453 
3454   SDValue Op1 =
3455       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3456 
3457   SDLoc DL(Op);
3458   SDValue Mask, VL;
3459   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3460 
3461   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3462 
3463   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3464 }
3465 
3466 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3467 // setcc operation:
3468 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3469 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3470                                                   SelectionDAG &DAG) const {
3471   SDLoc DL(Op);
3472   EVT MaskVT = Op.getValueType();
3473   // Only expect to custom-lower truncations to mask types
3474   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3475          "Unexpected type for vector mask lowering");
3476   SDValue Src = Op.getOperand(0);
3477   MVT VecVT = Src.getSimpleValueType();
3478 
3479   // If this is a fixed vector, we need to convert it to a scalable vector.
3480   MVT ContainerVT = VecVT;
3481   if (VecVT.isFixedLengthVector()) {
3482     ContainerVT = getContainerForFixedLengthVector(VecVT);
3483     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3484   }
3485 
3486   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3487   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3488 
3489   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3490   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3491 
3492   if (VecVT.isScalableVector()) {
3493     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3494     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3495   }
3496 
3497   SDValue Mask, VL;
3498   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3499 
3500   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3501   SDValue Trunc =
3502       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3503   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3504                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3505   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3506 }
3507 
3508 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3509 // first position of a vector, and that vector is slid up to the insert index.
3510 // By limiting the active vector length to index+1 and merging with the
3511 // original vector (with an undisturbed tail policy for elements >= VL), we
3512 // achieve the desired result of leaving all elements untouched except the one
3513 // at VL-1, which is replaced with the desired value.
3514 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3515                                                     SelectionDAG &DAG) const {
3516   SDLoc DL(Op);
3517   MVT VecVT = Op.getSimpleValueType();
3518   SDValue Vec = Op.getOperand(0);
3519   SDValue Val = Op.getOperand(1);
3520   SDValue Idx = Op.getOperand(2);
3521 
3522   if (VecVT.getVectorElementType() == MVT::i1) {
3523     // FIXME: For now we just promote to an i8 vector and insert into that,
3524     // but this is probably not optimal.
3525     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3526     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3527     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3528     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3529   }
3530 
3531   MVT ContainerVT = VecVT;
3532   // If the operand is a fixed-length vector, convert to a scalable one.
3533   if (VecVT.isFixedLengthVector()) {
3534     ContainerVT = getContainerForFixedLengthVector(VecVT);
3535     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3536   }
3537 
3538   MVT XLenVT = Subtarget.getXLenVT();
3539 
3540   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3541   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3542   // Even i64-element vectors on RV32 can be lowered without scalar
3543   // legalization if the most-significant 32 bits of the value are not affected
3544   // by the sign-extension of the lower 32 bits.
3545   // TODO: We could also catch sign extensions of a 32-bit value.
3546   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3547     const auto *CVal = cast<ConstantSDNode>(Val);
3548     if (isInt<32>(CVal->getSExtValue())) {
3549       IsLegalInsert = true;
3550       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3551     }
3552   }
3553 
3554   SDValue Mask, VL;
3555   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3556 
3557   SDValue ValInVec;
3558 
3559   if (IsLegalInsert) {
3560     unsigned Opc =
3561         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3562     if (isNullConstant(Idx)) {
3563       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3564       if (!VecVT.isFixedLengthVector())
3565         return Vec;
3566       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3567     }
3568     ValInVec =
3569         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3570   } else {
3571     // On RV32, i64-element vectors must be specially handled to place the
3572     // value at element 0, by using two vslide1up instructions in sequence on
3573     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3574     // this.
3575     SDValue One = DAG.getConstant(1, DL, XLenVT);
3576     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3577     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3578     MVT I32ContainerVT =
3579         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3580     SDValue I32Mask =
3581         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3582     // Limit the active VL to two.
3583     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3584     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3585     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3586     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3587                            InsertI64VL);
3588     // First slide in the hi value, then the lo in underneath it.
3589     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3590                            ValHi, I32Mask, InsertI64VL);
3591     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3592                            ValLo, I32Mask, InsertI64VL);
3593     // Bitcast back to the right container type.
3594     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3595   }
3596 
3597   // Now that the value is in a vector, slide it into position.
3598   SDValue InsertVL =
3599       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3600   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3601                                 ValInVec, Idx, Mask, InsertVL);
3602   if (!VecVT.isFixedLengthVector())
3603     return Slideup;
3604   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3605 }
3606 
3607 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3608 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3609 // types this is done using VMV_X_S to allow us to glean information about the
3610 // sign bits of the result.
3611 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3612                                                      SelectionDAG &DAG) const {
3613   SDLoc DL(Op);
3614   SDValue Idx = Op.getOperand(1);
3615   SDValue Vec = Op.getOperand(0);
3616   EVT EltVT = Op.getValueType();
3617   MVT VecVT = Vec.getSimpleValueType();
3618   MVT XLenVT = Subtarget.getXLenVT();
3619 
3620   if (VecVT.getVectorElementType() == MVT::i1) {
3621     // FIXME: For now we just promote to an i8 vector and extract from that,
3622     // but this is probably not optimal.
3623     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3624     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3625     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3626   }
3627 
3628   // If this is a fixed vector, we need to convert it to a scalable vector.
3629   MVT ContainerVT = VecVT;
3630   if (VecVT.isFixedLengthVector()) {
3631     ContainerVT = getContainerForFixedLengthVector(VecVT);
3632     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3633   }
3634 
3635   // If the index is 0, the vector is already in the right position.
3636   if (!isNullConstant(Idx)) {
3637     // Use a VL of 1 to avoid processing more elements than we need.
3638     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3639     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3640     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3641     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3642                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3643   }
3644 
3645   if (!EltVT.isInteger()) {
3646     // Floating-point extracts are handled in TableGen.
3647     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3648                        DAG.getConstant(0, DL, XLenVT));
3649   }
3650 
3651   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3652   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3653 }
3654 
3655 // Some RVV intrinsics may claim that they want an integer operand to be
3656 // promoted or expanded.
3657 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3658                                           const RISCVSubtarget &Subtarget) {
3659   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3660           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3661          "Unexpected opcode");
3662 
3663   if (!Subtarget.hasStdExtV())
3664     return SDValue();
3665 
3666   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3667   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3668   SDLoc DL(Op);
3669 
3670   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3671       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3672   if (!II || !II->SplatOperand)
3673     return SDValue();
3674 
3675   unsigned SplatOp = II->SplatOperand + HasChain;
3676   assert(SplatOp < Op.getNumOperands());
3677 
3678   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3679   SDValue &ScalarOp = Operands[SplatOp];
3680   MVT OpVT = ScalarOp.getSimpleValueType();
3681   MVT XLenVT = Subtarget.getXLenVT();
3682 
3683   // If this isn't a scalar, or its type is XLenVT we're done.
3684   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3685     return SDValue();
3686 
3687   // Simplest case is that the operand needs to be promoted to XLenVT.
3688   if (OpVT.bitsLT(XLenVT)) {
3689     // If the operand is a constant, sign extend to increase our chances
3690     // of being able to use a .vi instruction. ANY_EXTEND would become a
3691     // a zero extend and the simm5 check in isel would fail.
3692     // FIXME: Should we ignore the upper bits in isel instead?
3693     unsigned ExtOpc =
3694         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3695     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3696     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3697   }
3698 
3699   // Use the previous operand to get the vXi64 VT. The result might be a mask
3700   // VT for compares. Using the previous operand assumes that the previous
3701   // operand will never have a smaller element size than a scalar operand and
3702   // that a widening operation never uses SEW=64.
3703   // NOTE: If this fails the below assert, we can probably just find the
3704   // element count from any operand or result and use it to construct the VT.
3705   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3706   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3707 
3708   // The more complex case is when the scalar is larger than XLenVT.
3709   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3710          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3711 
3712   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3713   // on the instruction to sign-extend since SEW>XLEN.
3714   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3715     if (isInt<32>(CVal->getSExtValue())) {
3716       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3717       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3718     }
3719   }
3720 
3721   // We need to convert the scalar to a splat vector.
3722   // FIXME: Can we implicitly truncate the scalar if it is known to
3723   // be sign extended?
3724   // VL should be the last operand.
3725   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3726   assert(VL.getValueType() == XLenVT);
3727   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3728   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3729 }
3730 
3731 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3732                                                      SelectionDAG &DAG) const {
3733   unsigned IntNo = Op.getConstantOperandVal(0);
3734   SDLoc DL(Op);
3735   MVT XLenVT = Subtarget.getXLenVT();
3736 
3737   switch (IntNo) {
3738   default:
3739     break; // Don't custom lower most intrinsics.
3740   case Intrinsic::thread_pointer: {
3741     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3742     return DAG.getRegister(RISCV::X4, PtrVT);
3743   }
3744   case Intrinsic::riscv_orc_b:
3745     // Lower to the GORCI encoding for orc.b.
3746     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3747                        DAG.getConstant(7, DL, XLenVT));
3748   case Intrinsic::riscv_grev:
3749   case Intrinsic::riscv_gorc: {
3750     unsigned Opc =
3751         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3752     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3753   }
3754   case Intrinsic::riscv_shfl:
3755   case Intrinsic::riscv_unshfl: {
3756     unsigned Opc =
3757         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3758     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3759   }
3760   case Intrinsic::riscv_bcompress:
3761   case Intrinsic::riscv_bdecompress: {
3762     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3763                                                        : RISCVISD::BDECOMPRESS;
3764     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3765   }
3766   case Intrinsic::riscv_vmv_x_s:
3767     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3768     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3769                        Op.getOperand(1));
3770   case Intrinsic::riscv_vmv_v_x:
3771     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3772                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3773   case Intrinsic::riscv_vfmv_v_f:
3774     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3775                        Op.getOperand(1), Op.getOperand(2));
3776   case Intrinsic::riscv_vmv_s_x: {
3777     SDValue Scalar = Op.getOperand(2);
3778 
3779     if (Scalar.getValueType().bitsLE(XLenVT)) {
3780       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3781       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3782                          Op.getOperand(1), Scalar, Op.getOperand(3));
3783     }
3784 
3785     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3786 
3787     // This is an i64 value that lives in two scalar registers. We have to
3788     // insert this in a convoluted way. First we build vXi64 splat containing
3789     // the/ two values that we assemble using some bit math. Next we'll use
3790     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3791     // to merge element 0 from our splat into the source vector.
3792     // FIXME: This is probably not the best way to do this, but it is
3793     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3794     // point.
3795     //   sw lo, (a0)
3796     //   sw hi, 4(a0)
3797     //   vlse vX, (a0)
3798     //
3799     //   vid.v      vVid
3800     //   vmseq.vx   mMask, vVid, 0
3801     //   vmerge.vvm vDest, vSrc, vVal, mMask
3802     MVT VT = Op.getSimpleValueType();
3803     SDValue Vec = Op.getOperand(1);
3804     SDValue VL = Op.getOperand(3);
3805 
3806     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3807     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3808                                       DAG.getConstant(0, DL, MVT::i32), VL);
3809 
3810     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3811     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3812     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3813     SDValue SelectCond =
3814         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3815                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3816     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3817                        Vec, VL);
3818   }
3819   case Intrinsic::riscv_vslide1up:
3820   case Intrinsic::riscv_vslide1down:
3821   case Intrinsic::riscv_vslide1up_mask:
3822   case Intrinsic::riscv_vslide1down_mask: {
3823     // We need to special case these when the scalar is larger than XLen.
3824     unsigned NumOps = Op.getNumOperands();
3825     bool IsMasked = NumOps == 6;
3826     unsigned OpOffset = IsMasked ? 1 : 0;
3827     SDValue Scalar = Op.getOperand(2 + OpOffset);
3828     if (Scalar.getValueType().bitsLE(XLenVT))
3829       break;
3830 
3831     // Splatting a sign extended constant is fine.
3832     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3833       if (isInt<32>(CVal->getSExtValue()))
3834         break;
3835 
3836     MVT VT = Op.getSimpleValueType();
3837     assert(VT.getVectorElementType() == MVT::i64 &&
3838            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3839 
3840     // Convert the vector source to the equivalent nxvXi32 vector.
3841     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3842     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3843 
3844     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3845                                    DAG.getConstant(0, DL, XLenVT));
3846     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3847                                    DAG.getConstant(1, DL, XLenVT));
3848 
3849     // Double the VL since we halved SEW.
3850     SDValue VL = Op.getOperand(NumOps - 1);
3851     SDValue I32VL =
3852         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3853 
3854     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3855     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3856 
3857     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3858     // instructions.
3859     if (IntNo == Intrinsic::riscv_vslide1up ||
3860         IntNo == Intrinsic::riscv_vslide1up_mask) {
3861       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3862                         I32Mask, I32VL);
3863       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3864                         I32Mask, I32VL);
3865     } else {
3866       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3867                         I32Mask, I32VL);
3868       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3869                         I32Mask, I32VL);
3870     }
3871 
3872     // Convert back to nxvXi64.
3873     Vec = DAG.getBitcast(VT, Vec);
3874 
3875     if (!IsMasked)
3876       return Vec;
3877 
3878     // Apply mask after the operation.
3879     SDValue Mask = Op.getOperand(NumOps - 2);
3880     SDValue MaskedOff = Op.getOperand(1);
3881     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
3882   }
3883   }
3884 
3885   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3886 }
3887 
3888 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3889                                                     SelectionDAG &DAG) const {
3890   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3891 }
3892 
3893 static MVT getLMUL1VT(MVT VT) {
3894   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
3895          "Unexpected vector MVT");
3896   return MVT::getScalableVectorVT(
3897       VT.getVectorElementType(),
3898       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
3899 }
3900 
3901 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
3902   switch (ISDOpcode) {
3903   default:
3904     llvm_unreachable("Unhandled reduction");
3905   case ISD::VECREDUCE_ADD:
3906     return RISCVISD::VECREDUCE_ADD_VL;
3907   case ISD::VECREDUCE_UMAX:
3908     return RISCVISD::VECREDUCE_UMAX_VL;
3909   case ISD::VECREDUCE_SMAX:
3910     return RISCVISD::VECREDUCE_SMAX_VL;
3911   case ISD::VECREDUCE_UMIN:
3912     return RISCVISD::VECREDUCE_UMIN_VL;
3913   case ISD::VECREDUCE_SMIN:
3914     return RISCVISD::VECREDUCE_SMIN_VL;
3915   case ISD::VECREDUCE_AND:
3916     return RISCVISD::VECREDUCE_AND_VL;
3917   case ISD::VECREDUCE_OR:
3918     return RISCVISD::VECREDUCE_OR_VL;
3919   case ISD::VECREDUCE_XOR:
3920     return RISCVISD::VECREDUCE_XOR_VL;
3921   }
3922 }
3923 
3924 SDValue RISCVTargetLowering::lowerVectorMaskVECREDUCE(SDValue Op,
3925                                                       SelectionDAG &DAG) const {
3926   SDLoc DL(Op);
3927   SDValue Vec = Op.getOperand(0);
3928   MVT VecVT = Vec.getSimpleValueType();
3929   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
3930           Op.getOpcode() == ISD::VECREDUCE_OR ||
3931           Op.getOpcode() == ISD::VECREDUCE_XOR) &&
3932          "Unexpected reduction lowering");
3933 
3934   MVT XLenVT = Subtarget.getXLenVT();
3935   assert(Op.getValueType() == XLenVT &&
3936          "Expected reduction output to be legalized to XLenVT");
3937 
3938   MVT ContainerVT = VecVT;
3939   if (VecVT.isFixedLengthVector()) {
3940     ContainerVT = getContainerForFixedLengthVector(VecVT);
3941     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3942   }
3943 
3944   SDValue Mask, VL;
3945   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3946   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3947 
3948   switch (Op.getOpcode()) {
3949   default:
3950     llvm_unreachable("Unhandled reduction");
3951   case ISD::VECREDUCE_AND:
3952     // vpopc ~x == 0
3953     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, Mask, VL);
3954     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3955     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETEQ);
3956   case ISD::VECREDUCE_OR:
3957     // vpopc x != 0
3958     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3959     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
3960   case ISD::VECREDUCE_XOR: {
3961     // ((vpopc x) & 1) != 0
3962     SDValue One = DAG.getConstant(1, DL, XLenVT);
3963     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3964     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
3965     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
3966   }
3967   }
3968 }
3969 
3970 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
3971                                             SelectionDAG &DAG) const {
3972   SDLoc DL(Op);
3973   SDValue Vec = Op.getOperand(0);
3974   EVT VecEVT = Vec.getValueType();
3975 
3976   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
3977 
3978   // Due to ordering in legalize types we may have a vector type that needs to
3979   // be split. Do that manually so we can get down to a legal type.
3980   while (getTypeAction(*DAG.getContext(), VecEVT) ==
3981          TargetLowering::TypeSplitVector) {
3982     SDValue Lo, Hi;
3983     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
3984     VecEVT = Lo.getValueType();
3985     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
3986   }
3987 
3988   // TODO: The type may need to be widened rather than split. Or widened before
3989   // it can be split.
3990   if (!isTypeLegal(VecEVT))
3991     return SDValue();
3992 
3993   MVT VecVT = VecEVT.getSimpleVT();
3994   MVT VecEltVT = VecVT.getVectorElementType();
3995   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
3996 
3997   MVT ContainerVT = VecVT;
3998   if (VecVT.isFixedLengthVector()) {
3999     ContainerVT = getContainerForFixedLengthVector(VecVT);
4000     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4001   }
4002 
4003   MVT M1VT = getLMUL1VT(ContainerVT);
4004 
4005   SDValue Mask, VL;
4006   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4007 
4008   // FIXME: This is a VLMAX splat which might be too large and can prevent
4009   // vsetvli removal.
4010   SDValue NeutralElem =
4011       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4012   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
4013   SDValue Reduction =
4014       DAG.getNode(RVVOpcode, DL, M1VT, Vec, IdentitySplat, Mask, VL);
4015   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4016                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4017   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4018 }
4019 
4020 // Given a reduction op, this function returns the matching reduction opcode,
4021 // the vector SDValue and the scalar SDValue required to lower this to a
4022 // RISCVISD node.
4023 static std::tuple<unsigned, SDValue, SDValue>
4024 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4025   SDLoc DL(Op);
4026   auto Flags = Op->getFlags();
4027   unsigned Opcode = Op.getOpcode();
4028   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4029   switch (Opcode) {
4030   default:
4031     llvm_unreachable("Unhandled reduction");
4032   case ISD::VECREDUCE_FADD:
4033     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
4034                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4035   case ISD::VECREDUCE_SEQ_FADD:
4036     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4037                            Op.getOperand(0));
4038   case ISD::VECREDUCE_FMIN:
4039     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4040                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4041   case ISD::VECREDUCE_FMAX:
4042     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4043                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4044   }
4045 }
4046 
4047 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4048                                               SelectionDAG &DAG) const {
4049   SDLoc DL(Op);
4050   MVT VecEltVT = Op.getSimpleValueType();
4051 
4052   unsigned RVVOpcode;
4053   SDValue VectorVal, ScalarVal;
4054   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4055       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4056   MVT VecVT = VectorVal.getSimpleValueType();
4057 
4058   MVT ContainerVT = VecVT;
4059   if (VecVT.isFixedLengthVector()) {
4060     ContainerVT = getContainerForFixedLengthVector(VecVT);
4061     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4062   }
4063 
4064   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4065 
4066   SDValue Mask, VL;
4067   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4068 
4069   // FIXME: This is a VLMAX splat which might be too large and can prevent
4070   // vsetvli removal.
4071   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
4072   SDValue Reduction =
4073       DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat, Mask, VL);
4074   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4075                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4076 }
4077 
4078 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4079                                                    SelectionDAG &DAG) const {
4080   SDValue Vec = Op.getOperand(0);
4081   SDValue SubVec = Op.getOperand(1);
4082   MVT VecVT = Vec.getSimpleValueType();
4083   MVT SubVecVT = SubVec.getSimpleValueType();
4084 
4085   SDLoc DL(Op);
4086   MVT XLenVT = Subtarget.getXLenVT();
4087   unsigned OrigIdx = Op.getConstantOperandVal(2);
4088   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4089 
4090   // We don't have the ability to slide mask vectors up indexed by their i1
4091   // elements; the smallest we can do is i8. Often we are able to bitcast to
4092   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4093   // into a scalable one, we might not necessarily have enough scalable
4094   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4095   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4096       (OrigIdx != 0 || !Vec.isUndef())) {
4097     if (VecVT.getVectorMinNumElements() >= 8 &&
4098         SubVecVT.getVectorMinNumElements() >= 8) {
4099       assert(OrigIdx % 8 == 0 && "Invalid index");
4100       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4101              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4102              "Unexpected mask vector lowering");
4103       OrigIdx /= 8;
4104       SubVecVT =
4105           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4106                            SubVecVT.isScalableVector());
4107       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4108                                VecVT.isScalableVector());
4109       Vec = DAG.getBitcast(VecVT, Vec);
4110       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4111     } else {
4112       // We can't slide this mask vector up indexed by its i1 elements.
4113       // This poses a problem when we wish to insert a scalable vector which
4114       // can't be re-expressed as a larger type. Just choose the slow path and
4115       // extend to a larger type, then truncate back down.
4116       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4117       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4118       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4119       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4120       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4121                         Op.getOperand(2));
4122       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4123       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4124     }
4125   }
4126 
4127   // If the subvector vector is a fixed-length type, we cannot use subregister
4128   // manipulation to simplify the codegen; we don't know which register of a
4129   // LMUL group contains the specific subvector as we only know the minimum
4130   // register size. Therefore we must slide the vector group up the full
4131   // amount.
4132   if (SubVecVT.isFixedLengthVector()) {
4133     if (OrigIdx == 0 && Vec.isUndef())
4134       return Op;
4135     MVT ContainerVT = VecVT;
4136     if (VecVT.isFixedLengthVector()) {
4137       ContainerVT = getContainerForFixedLengthVector(VecVT);
4138       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4139     }
4140     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4141                          DAG.getUNDEF(ContainerVT), SubVec,
4142                          DAG.getConstant(0, DL, XLenVT));
4143     SDValue Mask =
4144         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4145     // Set the vector length to only the number of elements we care about. Note
4146     // that for slideup this includes the offset.
4147     SDValue VL =
4148         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4149     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4150     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4151                                   SubVec, SlideupAmt, Mask, VL);
4152     if (VecVT.isFixedLengthVector())
4153       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4154     return DAG.getBitcast(Op.getValueType(), Slideup);
4155   }
4156 
4157   unsigned SubRegIdx, RemIdx;
4158   std::tie(SubRegIdx, RemIdx) =
4159       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4160           VecVT, SubVecVT, OrigIdx, TRI);
4161 
4162   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4163   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4164                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4165                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4166 
4167   // 1. If the Idx has been completely eliminated and this subvector's size is
4168   // a vector register or a multiple thereof, or the surrounding elements are
4169   // undef, then this is a subvector insert which naturally aligns to a vector
4170   // register. These can easily be handled using subregister manipulation.
4171   // 2. If the subvector is smaller than a vector register, then the insertion
4172   // must preserve the undisturbed elements of the register. We do this by
4173   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4174   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4175   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4176   // LMUL=1 type back into the larger vector (resolving to another subregister
4177   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4178   // to avoid allocating a large register group to hold our subvector.
4179   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4180     return Op;
4181 
4182   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4183   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4184   // (in our case undisturbed). This means we can set up a subvector insertion
4185   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4186   // size of the subvector.
4187   MVT InterSubVT = VecVT;
4188   SDValue AlignedExtract = Vec;
4189   unsigned AlignedIdx = OrigIdx - RemIdx;
4190   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4191     InterSubVT = getLMUL1VT(VecVT);
4192     // Extract a subvector equal to the nearest full vector register type. This
4193     // should resolve to a EXTRACT_SUBREG instruction.
4194     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4195                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4196   }
4197 
4198   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4199   // For scalable vectors this must be further multiplied by vscale.
4200   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4201 
4202   SDValue Mask, VL;
4203   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4204 
4205   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4206   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4207   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4208   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4209 
4210   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4211                        DAG.getUNDEF(InterSubVT), SubVec,
4212                        DAG.getConstant(0, DL, XLenVT));
4213 
4214   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4215                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4216 
4217   // If required, insert this subvector back into the correct vector register.
4218   // This should resolve to an INSERT_SUBREG instruction.
4219   if (VecVT.bitsGT(InterSubVT))
4220     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4221                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4222 
4223   // We might have bitcast from a mask type: cast back to the original type if
4224   // required.
4225   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4226 }
4227 
4228 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4229                                                     SelectionDAG &DAG) const {
4230   SDValue Vec = Op.getOperand(0);
4231   MVT SubVecVT = Op.getSimpleValueType();
4232   MVT VecVT = Vec.getSimpleValueType();
4233 
4234   SDLoc DL(Op);
4235   MVT XLenVT = Subtarget.getXLenVT();
4236   unsigned OrigIdx = Op.getConstantOperandVal(1);
4237   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4238 
4239   // We don't have the ability to slide mask vectors down indexed by their i1
4240   // elements; the smallest we can do is i8. Often we are able to bitcast to
4241   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4242   // from a scalable one, we might not necessarily have enough scalable
4243   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4244   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4245     if (VecVT.getVectorMinNumElements() >= 8 &&
4246         SubVecVT.getVectorMinNumElements() >= 8) {
4247       assert(OrigIdx % 8 == 0 && "Invalid index");
4248       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4249              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4250              "Unexpected mask vector lowering");
4251       OrigIdx /= 8;
4252       SubVecVT =
4253           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4254                            SubVecVT.isScalableVector());
4255       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4256                                VecVT.isScalableVector());
4257       Vec = DAG.getBitcast(VecVT, Vec);
4258     } else {
4259       // We can't slide this mask vector down, indexed by its i1 elements.
4260       // This poses a problem when we wish to extract a scalable vector which
4261       // can't be re-expressed as a larger type. Just choose the slow path and
4262       // extend to a larger type, then truncate back down.
4263       // TODO: We could probably improve this when extracting certain fixed
4264       // from fixed, where we can extract as i8 and shift the correct element
4265       // right to reach the desired subvector?
4266       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4267       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4268       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4269       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4270                         Op.getOperand(1));
4271       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4272       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4273     }
4274   }
4275 
4276   // If the subvector vector is a fixed-length type, we cannot use subregister
4277   // manipulation to simplify the codegen; we don't know which register of a
4278   // LMUL group contains the specific subvector as we only know the minimum
4279   // register size. Therefore we must slide the vector group down the full
4280   // amount.
4281   if (SubVecVT.isFixedLengthVector()) {
4282     // With an index of 0 this is a cast-like subvector, which can be performed
4283     // with subregister operations.
4284     if (OrigIdx == 0)
4285       return Op;
4286     MVT ContainerVT = VecVT;
4287     if (VecVT.isFixedLengthVector()) {
4288       ContainerVT = getContainerForFixedLengthVector(VecVT);
4289       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4290     }
4291     SDValue Mask =
4292         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4293     // Set the vector length to only the number of elements we care about. This
4294     // avoids sliding down elements we're going to discard straight away.
4295     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4296     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4297     SDValue Slidedown =
4298         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4299                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4300     // Now we can use a cast-like subvector extract to get the result.
4301     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4302                             DAG.getConstant(0, DL, XLenVT));
4303     return DAG.getBitcast(Op.getValueType(), Slidedown);
4304   }
4305 
4306   unsigned SubRegIdx, RemIdx;
4307   std::tie(SubRegIdx, RemIdx) =
4308       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4309           VecVT, SubVecVT, OrigIdx, TRI);
4310 
4311   // If the Idx has been completely eliminated then this is a subvector extract
4312   // which naturally aligns to a vector register. These can easily be handled
4313   // using subregister manipulation.
4314   if (RemIdx == 0)
4315     return Op;
4316 
4317   // Else we must shift our vector register directly to extract the subvector.
4318   // Do this using VSLIDEDOWN.
4319 
4320   // If the vector type is an LMUL-group type, extract a subvector equal to the
4321   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4322   // instruction.
4323   MVT InterSubVT = VecVT;
4324   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4325     InterSubVT = getLMUL1VT(VecVT);
4326     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4327                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4328   }
4329 
4330   // Slide this vector register down by the desired number of elements in order
4331   // to place the desired subvector starting at element 0.
4332   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4333   // For scalable vectors this must be further multiplied by vscale.
4334   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4335 
4336   SDValue Mask, VL;
4337   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4338   SDValue Slidedown =
4339       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4340                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4341 
4342   // Now the vector is in the right position, extract our final subvector. This
4343   // should resolve to a COPY.
4344   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4345                           DAG.getConstant(0, DL, XLenVT));
4346 
4347   // We might have bitcast from a mask type: cast back to the original type if
4348   // required.
4349   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4350 }
4351 
4352 // Lower step_vector to the vid instruction. Any non-identity step value must
4353 // be accounted for my manual expansion.
4354 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4355                                               SelectionDAG &DAG) const {
4356   SDLoc DL(Op);
4357   MVT VT = Op.getSimpleValueType();
4358   MVT XLenVT = Subtarget.getXLenVT();
4359   SDValue Mask, VL;
4360   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4361   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4362   uint64_t StepValImm = Op.getConstantOperandVal(0);
4363   if (StepValImm != 1) {
4364     if (isPowerOf2_64(StepValImm)) {
4365       SDValue StepVal =
4366           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4367                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4368       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4369     } else {
4370       SDValue StepVal = lowerScalarSplat(
4371           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4372           DL, DAG, Subtarget);
4373       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4374     }
4375   }
4376   return StepVec;
4377 }
4378 
4379 // Implement vector_reverse using vrgather.vv with indices determined by
4380 // subtracting the id of each element from (VLMAX-1). This will convert
4381 // the indices like so:
4382 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4383 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4384 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4385                                                  SelectionDAG &DAG) const {
4386   SDLoc DL(Op);
4387   MVT VecVT = Op.getSimpleValueType();
4388   unsigned EltSize = VecVT.getScalarSizeInBits();
4389   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4390 
4391   unsigned MaxVLMAX = 0;
4392   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4393   if (VectorBitsMax != 0)
4394     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4395 
4396   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4397   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4398 
4399   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4400   // to use vrgatherei16.vv.
4401   // TODO: It's also possible to use vrgatherei16.vv for other types to
4402   // decrease register width for the index calculation.
4403   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4404     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4405     // Reverse each half, then reassemble them in reverse order.
4406     // NOTE: It's also possible that after splitting that VLMAX no longer
4407     // requires vrgatherei16.vv.
4408     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4409       SDValue Lo, Hi;
4410       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4411       EVT LoVT, HiVT;
4412       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4413       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4414       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4415       // Reassemble the low and high pieces reversed.
4416       // FIXME: This is a CONCAT_VECTORS.
4417       SDValue Res =
4418           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4419                       DAG.getIntPtrConstant(0, DL));
4420       return DAG.getNode(
4421           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4422           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4423     }
4424 
4425     // Just promote the int type to i16 which will double the LMUL.
4426     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4427     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4428   }
4429 
4430   MVT XLenVT = Subtarget.getXLenVT();
4431   SDValue Mask, VL;
4432   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4433 
4434   // Calculate VLMAX-1 for the desired SEW.
4435   unsigned MinElts = VecVT.getVectorMinNumElements();
4436   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4437                               DAG.getConstant(MinElts, DL, XLenVT));
4438   SDValue VLMinus1 =
4439       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4440 
4441   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4442   bool IsRV32E64 =
4443       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4444   SDValue SplatVL;
4445   if (!IsRV32E64)
4446     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4447   else
4448     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4449 
4450   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4451   SDValue Indices =
4452       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4453 
4454   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4455 }
4456 
4457 SDValue
4458 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4459                                                      SelectionDAG &DAG) const {
4460   SDLoc DL(Op);
4461   auto *Load = cast<LoadSDNode>(Op);
4462 
4463   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4464                                         Load->getMemoryVT(),
4465                                         *Load->getMemOperand()) &&
4466          "Expecting a correctly-aligned load");
4467 
4468   MVT VT = Op.getSimpleValueType();
4469   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4470 
4471   SDValue VL =
4472       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4473 
4474   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4475   SDValue NewLoad = DAG.getMemIntrinsicNode(
4476       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4477       Load->getMemoryVT(), Load->getMemOperand());
4478 
4479   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4480   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4481 }
4482 
4483 SDValue
4484 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4485                                                       SelectionDAG &DAG) const {
4486   SDLoc DL(Op);
4487   auto *Store = cast<StoreSDNode>(Op);
4488 
4489   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4490                                         Store->getMemoryVT(),
4491                                         *Store->getMemOperand()) &&
4492          "Expecting a correctly-aligned store");
4493 
4494   SDValue StoreVal = Store->getValue();
4495   MVT VT = StoreVal.getSimpleValueType();
4496 
4497   // If the size less than a byte, we need to pad with zeros to make a byte.
4498   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4499     VT = MVT::v8i1;
4500     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4501                            DAG.getConstant(0, DL, VT), StoreVal,
4502                            DAG.getIntPtrConstant(0, DL));
4503   }
4504 
4505   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4506 
4507   SDValue VL =
4508       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4509 
4510   SDValue NewValue =
4511       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4512   return DAG.getMemIntrinsicNode(
4513       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4514       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4515       Store->getMemoryVT(), Store->getMemOperand());
4516 }
4517 
4518 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
4519                                              SelectionDAG &DAG) const {
4520   SDLoc DL(Op);
4521   MVT VT = Op.getSimpleValueType();
4522 
4523   const auto *MemSD = cast<MemSDNode>(Op);
4524   EVT MemVT = MemSD->getMemoryVT();
4525   MachineMemOperand *MMO = MemSD->getMemOperand();
4526   SDValue Chain = MemSD->getChain();
4527   SDValue BasePtr = MemSD->getBasePtr();
4528 
4529   SDValue Mask, PassThru, VL;
4530   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
4531     Mask = VPLoad->getMask();
4532     PassThru = DAG.getUNDEF(VT);
4533     VL = VPLoad->getVectorLength();
4534   } else {
4535     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
4536     Mask = MLoad->getMask();
4537     PassThru = MLoad->getPassThru();
4538   }
4539 
4540   MVT XLenVT = Subtarget.getXLenVT();
4541 
4542   MVT ContainerVT = VT;
4543   if (VT.isFixedLengthVector()) {
4544     ContainerVT = getContainerForFixedLengthVector(VT);
4545     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4546 
4547     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4548     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4549   }
4550 
4551   if (!VL)
4552     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4553 
4554   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4555   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT);
4556   SDValue Ops[] = {Chain, IntID, PassThru, BasePtr, Mask, VL};
4557   SDValue Result =
4558       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4559   Chain = Result.getValue(1);
4560 
4561   if (VT.isFixedLengthVector())
4562     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4563 
4564   return DAG.getMergeValues({Result, Chain}, DL);
4565 }
4566 
4567 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
4568                                               SelectionDAG &DAG) const {
4569   SDLoc DL(Op);
4570 
4571   const auto *MemSD = cast<MemSDNode>(Op);
4572   EVT MemVT = MemSD->getMemoryVT();
4573   MachineMemOperand *MMO = MemSD->getMemOperand();
4574   SDValue Chain = MemSD->getChain();
4575   SDValue BasePtr = MemSD->getBasePtr();
4576   SDValue Val, Mask, VL;
4577 
4578   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
4579     Val = VPStore->getValue();
4580     Mask = VPStore->getMask();
4581     VL = VPStore->getVectorLength();
4582   } else {
4583     const auto *MStore = cast<MaskedStoreSDNode>(Op);
4584     Val = MStore->getValue();
4585     Mask = MStore->getMask();
4586   }
4587 
4588   MVT VT = Val.getSimpleValueType();
4589   MVT XLenVT = Subtarget.getXLenVT();
4590 
4591   MVT ContainerVT = VT;
4592   if (VT.isFixedLengthVector()) {
4593     ContainerVT = getContainerForFixedLengthVector(VT);
4594     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4595 
4596     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4597     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4598   }
4599 
4600   if (!VL)
4601     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4602 
4603   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vse_mask, DL, XLenVT);
4604   return DAG.getMemIntrinsicNode(
4605       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
4606       {Chain, IntID, Val, BasePtr, Mask, VL}, MemVT, MMO);
4607 }
4608 
4609 SDValue
4610 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4611                                                       SelectionDAG &DAG) const {
4612   MVT InVT = Op.getOperand(0).getSimpleValueType();
4613   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4614 
4615   MVT VT = Op.getSimpleValueType();
4616 
4617   SDValue Op1 =
4618       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4619   SDValue Op2 =
4620       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4621 
4622   SDLoc DL(Op);
4623   SDValue VL =
4624       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4625 
4626   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4627   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4628 
4629   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4630                             Op.getOperand(2), Mask, VL);
4631 
4632   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
4633 }
4634 
4635 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
4636     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
4637   MVT VT = Op.getSimpleValueType();
4638 
4639   if (VT.getVectorElementType() == MVT::i1)
4640     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
4641 
4642   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
4643 }
4644 
4645 SDValue
4646 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
4647                                                       SelectionDAG &DAG) const {
4648   unsigned Opc;
4649   switch (Op.getOpcode()) {
4650   default: llvm_unreachable("Unexpected opcode!");
4651   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
4652   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
4653   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
4654   }
4655 
4656   return lowerToScalableOp(Op, DAG, Opc);
4657 }
4658 
4659 // Lower vector ABS to smax(X, sub(0, X)).
4660 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
4661   SDLoc DL(Op);
4662   MVT VT = Op.getSimpleValueType();
4663   SDValue X = Op.getOperand(0);
4664 
4665   assert(VT.isFixedLengthVector() && "Unexpected type");
4666 
4667   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4668   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
4669 
4670   SDValue Mask, VL;
4671   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4672 
4673   SDValue SplatZero =
4674       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4675                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4676   SDValue NegX =
4677       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
4678   SDValue Max =
4679       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
4680 
4681   return convertFromScalableVector(VT, Max, DAG, Subtarget);
4682 }
4683 
4684 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
4685     SDValue Op, SelectionDAG &DAG) const {
4686   SDLoc DL(Op);
4687   MVT VT = Op.getSimpleValueType();
4688   SDValue Mag = Op.getOperand(0);
4689   SDValue Sign = Op.getOperand(1);
4690   assert(Mag.getValueType() == Sign.getValueType() &&
4691          "Can only handle COPYSIGN with matching types.");
4692 
4693   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4694   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
4695   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
4696 
4697   SDValue Mask, VL;
4698   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4699 
4700   SDValue CopySign =
4701       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
4702 
4703   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
4704 }
4705 
4706 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
4707     SDValue Op, SelectionDAG &DAG) const {
4708   MVT VT = Op.getSimpleValueType();
4709   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4710 
4711   MVT I1ContainerVT =
4712       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4713 
4714   SDValue CC =
4715       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
4716   SDValue Op1 =
4717       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4718   SDValue Op2 =
4719       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
4720 
4721   SDLoc DL(Op);
4722   SDValue Mask, VL;
4723   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4724 
4725   SDValue Select =
4726       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
4727 
4728   return convertFromScalableVector(VT, Select, DAG, Subtarget);
4729 }
4730 
4731 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
4732                                                unsigned NewOpc,
4733                                                bool HasMask) const {
4734   MVT VT = Op.getSimpleValueType();
4735   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4736 
4737   // Create list of operands by converting existing ones to scalable types.
4738   SmallVector<SDValue, 6> Ops;
4739   for (const SDValue &V : Op->op_values()) {
4740     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4741 
4742     // Pass through non-vector operands.
4743     if (!V.getValueType().isVector()) {
4744       Ops.push_back(V);
4745       continue;
4746     }
4747 
4748     // "cast" fixed length vector to a scalable vector.
4749     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
4750            "Only fixed length vectors are supported!");
4751     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4752   }
4753 
4754   SDLoc DL(Op);
4755   SDValue Mask, VL;
4756   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4757   if (HasMask)
4758     Ops.push_back(Mask);
4759   Ops.push_back(VL);
4760 
4761   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
4762   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
4763 }
4764 
4765 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
4766 // * Operands of each node are assumed to be in the same order.
4767 // * The EVL operand is promoted from i32 to i64 on RV64.
4768 // * Fixed-length vectors are converted to their scalable-vector container
4769 //   types.
4770 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
4771                                        unsigned RISCVISDOpc) const {
4772   SDLoc DL(Op);
4773   MVT VT = Op.getSimpleValueType();
4774   SmallVector<SDValue, 4> Ops;
4775 
4776   for (const auto &OpIdx : enumerate(Op->ops())) {
4777     SDValue V = OpIdx.value();
4778     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4779     // Pass through operands which aren't fixed-length vectors.
4780     if (!V.getValueType().isFixedLengthVector()) {
4781       Ops.push_back(V);
4782       continue;
4783     }
4784     // "cast" fixed length vector to a scalable vector.
4785     MVT OpVT = V.getSimpleValueType();
4786     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
4787     assert(useRVVForFixedLengthVectorVT(OpVT) &&
4788            "Only fixed length vectors are supported!");
4789     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4790   }
4791 
4792   if (!VT.isFixedLengthVector())
4793     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
4794 
4795   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4796 
4797   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
4798 
4799   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
4800 }
4801 
4802 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
4803 // matched to a RVV indexed load. The RVV indexed load instructions only
4804 // support the "unsigned unscaled" addressing mode; indices are implicitly
4805 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
4806 // signed or scaled indexing is extended to the XLEN value type and scaled
4807 // accordingly.
4808 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
4809                                                SelectionDAG &DAG) const {
4810   SDLoc DL(Op);
4811   MVT VT = Op.getSimpleValueType();
4812 
4813   const auto *MemSD = cast<MemSDNode>(Op.getNode());
4814   EVT MemVT = MemSD->getMemoryVT();
4815   MachineMemOperand *MMO = MemSD->getMemOperand();
4816   SDValue Chain = MemSD->getChain();
4817   SDValue BasePtr = MemSD->getBasePtr();
4818 
4819   ISD::LoadExtType LoadExtType;
4820   SDValue Index, Mask, PassThru, VL;
4821 
4822   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
4823     Index = VPGN->getIndex();
4824     Mask = VPGN->getMask();
4825     PassThru = DAG.getUNDEF(VT);
4826     VL = VPGN->getVectorLength();
4827     // VP doesn't support extending loads.
4828     LoadExtType = ISD::NON_EXTLOAD;
4829   } else {
4830     // Else it must be a MGATHER.
4831     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
4832     Index = MGN->getIndex();
4833     Mask = MGN->getMask();
4834     PassThru = MGN->getPassThru();
4835     LoadExtType = MGN->getExtensionType();
4836   }
4837 
4838   MVT IndexVT = Index.getSimpleValueType();
4839   MVT XLenVT = Subtarget.getXLenVT();
4840 
4841   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
4842          "Unexpected VTs!");
4843   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
4844   // Targets have to explicitly opt-in for extending vector loads.
4845   assert(LoadExtType == ISD::NON_EXTLOAD &&
4846          "Unexpected extending MGATHER/VP_GATHER");
4847   (void)LoadExtType;
4848 
4849   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4850   // the selection of the masked intrinsics doesn't do this for us.
4851   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4852 
4853   MVT ContainerVT = VT;
4854   if (VT.isFixedLengthVector()) {
4855     // We need to use the larger of the result and index type to determine the
4856     // scalable type to use so we don't increase LMUL for any operand/result.
4857     if (VT.bitsGE(IndexVT)) {
4858       ContainerVT = getContainerForFixedLengthVector(VT);
4859       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
4860                                  ContainerVT.getVectorElementCount());
4861     } else {
4862       IndexVT = getContainerForFixedLengthVector(IndexVT);
4863       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
4864                                      IndexVT.getVectorElementCount());
4865     }
4866 
4867     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
4868 
4869     if (!IsUnmasked) {
4870       MVT MaskVT =
4871           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4872       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4873       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4874     }
4875   }
4876 
4877   if (!VL)
4878     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4879 
4880   unsigned IntID =
4881       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
4882   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4883   if (!IsUnmasked)
4884     Ops.push_back(PassThru);
4885   Ops.push_back(BasePtr);
4886   Ops.push_back(Index);
4887   if (!IsUnmasked)
4888     Ops.push_back(Mask);
4889   Ops.push_back(VL);
4890 
4891   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4892   SDValue Result =
4893       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
4894   Chain = Result.getValue(1);
4895 
4896   if (VT.isFixedLengthVector())
4897     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4898 
4899   return DAG.getMergeValues({Result, Chain}, DL);
4900 }
4901 
4902 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
4903 // matched to a RVV indexed store. The RVV indexed store instructions only
4904 // support the "unsigned unscaled" addressing mode; indices are implicitly
4905 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
4906 // signed or scaled indexing is extended to the XLEN value type and scaled
4907 // accordingly.
4908 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
4909                                                 SelectionDAG &DAG) const {
4910   SDLoc DL(Op);
4911   const auto *MemSD = cast<MemSDNode>(Op.getNode());
4912   EVT MemVT = MemSD->getMemoryVT();
4913   MachineMemOperand *MMO = MemSD->getMemOperand();
4914   SDValue Chain = MemSD->getChain();
4915   SDValue BasePtr = MemSD->getBasePtr();
4916 
4917   bool IsTruncatingStore = false;
4918   SDValue Index, Mask, Val, VL;
4919 
4920   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
4921     Index = VPSN->getIndex();
4922     Mask = VPSN->getMask();
4923     Val = VPSN->getValue();
4924     VL = VPSN->getVectorLength();
4925     // VP doesn't support truncating stores.
4926     IsTruncatingStore = false;
4927   } else {
4928     // Else it must be a MSCATTER.
4929     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
4930     Index = MSN->getIndex();
4931     Mask = MSN->getMask();
4932     Val = MSN->getValue();
4933     IsTruncatingStore = MSN->isTruncatingStore();
4934   }
4935 
4936   MVT VT = Val.getSimpleValueType();
4937   MVT IndexVT = Index.getSimpleValueType();
4938   MVT XLenVT = Subtarget.getXLenVT();
4939 
4940   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
4941          "Unexpected VTs!");
4942   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
4943   // Targets have to explicitly opt-in for extending vector loads and
4944   // truncating vector stores.
4945   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
4946   (void)IsTruncatingStore;
4947 
4948   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4949   // the selection of the masked intrinsics doesn't do this for us.
4950   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4951 
4952   MVT ContainerVT = VT;
4953   if (VT.isFixedLengthVector()) {
4954     // We need to use the larger of the value and index type to determine the
4955     // scalable type to use so we don't increase LMUL for any operand/result.
4956     if (VT.bitsGE(IndexVT)) {
4957       ContainerVT = getContainerForFixedLengthVector(VT);
4958       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
4959                                  ContainerVT.getVectorElementCount());
4960     } else {
4961       IndexVT = getContainerForFixedLengthVector(IndexVT);
4962       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4963                                      IndexVT.getVectorElementCount());
4964     }
4965 
4966     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
4967     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4968 
4969     if (!IsUnmasked) {
4970       MVT MaskVT =
4971           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4972       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4973     }
4974   }
4975 
4976   if (!VL)
4977     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
4978 
4979   unsigned IntID =
4980       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
4981   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
4982   Ops.push_back(Val);
4983   Ops.push_back(BasePtr);
4984   Ops.push_back(Index);
4985   if (!IsUnmasked)
4986     Ops.push_back(Mask);
4987   Ops.push_back(VL);
4988 
4989   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
4990                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
4991 }
4992 
4993 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
4994                                                SelectionDAG &DAG) const {
4995   const MVT XLenVT = Subtarget.getXLenVT();
4996   SDLoc DL(Op);
4997   SDValue Chain = Op->getOperand(0);
4998   SDValue SysRegNo = DAG.getConstant(
4999       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5000   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5001   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5002 
5003   // Encoding used for rounding mode in RISCV differs from that used in
5004   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5005   // table, which consists of a sequence of 4-bit fields, each representing
5006   // corresponding FLT_ROUNDS mode.
5007   static const int Table =
5008       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5009       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5010       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5011       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5012       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5013 
5014   SDValue Shift =
5015       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5016   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5017                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5018   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5019                                DAG.getConstant(7, DL, XLenVT));
5020 
5021   return DAG.getMergeValues({Masked, Chain}, DL);
5022 }
5023 
5024 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5025                                                SelectionDAG &DAG) const {
5026   const MVT XLenVT = Subtarget.getXLenVT();
5027   SDLoc DL(Op);
5028   SDValue Chain = Op->getOperand(0);
5029   SDValue RMValue = Op->getOperand(1);
5030   SDValue SysRegNo = DAG.getConstant(
5031       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5032 
5033   // Encoding used for rounding mode in RISCV differs from that used in
5034   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5035   // a table, which consists of a sequence of 4-bit fields, each representing
5036   // corresponding RISCV mode.
5037   static const unsigned Table =
5038       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5039       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5040       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5041       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5042       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5043 
5044   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5045                               DAG.getConstant(2, DL, XLenVT));
5046   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5047                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5048   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5049                         DAG.getConstant(0x7, DL, XLenVT));
5050   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5051                      RMValue);
5052 }
5053 
5054 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5055 // form of the given Opcode.
5056 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5057   switch (Opcode) {
5058   default:
5059     llvm_unreachable("Unexpected opcode");
5060   case ISD::SHL:
5061     return RISCVISD::SLLW;
5062   case ISD::SRA:
5063     return RISCVISD::SRAW;
5064   case ISD::SRL:
5065     return RISCVISD::SRLW;
5066   case ISD::SDIV:
5067     return RISCVISD::DIVW;
5068   case ISD::UDIV:
5069     return RISCVISD::DIVUW;
5070   case ISD::UREM:
5071     return RISCVISD::REMUW;
5072   case ISD::ROTL:
5073     return RISCVISD::ROLW;
5074   case ISD::ROTR:
5075     return RISCVISD::RORW;
5076   case RISCVISD::GREV:
5077     return RISCVISD::GREVW;
5078   case RISCVISD::GORC:
5079     return RISCVISD::GORCW;
5080   }
5081 }
5082 
5083 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5084 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5085 // otherwise be promoted to i64, making it difficult to select the
5086 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5087 // type i8/i16/i32 is lost.
5088 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5089                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5090   SDLoc DL(N);
5091   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5092   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5093   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5094   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5095   // ReplaceNodeResults requires we maintain the same type for the return value.
5096   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5097 }
5098 
5099 // Converts the given 32-bit operation to a i64 operation with signed extension
5100 // semantic to reduce the signed extension instructions.
5101 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5102   SDLoc DL(N);
5103   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5104   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5105   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5106   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5107                                DAG.getValueType(MVT::i32));
5108   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5109 }
5110 
5111 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5112                                              SmallVectorImpl<SDValue> &Results,
5113                                              SelectionDAG &DAG) const {
5114   SDLoc DL(N);
5115   switch (N->getOpcode()) {
5116   default:
5117     llvm_unreachable("Don't know how to custom type legalize this operation!");
5118   case ISD::STRICT_FP_TO_SINT:
5119   case ISD::STRICT_FP_TO_UINT:
5120   case ISD::FP_TO_SINT:
5121   case ISD::FP_TO_UINT: {
5122     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5123            "Unexpected custom legalisation");
5124     bool IsStrict = N->isStrictFPOpcode();
5125     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5126                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5127     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5128     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5129         TargetLowering::TypeSoftenFloat) {
5130       // FIXME: Support strict FP.
5131       if (IsStrict)
5132         return;
5133       if (!isTypeLegal(Op0.getValueType()))
5134         return;
5135       unsigned Opc =
5136           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
5137       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
5138       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5139       return;
5140     }
5141     // If the FP type needs to be softened, emit a library call using the 'si'
5142     // version. If we left it to default legalization we'd end up with 'di'. If
5143     // the FP type doesn't need to be softened just let generic type
5144     // legalization promote the result type.
5145     RTLIB::Libcall LC;
5146     if (IsSigned)
5147       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5148     else
5149       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5150     MakeLibCallOptions CallOptions;
5151     EVT OpVT = Op0.getValueType();
5152     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5153     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5154     SDValue Result;
5155     std::tie(Result, Chain) =
5156         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5157     Results.push_back(Result);
5158     if (IsStrict)
5159       Results.push_back(Chain);
5160     break;
5161   }
5162   case ISD::READCYCLECOUNTER: {
5163     assert(!Subtarget.is64Bit() &&
5164            "READCYCLECOUNTER only has custom type legalization on riscv32");
5165 
5166     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5167     SDValue RCW =
5168         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5169 
5170     Results.push_back(
5171         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5172     Results.push_back(RCW.getValue(2));
5173     break;
5174   }
5175   case ISD::MUL: {
5176     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5177     unsigned XLen = Subtarget.getXLen();
5178     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5179     if (Size > XLen) {
5180       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5181       SDValue LHS = N->getOperand(0);
5182       SDValue RHS = N->getOperand(1);
5183       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5184 
5185       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5186       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5187       // We need exactly one side to be unsigned.
5188       if (LHSIsU == RHSIsU)
5189         return;
5190 
5191       auto MakeMULPair = [&](SDValue S, SDValue U) {
5192         MVT XLenVT = Subtarget.getXLenVT();
5193         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5194         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5195         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5196         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5197         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5198       };
5199 
5200       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5201       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5202 
5203       // The other operand should be signed, but still prefer MULH when
5204       // possible.
5205       if (RHSIsU && LHSIsS && !RHSIsS)
5206         Results.push_back(MakeMULPair(LHS, RHS));
5207       else if (LHSIsU && RHSIsS && !LHSIsS)
5208         Results.push_back(MakeMULPair(RHS, LHS));
5209 
5210       return;
5211     }
5212     LLVM_FALLTHROUGH;
5213   }
5214   case ISD::ADD:
5215   case ISD::SUB:
5216     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5217            "Unexpected custom legalisation");
5218     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5219     break;
5220   case ISD::SHL:
5221   case ISD::SRA:
5222   case ISD::SRL:
5223     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5224            "Unexpected custom legalisation");
5225     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5226       Results.push_back(customLegalizeToWOp(N, DAG));
5227       break;
5228     }
5229 
5230     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5231     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5232     // shift amount.
5233     if (N->getOpcode() == ISD::SHL) {
5234       SDLoc DL(N);
5235       SDValue NewOp0 =
5236           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5237       SDValue NewOp1 =
5238           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5239       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5240       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5241                                    DAG.getValueType(MVT::i32));
5242       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5243     }
5244 
5245     break;
5246   case ISD::ROTL:
5247   case ISD::ROTR:
5248     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5249            "Unexpected custom legalisation");
5250     Results.push_back(customLegalizeToWOp(N, DAG));
5251     break;
5252   case ISD::CTTZ:
5253   case ISD::CTTZ_ZERO_UNDEF:
5254   case ISD::CTLZ:
5255   case ISD::CTLZ_ZERO_UNDEF: {
5256     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5257            "Unexpected custom legalisation");
5258 
5259     SDValue NewOp0 =
5260         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5261     bool IsCTZ =
5262         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5263     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5264     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5265     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5266     return;
5267   }
5268   case ISD::SDIV:
5269   case ISD::UDIV:
5270   case ISD::UREM: {
5271     MVT VT = N->getSimpleValueType(0);
5272     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5273            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5274            "Unexpected custom legalisation");
5275     // Don't promote division/remainder by constant since we should expand those
5276     // to multiply by magic constant.
5277     // FIXME: What if the expansion is disabled for minsize.
5278     if (N->getOperand(1).getOpcode() == ISD::Constant)
5279       return;
5280 
5281     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5282     // the upper 32 bits. For other types we need to sign or zero extend
5283     // based on the opcode.
5284     unsigned ExtOpc = ISD::ANY_EXTEND;
5285     if (VT != MVT::i32)
5286       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5287                                            : ISD::ZERO_EXTEND;
5288 
5289     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5290     break;
5291   }
5292   case ISD::UADDO:
5293   case ISD::USUBO: {
5294     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5295            "Unexpected custom legalisation");
5296     bool IsAdd = N->getOpcode() == ISD::UADDO;
5297     // Create an ADDW or SUBW.
5298     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5299     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5300     SDValue Res =
5301         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5302     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5303                       DAG.getValueType(MVT::i32));
5304 
5305     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5306     // Since the inputs are sign extended from i32, this is equivalent to
5307     // comparing the lower 32 bits.
5308     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5309     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5310                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5311 
5312     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5313     Results.push_back(Overflow);
5314     return;
5315   }
5316   case ISD::UADDSAT:
5317   case ISD::USUBSAT: {
5318     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5319            "Unexpected custom legalisation");
5320     if (Subtarget.hasStdExtZbb()) {
5321       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5322       // sign extend allows overflow of the lower 32 bits to be detected on
5323       // the promoted size.
5324       SDValue LHS =
5325           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5326       SDValue RHS =
5327           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5328       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5329       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5330       return;
5331     }
5332 
5333     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5334     // promotion for UADDO/USUBO.
5335     Results.push_back(expandAddSubSat(N, DAG));
5336     return;
5337   }
5338   case ISD::BITCAST: {
5339     EVT VT = N->getValueType(0);
5340     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5341     SDValue Op0 = N->getOperand(0);
5342     EVT Op0VT = Op0.getValueType();
5343     MVT XLenVT = Subtarget.getXLenVT();
5344     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5345       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5346       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5347     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5348                Subtarget.hasStdExtF()) {
5349       SDValue FPConv =
5350           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5351       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5352     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5353                isTypeLegal(Op0VT)) {
5354       // Custom-legalize bitcasts from fixed-length vector types to illegal
5355       // scalar types in order to improve codegen. Bitcast the vector to a
5356       // one-element vector type whose element type is the same as the result
5357       // type, and extract the first element.
5358       LLVMContext &Context = *DAG.getContext();
5359       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5360       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5361                                     DAG.getConstant(0, DL, XLenVT)));
5362     }
5363     break;
5364   }
5365   case RISCVISD::GREV:
5366   case RISCVISD::GORC: {
5367     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5368            "Unexpected custom legalisation");
5369     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5370     // This is similar to customLegalizeToWOp, except that we pass the second
5371     // operand (a TargetConstant) straight through: it is already of type
5372     // XLenVT.
5373     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5374     SDValue NewOp0 =
5375         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5376     SDValue NewOp1 =
5377         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5378     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5379     // ReplaceNodeResults requires we maintain the same type for the return
5380     // value.
5381     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5382     break;
5383   }
5384   case RISCVISD::SHFL: {
5385     // There is no SHFLIW instruction, but we can just promote the operation.
5386     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5387            "Unexpected custom legalisation");
5388     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5389     SDValue NewOp0 =
5390         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5391     SDValue NewOp1 =
5392         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5393     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5394     // ReplaceNodeResults requires we maintain the same type for the return
5395     // value.
5396     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5397     break;
5398   }
5399   case ISD::BSWAP:
5400   case ISD::BITREVERSE: {
5401     MVT VT = N->getSimpleValueType(0);
5402     MVT XLenVT = Subtarget.getXLenVT();
5403     assert((VT == MVT::i8 || VT == MVT::i16 ||
5404             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5405            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5406     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5407     unsigned Imm = VT.getSizeInBits() - 1;
5408     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5409     if (N->getOpcode() == ISD::BSWAP)
5410       Imm &= ~0x7U;
5411     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5412     SDValue GREVI =
5413         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5414     // ReplaceNodeResults requires we maintain the same type for the return
5415     // value.
5416     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5417     break;
5418   }
5419   case ISD::FSHL:
5420   case ISD::FSHR: {
5421     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5422            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5423     SDValue NewOp0 =
5424         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5425     SDValue NewOp1 =
5426         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5427     SDValue NewOp2 =
5428         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5429     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5430     // Mask the shift amount to 5 bits.
5431     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5432                          DAG.getConstant(0x1f, DL, MVT::i64));
5433     unsigned Opc =
5434         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5435     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5436     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5437     break;
5438   }
5439   case ISD::EXTRACT_VECTOR_ELT: {
5440     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5441     // type is illegal (currently only vXi64 RV32).
5442     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5443     // transferred to the destination register. We issue two of these from the
5444     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5445     // first element.
5446     SDValue Vec = N->getOperand(0);
5447     SDValue Idx = N->getOperand(1);
5448 
5449     // The vector type hasn't been legalized yet so we can't issue target
5450     // specific nodes if it needs legalization.
5451     // FIXME: We would manually legalize if it's important.
5452     if (!isTypeLegal(Vec.getValueType()))
5453       return;
5454 
5455     MVT VecVT = Vec.getSimpleValueType();
5456 
5457     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5458            VecVT.getVectorElementType() == MVT::i64 &&
5459            "Unexpected EXTRACT_VECTOR_ELT legalization");
5460 
5461     // If this is a fixed vector, we need to convert it to a scalable vector.
5462     MVT ContainerVT = VecVT;
5463     if (VecVT.isFixedLengthVector()) {
5464       ContainerVT = getContainerForFixedLengthVector(VecVT);
5465       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5466     }
5467 
5468     MVT XLenVT = Subtarget.getXLenVT();
5469 
5470     // Use a VL of 1 to avoid processing more elements than we need.
5471     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5472     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5473     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5474 
5475     // Unless the index is known to be 0, we must slide the vector down to get
5476     // the desired element into index 0.
5477     if (!isNullConstant(Idx)) {
5478       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5479                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5480     }
5481 
5482     // Extract the lower XLEN bits of the correct vector element.
5483     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5484 
5485     // To extract the upper XLEN bits of the vector element, shift the first
5486     // element right by 32 bits and re-extract the lower XLEN bits.
5487     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5488                                      DAG.getConstant(32, DL, XLenVT), VL);
5489     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5490                                  ThirtyTwoV, Mask, VL);
5491 
5492     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5493 
5494     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5495     break;
5496   }
5497   case ISD::INTRINSIC_WO_CHAIN: {
5498     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5499     switch (IntNo) {
5500     default:
5501       llvm_unreachable(
5502           "Don't know how to custom type legalize this intrinsic!");
5503     case Intrinsic::riscv_orc_b: {
5504       // Lower to the GORCI encoding for orc.b with the operand extended.
5505       SDValue NewOp =
5506           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5507       // If Zbp is enabled, use GORCIW which will sign extend the result.
5508       unsigned Opc =
5509           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5510       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5511                                 DAG.getConstant(7, DL, MVT::i64));
5512       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5513       return;
5514     }
5515     case Intrinsic::riscv_grev:
5516     case Intrinsic::riscv_gorc: {
5517       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5518              "Unexpected custom legalisation");
5519       SDValue NewOp1 =
5520           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5521       SDValue NewOp2 =
5522           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5523       unsigned Opc =
5524           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5525       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5526       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5527       break;
5528     }
5529     case Intrinsic::riscv_shfl:
5530     case Intrinsic::riscv_unshfl: {
5531       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5532              "Unexpected custom legalisation");
5533       SDValue NewOp1 =
5534           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5535       SDValue NewOp2 =
5536           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5537       unsigned Opc =
5538           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5539       if (isa<ConstantSDNode>(N->getOperand(2))) {
5540         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5541                              DAG.getConstant(0xf, DL, MVT::i64));
5542         Opc =
5543             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5544       }
5545       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5546       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5547       break;
5548     }
5549     case Intrinsic::riscv_bcompress:
5550     case Intrinsic::riscv_bdecompress: {
5551       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5552              "Unexpected custom legalisation");
5553       SDValue NewOp1 =
5554           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5555       SDValue NewOp2 =
5556           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5557       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5558                          ? RISCVISD::BCOMPRESSW
5559                          : RISCVISD::BDECOMPRESSW;
5560       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5561       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5562       break;
5563     }
5564     case Intrinsic::riscv_vmv_x_s: {
5565       EVT VT = N->getValueType(0);
5566       MVT XLenVT = Subtarget.getXLenVT();
5567       if (VT.bitsLT(XLenVT)) {
5568         // Simple case just extract using vmv.x.s and truncate.
5569         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5570                                       Subtarget.getXLenVT(), N->getOperand(1));
5571         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5572         return;
5573       }
5574 
5575       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5576              "Unexpected custom legalization");
5577 
5578       // We need to do the move in two steps.
5579       SDValue Vec = N->getOperand(1);
5580       MVT VecVT = Vec.getSimpleValueType();
5581 
5582       // First extract the lower XLEN bits of the element.
5583       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5584 
5585       // To extract the upper XLEN bits of the vector element, shift the first
5586       // element right by 32 bits and re-extract the lower XLEN bits.
5587       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5588       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5589       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5590       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5591                                        DAG.getConstant(32, DL, XLenVT), VL);
5592       SDValue LShr32 =
5593           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5594       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5595 
5596       Results.push_back(
5597           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5598       break;
5599     }
5600     }
5601     break;
5602   }
5603   case ISD::VECREDUCE_ADD:
5604   case ISD::VECREDUCE_AND:
5605   case ISD::VECREDUCE_OR:
5606   case ISD::VECREDUCE_XOR:
5607   case ISD::VECREDUCE_SMAX:
5608   case ISD::VECREDUCE_UMAX:
5609   case ISD::VECREDUCE_SMIN:
5610   case ISD::VECREDUCE_UMIN:
5611     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5612       Results.push_back(V);
5613     break;
5614   case ISD::FLT_ROUNDS_: {
5615     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5616     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5617     Results.push_back(Res.getValue(0));
5618     Results.push_back(Res.getValue(1));
5619     break;
5620   }
5621   }
5622 }
5623 
5624 // A structure to hold one of the bit-manipulation patterns below. Together, a
5625 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
5626 //   (or (and (shl x, 1), 0xAAAAAAAA),
5627 //       (and (srl x, 1), 0x55555555))
5628 struct RISCVBitmanipPat {
5629   SDValue Op;
5630   unsigned ShAmt;
5631   bool IsSHL;
5632 
5633   bool formsPairWith(const RISCVBitmanipPat &Other) const {
5634     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
5635   }
5636 };
5637 
5638 // Matches patterns of the form
5639 //   (and (shl x, C2), (C1 << C2))
5640 //   (and (srl x, C2), C1)
5641 //   (shl (and x, C1), C2)
5642 //   (srl (and x, (C1 << C2)), C2)
5643 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
5644 // The expected masks for each shift amount are specified in BitmanipMasks where
5645 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
5646 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
5647 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
5648 // XLen is 64.
5649 static Optional<RISCVBitmanipPat>
5650 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
5651   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
5652          "Unexpected number of masks");
5653   Optional<uint64_t> Mask;
5654   // Optionally consume a mask around the shift operation.
5655   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
5656     Mask = Op.getConstantOperandVal(1);
5657     Op = Op.getOperand(0);
5658   }
5659   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
5660     return None;
5661   bool IsSHL = Op.getOpcode() == ISD::SHL;
5662 
5663   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5664     return None;
5665   uint64_t ShAmt = Op.getConstantOperandVal(1);
5666 
5667   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5668   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
5669     return None;
5670   // If we don't have enough masks for 64 bit, then we must be trying to
5671   // match SHFL so we're only allowed to shift 1/4 of the width.
5672   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
5673     return None;
5674 
5675   SDValue Src = Op.getOperand(0);
5676 
5677   // The expected mask is shifted left when the AND is found around SHL
5678   // patterns.
5679   //   ((x >> 1) & 0x55555555)
5680   //   ((x << 1) & 0xAAAAAAAA)
5681   bool SHLExpMask = IsSHL;
5682 
5683   if (!Mask) {
5684     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
5685     // the mask is all ones: consume that now.
5686     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
5687       Mask = Src.getConstantOperandVal(1);
5688       Src = Src.getOperand(0);
5689       // The expected mask is now in fact shifted left for SRL, so reverse the
5690       // decision.
5691       //   ((x & 0xAAAAAAAA) >> 1)
5692       //   ((x & 0x55555555) << 1)
5693       SHLExpMask = !SHLExpMask;
5694     } else {
5695       // Use a default shifted mask of all-ones if there's no AND, truncated
5696       // down to the expected width. This simplifies the logic later on.
5697       Mask = maskTrailingOnes<uint64_t>(Width);
5698       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
5699     }
5700   }
5701 
5702   unsigned MaskIdx = Log2_32(ShAmt);
5703   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5704 
5705   if (SHLExpMask)
5706     ExpMask <<= ShAmt;
5707 
5708   if (Mask != ExpMask)
5709     return None;
5710 
5711   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
5712 }
5713 
5714 // Matches any of the following bit-manipulation patterns:
5715 //   (and (shl x, 1), (0x55555555 << 1))
5716 //   (and (srl x, 1), 0x55555555)
5717 //   (shl (and x, 0x55555555), 1)
5718 //   (srl (and x, (0x55555555 << 1)), 1)
5719 // where the shift amount and mask may vary thus:
5720 //   [1]  = 0x55555555 / 0xAAAAAAAA
5721 //   [2]  = 0x33333333 / 0xCCCCCCCC
5722 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
5723 //   [8]  = 0x00FF00FF / 0xFF00FF00
5724 //   [16] = 0x0000FFFF / 0xFFFFFFFF
5725 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
5726 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
5727   // These are the unshifted masks which we use to match bit-manipulation
5728   // patterns. They may be shifted left in certain circumstances.
5729   static const uint64_t BitmanipMasks[] = {
5730       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
5731       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
5732 
5733   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5734 }
5735 
5736 // Match the following pattern as a GREVI(W) operation
5737 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
5738 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
5739                                const RISCVSubtarget &Subtarget) {
5740   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5741   EVT VT = Op.getValueType();
5742 
5743   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5744     auto LHS = matchGREVIPat(Op.getOperand(0));
5745     auto RHS = matchGREVIPat(Op.getOperand(1));
5746     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
5747       SDLoc DL(Op);
5748       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
5749                          DAG.getConstant(LHS->ShAmt, DL, VT));
5750     }
5751   }
5752   return SDValue();
5753 }
5754 
5755 // Matches any the following pattern as a GORCI(W) operation
5756 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
5757 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
5758 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
5759 // Note that with the variant of 3.,
5760 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
5761 // the inner pattern will first be matched as GREVI and then the outer
5762 // pattern will be matched to GORC via the first rule above.
5763 // 4.  (or (rotl/rotr x, bitwidth/2), x)
5764 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
5765                                const RISCVSubtarget &Subtarget) {
5766   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5767   EVT VT = Op.getValueType();
5768 
5769   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5770     SDLoc DL(Op);
5771     SDValue Op0 = Op.getOperand(0);
5772     SDValue Op1 = Op.getOperand(1);
5773 
5774     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
5775       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
5776           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
5777           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
5778         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
5779       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
5780       if ((Reverse.getOpcode() == ISD::ROTL ||
5781            Reverse.getOpcode() == ISD::ROTR) &&
5782           Reverse.getOperand(0) == X &&
5783           isa<ConstantSDNode>(Reverse.getOperand(1))) {
5784         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
5785         if (RotAmt == (VT.getSizeInBits() / 2))
5786           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
5787                              DAG.getConstant(RotAmt, DL, VT));
5788       }
5789       return SDValue();
5790     };
5791 
5792     // Check for either commutable permutation of (or (GREVI x, shamt), x)
5793     if (SDValue V = MatchOROfReverse(Op0, Op1))
5794       return V;
5795     if (SDValue V = MatchOROfReverse(Op1, Op0))
5796       return V;
5797 
5798     // OR is commutable so canonicalize its OR operand to the left
5799     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
5800       std::swap(Op0, Op1);
5801     if (Op0.getOpcode() != ISD::OR)
5802       return SDValue();
5803     SDValue OrOp0 = Op0.getOperand(0);
5804     SDValue OrOp1 = Op0.getOperand(1);
5805     auto LHS = matchGREVIPat(OrOp0);
5806     // OR is commutable so swap the operands and try again: x might have been
5807     // on the left
5808     if (!LHS) {
5809       std::swap(OrOp0, OrOp1);
5810       LHS = matchGREVIPat(OrOp0);
5811     }
5812     auto RHS = matchGREVIPat(Op1);
5813     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
5814       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
5815                          DAG.getConstant(LHS->ShAmt, DL, VT));
5816     }
5817   }
5818   return SDValue();
5819 }
5820 
5821 // Matches any of the following bit-manipulation patterns:
5822 //   (and (shl x, 1), (0x22222222 << 1))
5823 //   (and (srl x, 1), 0x22222222)
5824 //   (shl (and x, 0x22222222), 1)
5825 //   (srl (and x, (0x22222222 << 1)), 1)
5826 // where the shift amount and mask may vary thus:
5827 //   [1]  = 0x22222222 / 0x44444444
5828 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
5829 //   [4]  = 0x00F000F0 / 0x0F000F00
5830 //   [8]  = 0x0000FF00 / 0x00FF0000
5831 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
5832 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
5833   // These are the unshifted masks which we use to match bit-manipulation
5834   // patterns. They may be shifted left in certain circumstances.
5835   static const uint64_t BitmanipMasks[] = {
5836       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
5837       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
5838 
5839   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5840 }
5841 
5842 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
5843 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
5844                                const RISCVSubtarget &Subtarget) {
5845   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5846   EVT VT = Op.getValueType();
5847 
5848   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
5849     return SDValue();
5850 
5851   SDValue Op0 = Op.getOperand(0);
5852   SDValue Op1 = Op.getOperand(1);
5853 
5854   // Or is commutable so canonicalize the second OR to the LHS.
5855   if (Op0.getOpcode() != ISD::OR)
5856     std::swap(Op0, Op1);
5857   if (Op0.getOpcode() != ISD::OR)
5858     return SDValue();
5859 
5860   // We found an inner OR, so our operands are the operands of the inner OR
5861   // and the other operand of the outer OR.
5862   SDValue A = Op0.getOperand(0);
5863   SDValue B = Op0.getOperand(1);
5864   SDValue C = Op1;
5865 
5866   auto Match1 = matchSHFLPat(A);
5867   auto Match2 = matchSHFLPat(B);
5868 
5869   // If neither matched, we failed.
5870   if (!Match1 && !Match2)
5871     return SDValue();
5872 
5873   // We had at least one match. if one failed, try the remaining C operand.
5874   if (!Match1) {
5875     std::swap(A, C);
5876     Match1 = matchSHFLPat(A);
5877     if (!Match1)
5878       return SDValue();
5879   } else if (!Match2) {
5880     std::swap(B, C);
5881     Match2 = matchSHFLPat(B);
5882     if (!Match2)
5883       return SDValue();
5884   }
5885   assert(Match1 && Match2);
5886 
5887   // Make sure our matches pair up.
5888   if (!Match1->formsPairWith(*Match2))
5889     return SDValue();
5890 
5891   // All the remains is to make sure C is an AND with the same input, that masks
5892   // out the bits that are being shuffled.
5893   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
5894       C.getOperand(0) != Match1->Op)
5895     return SDValue();
5896 
5897   uint64_t Mask = C.getConstantOperandVal(1);
5898 
5899   static const uint64_t BitmanipMasks[] = {
5900       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
5901       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
5902   };
5903 
5904   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5905   unsigned MaskIdx = Log2_32(Match1->ShAmt);
5906   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5907 
5908   if (Mask != ExpMask)
5909     return SDValue();
5910 
5911   SDLoc DL(Op);
5912   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
5913                      DAG.getConstant(Match1->ShAmt, DL, VT));
5914 }
5915 
5916 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
5917 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
5918 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
5919 // not undo itself, but they are redundant.
5920 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
5921   SDValue Src = N->getOperand(0);
5922 
5923   if (Src.getOpcode() != N->getOpcode())
5924     return SDValue();
5925 
5926   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
5927       !isa<ConstantSDNode>(Src.getOperand(1)))
5928     return SDValue();
5929 
5930   unsigned ShAmt1 = N->getConstantOperandVal(1);
5931   unsigned ShAmt2 = Src.getConstantOperandVal(1);
5932   Src = Src.getOperand(0);
5933 
5934   unsigned CombinedShAmt;
5935   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
5936     CombinedShAmt = ShAmt1 | ShAmt2;
5937   else
5938     CombinedShAmt = ShAmt1 ^ ShAmt2;
5939 
5940   if (CombinedShAmt == 0)
5941     return Src;
5942 
5943   SDLoc DL(N);
5944   return DAG.getNode(
5945       N->getOpcode(), DL, N->getValueType(0), Src,
5946       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
5947 }
5948 
5949 // Combine a constant select operand into its use:
5950 //
5951 // (and (select cond, -1, c), x)
5952 //   -> (select cond, x, (and x, c))  [AllOnes=1]
5953 // (or  (select cond, 0, c), x)
5954 //   -> (select cond, x, (or x, c))  [AllOnes=0]
5955 // (xor (select cond, 0, c), x)
5956 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
5957 // (add (select cond, 0, c), x)
5958 //   -> (select cond, x, (add x, c))  [AllOnes=0]
5959 // (sub x, (select cond, 0, c))
5960 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
5961 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
5962                                    SelectionDAG &DAG, bool AllOnes) {
5963   EVT VT = N->getValueType(0);
5964 
5965   // Skip vectors.
5966   if (VT.isVector())
5967     return SDValue();
5968 
5969   if ((Slct.getOpcode() != ISD::SELECT &&
5970        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
5971       !Slct.hasOneUse())
5972     return SDValue();
5973 
5974   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
5975     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
5976   };
5977 
5978   bool SwapSelectOps;
5979   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
5980   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
5981   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
5982   SDValue NonConstantVal;
5983   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
5984     SwapSelectOps = false;
5985     NonConstantVal = FalseVal;
5986   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
5987     SwapSelectOps = true;
5988     NonConstantVal = TrueVal;
5989   } else
5990     return SDValue();
5991 
5992   // Slct is now know to be the desired identity constant when CC is true.
5993   TrueVal = OtherOp;
5994   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
5995   // Unless SwapSelectOps says the condition should be false.
5996   if (SwapSelectOps)
5997     std::swap(TrueVal, FalseVal);
5998 
5999   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6000     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6001                        {Slct.getOperand(0), Slct.getOperand(1),
6002                         Slct.getOperand(2), TrueVal, FalseVal});
6003 
6004   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6005                      {Slct.getOperand(0), TrueVal, FalseVal});
6006 }
6007 
6008 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6009 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6010                                               bool AllOnes) {
6011   SDValue N0 = N->getOperand(0);
6012   SDValue N1 = N->getOperand(1);
6013   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6014     return Result;
6015   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6016     return Result;
6017   return SDValue();
6018 }
6019 
6020 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG) {
6021   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6022   //      (select lhs, rhs, cc, x, (add x, y))
6023   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6024 }
6025 
6026 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6027   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6028   //      (select lhs, rhs, cc, x, (sub x, y))
6029   SDValue N0 = N->getOperand(0);
6030   SDValue N1 = N->getOperand(1);
6031   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6032 }
6033 
6034 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6035   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6036   //      (select lhs, rhs, cc, x, (and x, y))
6037   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6038 }
6039 
6040 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6041                                 const RISCVSubtarget &Subtarget) {
6042   if (Subtarget.hasStdExtZbp()) {
6043     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6044       return GREV;
6045     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6046       return GORC;
6047     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6048       return SHFL;
6049   }
6050 
6051   // fold (or (select cond, 0, y), x) ->
6052   //      (select cond, x, (or x, y))
6053   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6054 }
6055 
6056 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6057   // fold (xor (select cond, 0, y), x) ->
6058   //      (select cond, x, (xor x, y))
6059   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6060 }
6061 
6062 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6063 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6064 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6065 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6066 // ADDW/SUBW/MULW.
6067 static SDValue performANY_EXTENDCombine(SDNode *N,
6068                                         TargetLowering::DAGCombinerInfo &DCI,
6069                                         const RISCVSubtarget &Subtarget) {
6070   if (!Subtarget.is64Bit())
6071     return SDValue();
6072 
6073   SelectionDAG &DAG = DCI.DAG;
6074 
6075   SDValue Src = N->getOperand(0);
6076   EVT VT = N->getValueType(0);
6077   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6078     return SDValue();
6079 
6080   // The opcode must be one that can implicitly sign_extend.
6081   // FIXME: Additional opcodes.
6082   switch (Src.getOpcode()) {
6083   default:
6084     return SDValue();
6085   case ISD::MUL:
6086     if (!Subtarget.hasStdExtM())
6087       return SDValue();
6088     LLVM_FALLTHROUGH;
6089   case ISD::ADD:
6090   case ISD::SUB:
6091     break;
6092   }
6093 
6094   // Only handle cases where the result is used by a CopyToReg. That likely
6095   // means the value is a liveout of the basic block. This helps prevent
6096   // infinite combine loops like PR51206.
6097   if (none_of(N->uses(),
6098               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
6099     return SDValue();
6100 
6101   SmallVector<SDNode *, 4> SetCCs;
6102   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
6103                             UE = Src.getNode()->use_end();
6104        UI != UE; ++UI) {
6105     SDNode *User = *UI;
6106     if (User == N)
6107       continue;
6108     if (UI.getUse().getResNo() != Src.getResNo())
6109       continue;
6110     // All i32 setccs are legalized by sign extending operands.
6111     if (User->getOpcode() == ISD::SETCC) {
6112       SetCCs.push_back(User);
6113       continue;
6114     }
6115     // We don't know if we can extend this user.
6116     break;
6117   }
6118 
6119   // If we don't have any SetCCs, this isn't worthwhile.
6120   if (SetCCs.empty())
6121     return SDValue();
6122 
6123   SDLoc DL(N);
6124   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
6125   DCI.CombineTo(N, SExt);
6126 
6127   // Promote all the setccs.
6128   for (SDNode *SetCC : SetCCs) {
6129     SmallVector<SDValue, 4> Ops;
6130 
6131     for (unsigned j = 0; j != 2; ++j) {
6132       SDValue SOp = SetCC->getOperand(j);
6133       if (SOp == Src)
6134         Ops.push_back(SExt);
6135       else
6136         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
6137     }
6138 
6139     Ops.push_back(SetCC->getOperand(2));
6140     DCI.CombineTo(SetCC,
6141                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6142   }
6143   return SDValue(N, 0);
6144 }
6145 
6146 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
6147                                                DAGCombinerInfo &DCI) const {
6148   SelectionDAG &DAG = DCI.DAG;
6149 
6150   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6151   // bits are demanded. N will be added to the Worklist if it was not deleted.
6152   // Caller should return SDValue(N, 0) if this returns true.
6153   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6154     SDValue Op = N->getOperand(OpNo);
6155     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6156     if (!SimplifyDemandedBits(Op, Mask, DCI))
6157       return false;
6158 
6159     if (N->getOpcode() != ISD::DELETED_NODE)
6160       DCI.AddToWorklist(N);
6161     return true;
6162   };
6163 
6164   switch (N->getOpcode()) {
6165   default:
6166     break;
6167   case RISCVISD::SplitF64: {
6168     SDValue Op0 = N->getOperand(0);
6169     // If the input to SplitF64 is just BuildPairF64 then the operation is
6170     // redundant. Instead, use BuildPairF64's operands directly.
6171     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6172       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6173 
6174     SDLoc DL(N);
6175 
6176     // It's cheaper to materialise two 32-bit integers than to load a double
6177     // from the constant pool and transfer it to integer registers through the
6178     // stack.
6179     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6180       APInt V = C->getValueAPF().bitcastToAPInt();
6181       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6182       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6183       return DCI.CombineTo(N, Lo, Hi);
6184     }
6185 
6186     // This is a target-specific version of a DAGCombine performed in
6187     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6188     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6189     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6190     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6191         !Op0.getNode()->hasOneUse())
6192       break;
6193     SDValue NewSplitF64 =
6194         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6195                     Op0.getOperand(0));
6196     SDValue Lo = NewSplitF64.getValue(0);
6197     SDValue Hi = NewSplitF64.getValue(1);
6198     APInt SignBit = APInt::getSignMask(32);
6199     if (Op0.getOpcode() == ISD::FNEG) {
6200       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6201                                   DAG.getConstant(SignBit, DL, MVT::i32));
6202       return DCI.CombineTo(N, Lo, NewHi);
6203     }
6204     assert(Op0.getOpcode() == ISD::FABS);
6205     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6206                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6207     return DCI.CombineTo(N, Lo, NewHi);
6208   }
6209   case RISCVISD::SLLW:
6210   case RISCVISD::SRAW:
6211   case RISCVISD::SRLW:
6212   case RISCVISD::ROLW:
6213   case RISCVISD::RORW: {
6214     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6215     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6216         SimplifyDemandedLowBitsHelper(1, 5))
6217       return SDValue(N, 0);
6218     break;
6219   }
6220   case RISCVISD::CLZW:
6221   case RISCVISD::CTZW: {
6222     // Only the lower 32 bits of the first operand are read
6223     if (SimplifyDemandedLowBitsHelper(0, 32))
6224       return SDValue(N, 0);
6225     break;
6226   }
6227   case RISCVISD::FSL:
6228   case RISCVISD::FSR: {
6229     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6230     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6231     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6232     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6233       return SDValue(N, 0);
6234     break;
6235   }
6236   case RISCVISD::FSLW:
6237   case RISCVISD::FSRW: {
6238     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6239     // read.
6240     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6241         SimplifyDemandedLowBitsHelper(1, 32) ||
6242         SimplifyDemandedLowBitsHelper(2, 6))
6243       return SDValue(N, 0);
6244     break;
6245   }
6246   case RISCVISD::GREV:
6247   case RISCVISD::GORC: {
6248     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6249     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6250     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6251     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6252       return SDValue(N, 0);
6253 
6254     return combineGREVI_GORCI(N, DCI.DAG);
6255   }
6256   case RISCVISD::GREVW:
6257   case RISCVISD::GORCW: {
6258     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6259     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6260         SimplifyDemandedLowBitsHelper(1, 5))
6261       return SDValue(N, 0);
6262 
6263     return combineGREVI_GORCI(N, DCI.DAG);
6264   }
6265   case RISCVISD::SHFL:
6266   case RISCVISD::UNSHFL: {
6267     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6268     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6269     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6270     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6271       return SDValue(N, 0);
6272 
6273     break;
6274   }
6275   case RISCVISD::SHFLW:
6276   case RISCVISD::UNSHFLW: {
6277     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6278     SDValue LHS = N->getOperand(0);
6279     SDValue RHS = N->getOperand(1);
6280     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6281     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6282     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6283         SimplifyDemandedLowBitsHelper(1, 4))
6284       return SDValue(N, 0);
6285 
6286     break;
6287   }
6288   case RISCVISD::BCOMPRESSW:
6289   case RISCVISD::BDECOMPRESSW: {
6290     // Only the lower 32 bits of LHS and RHS are read.
6291     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6292         SimplifyDemandedLowBitsHelper(1, 32))
6293       return SDValue(N, 0);
6294 
6295     break;
6296   }
6297   case RISCVISD::FMV_X_ANYEXTH:
6298   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6299     SDLoc DL(N);
6300     SDValue Op0 = N->getOperand(0);
6301     MVT VT = N->getSimpleValueType(0);
6302     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6303     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6304     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6305     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6306          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6307         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6308          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6309       assert(Op0.getOperand(0).getValueType() == VT &&
6310              "Unexpected value type!");
6311       return Op0.getOperand(0);
6312     }
6313 
6314     // This is a target-specific version of a DAGCombine performed in
6315     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6316     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6317     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6318     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6319         !Op0.getNode()->hasOneUse())
6320       break;
6321     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6322     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6323     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6324     if (Op0.getOpcode() == ISD::FNEG)
6325       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6326                          DAG.getConstant(SignBit, DL, VT));
6327 
6328     assert(Op0.getOpcode() == ISD::FABS);
6329     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6330                        DAG.getConstant(~SignBit, DL, VT));
6331   }
6332   case ISD::ADD:
6333     return performADDCombine(N, DAG);
6334   case ISD::SUB:
6335     return performSUBCombine(N, DAG);
6336   case ISD::AND:
6337     return performANDCombine(N, DAG);
6338   case ISD::OR:
6339     return performORCombine(N, DAG, Subtarget);
6340   case ISD::XOR:
6341     return performXORCombine(N, DAG);
6342   case ISD::ANY_EXTEND:
6343     return performANY_EXTENDCombine(N, DCI, Subtarget);
6344   case ISD::ZERO_EXTEND:
6345     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6346     // type legalization. This is safe because fp_to_uint produces poison if
6347     // it overflows.
6348     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6349         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6350         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6351       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6352                          N->getOperand(0).getOperand(0));
6353     return SDValue();
6354   case RISCVISD::SELECT_CC: {
6355     // Transform
6356     SDValue LHS = N->getOperand(0);
6357     SDValue RHS = N->getOperand(1);
6358     SDValue TrueV = N->getOperand(3);
6359     SDValue FalseV = N->getOperand(4);
6360 
6361     // If the True and False values are the same, we don't need a select_cc.
6362     if (TrueV == FalseV)
6363       return TrueV;
6364 
6365     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6366     if (!ISD::isIntEqualitySetCC(CCVal))
6367       break;
6368 
6369     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6370     //      (select_cc X, Y, lt, trueV, falseV)
6371     // Sometimes the setcc is introduced after select_cc has been formed.
6372     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6373         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6374       // If we're looking for eq 0 instead of ne 0, we need to invert the
6375       // condition.
6376       bool Invert = CCVal == ISD::SETEQ;
6377       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6378       if (Invert)
6379         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6380 
6381       SDLoc DL(N);
6382       RHS = LHS.getOperand(1);
6383       LHS = LHS.getOperand(0);
6384       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6385 
6386       SDValue TargetCC = DAG.getCondCode(CCVal);
6387       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6388                          {LHS, RHS, TargetCC, TrueV, FalseV});
6389     }
6390 
6391     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6392     //      (select_cc X, Y, eq/ne, trueV, falseV)
6393     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6394       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6395                          {LHS.getOperand(0), LHS.getOperand(1),
6396                           N->getOperand(2), TrueV, FalseV});
6397     // (select_cc X, 1, setne, trueV, falseV) ->
6398     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6399     // This can occur when legalizing some floating point comparisons.
6400     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6401     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6402       SDLoc DL(N);
6403       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6404       SDValue TargetCC = DAG.getCondCode(CCVal);
6405       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6406       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
6407                          {LHS, RHS, TargetCC, TrueV, FalseV});
6408     }
6409 
6410     break;
6411   }
6412   case RISCVISD::BR_CC: {
6413     SDValue LHS = N->getOperand(1);
6414     SDValue RHS = N->getOperand(2);
6415     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6416     if (!ISD::isIntEqualitySetCC(CCVal))
6417       break;
6418 
6419     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6420     //      (br_cc X, Y, lt, dest)
6421     // Sometimes the setcc is introduced after br_cc has been formed.
6422     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6423         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6424       // If we're looking for eq 0 instead of ne 0, we need to invert the
6425       // condition.
6426       bool Invert = CCVal == ISD::SETEQ;
6427       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6428       if (Invert)
6429         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6430 
6431       SDLoc DL(N);
6432       RHS = LHS.getOperand(1);
6433       LHS = LHS.getOperand(0);
6434       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6435 
6436       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6437                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
6438                          N->getOperand(4));
6439     }
6440 
6441     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
6442     //      (br_cc X, Y, eq/ne, trueV, falseV)
6443     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6444       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
6445                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
6446                          N->getOperand(3), N->getOperand(4));
6447 
6448     // (br_cc X, 1, setne, br_cc) ->
6449     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
6450     // This can occur when legalizing some floating point comparisons.
6451     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6452     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6453       SDLoc DL(N);
6454       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6455       SDValue TargetCC = DAG.getCondCode(CCVal);
6456       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6457       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6458                          N->getOperand(0), LHS, RHS, TargetCC,
6459                          N->getOperand(4));
6460     }
6461     break;
6462   }
6463   case ISD::FCOPYSIGN: {
6464     EVT VT = N->getValueType(0);
6465     if (!VT.isVector())
6466       break;
6467     // There is a form of VFSGNJ which injects the negated sign of its second
6468     // operand. Try and bubble any FNEG up after the extend/round to produce
6469     // this optimized pattern. Avoid modifying cases where FP_ROUND and
6470     // TRUNC=1.
6471     SDValue In2 = N->getOperand(1);
6472     // Avoid cases where the extend/round has multiple uses, as duplicating
6473     // those is typically more expensive than removing a fneg.
6474     if (!In2.hasOneUse())
6475       break;
6476     if (In2.getOpcode() != ISD::FP_EXTEND &&
6477         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
6478       break;
6479     In2 = In2.getOperand(0);
6480     if (In2.getOpcode() != ISD::FNEG)
6481       break;
6482     SDLoc DL(N);
6483     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
6484     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
6485                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
6486   }
6487   case ISD::MGATHER:
6488   case ISD::MSCATTER:
6489   case ISD::VP_GATHER:
6490   case ISD::VP_SCATTER: {
6491     if (!DCI.isBeforeLegalize())
6492       break;
6493     SDValue Index, ScaleOp;
6494     bool IsIndexScaled = false;
6495     bool IsIndexSigned = false;
6496     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
6497       Index = VPGSN->getIndex();
6498       ScaleOp = VPGSN->getScale();
6499       IsIndexScaled = VPGSN->isIndexScaled();
6500       IsIndexSigned = VPGSN->isIndexSigned();
6501     } else {
6502       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
6503       Index = MGSN->getIndex();
6504       ScaleOp = MGSN->getScale();
6505       IsIndexScaled = MGSN->isIndexScaled();
6506       IsIndexSigned = MGSN->isIndexSigned();
6507     }
6508     EVT IndexVT = Index.getValueType();
6509     MVT XLenVT = Subtarget.getXLenVT();
6510     // RISCV indexed loads only support the "unsigned unscaled" addressing
6511     // mode, so anything else must be manually legalized.
6512     bool NeedsIdxLegalization =
6513         IsIndexScaled ||
6514         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
6515     if (!NeedsIdxLegalization)
6516       break;
6517 
6518     SDLoc DL(N);
6519 
6520     // Any index legalization should first promote to XLenVT, so we don't lose
6521     // bits when scaling. This may create an illegal index type so we let
6522     // LLVM's legalization take care of the splitting.
6523     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
6524     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
6525       IndexVT = IndexVT.changeVectorElementType(XLenVT);
6526       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6527                           DL, IndexVT, Index);
6528     }
6529 
6530     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
6531     if (IsIndexScaled && Scale != 1) {
6532       // Manually scale the indices by the element size.
6533       // TODO: Sanitize the scale operand here?
6534       // TODO: For VP nodes, should we use VP_SHL here?
6535       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
6536       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
6537       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
6538     }
6539 
6540     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
6541     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
6542       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
6543                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
6544                               VPGN->getScale(), VPGN->getMask(),
6545                               VPGN->getVectorLength()},
6546                              VPGN->getMemOperand(), NewIndexTy);
6547     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
6548       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
6549                               {VPSN->getChain(), VPSN->getValue(),
6550                                VPSN->getBasePtr(), Index, VPSN->getScale(),
6551                                VPSN->getMask(), VPSN->getVectorLength()},
6552                               VPSN->getMemOperand(), NewIndexTy);
6553     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
6554       return DAG.getMaskedGather(
6555           N->getVTList(), MGN->getMemoryVT(), DL,
6556           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
6557            MGN->getBasePtr(), Index, MGN->getScale()},
6558           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
6559     const auto *MSN = cast<MaskedScatterSDNode>(N);
6560     return DAG.getMaskedScatter(
6561         N->getVTList(), MSN->getMemoryVT(), DL,
6562         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
6563          Index, MSN->getScale()},
6564         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
6565   }
6566   case RISCVISD::SRA_VL:
6567   case RISCVISD::SRL_VL:
6568   case RISCVISD::SHL_VL: {
6569     SDValue ShAmt = N->getOperand(1);
6570     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6571       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6572       SDLoc DL(N);
6573       SDValue VL = N->getOperand(3);
6574       EVT VT = N->getValueType(0);
6575       ShAmt =
6576           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
6577       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
6578                          N->getOperand(2), N->getOperand(3));
6579     }
6580     break;
6581   }
6582   case ISD::SRA:
6583   case ISD::SRL:
6584   case ISD::SHL: {
6585     SDValue ShAmt = N->getOperand(1);
6586     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6587       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6588       SDLoc DL(N);
6589       EVT VT = N->getValueType(0);
6590       ShAmt =
6591           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
6592       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
6593     }
6594     break;
6595   }
6596   case RISCVISD::MUL_VL: {
6597     // Try to form VWMUL or VWMULU.
6598     // FIXME: Look for splat of extended scalar as well.
6599     // FIXME: Support VWMULSU.
6600     SDValue Op0 = N->getOperand(0);
6601     SDValue Op1 = N->getOperand(1);
6602     bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6603     bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6604     if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode())
6605       return SDValue();
6606 
6607     // Make sure the extends have a single use.
6608     if (!Op0.hasOneUse() || !Op1.hasOneUse())
6609       return SDValue();
6610 
6611     SDValue Mask = N->getOperand(2);
6612     SDValue VL = N->getOperand(3);
6613     if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask ||
6614         Op0.getOperand(2) != VL || Op1.getOperand(2) != VL)
6615       return SDValue();
6616 
6617     Op0 = Op0.getOperand(0);
6618     Op1 = Op1.getOperand(0);
6619 
6620     MVT VT = N->getSimpleValueType(0);
6621     MVT NarrowVT =
6622         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2),
6623                          VT.getVectorElementCount());
6624 
6625     SDLoc DL(N);
6626 
6627     // Re-introduce narrower extends if needed.
6628     unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6629     if (Op0.getValueType() != NarrowVT)
6630       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6631     if (Op1.getValueType() != NarrowVT)
6632       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6633 
6634     unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6635     return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6636   }
6637   }
6638 
6639   return SDValue();
6640 }
6641 
6642 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
6643     const SDNode *N, CombineLevel Level) const {
6644   // The following folds are only desirable if `(OP _, c1 << c2)` can be
6645   // materialised in fewer instructions than `(OP _, c1)`:
6646   //
6647   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
6648   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
6649   SDValue N0 = N->getOperand(0);
6650   EVT Ty = N0.getValueType();
6651   if (Ty.isScalarInteger() &&
6652       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
6653     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6654     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
6655     if (C1 && C2) {
6656       const APInt &C1Int = C1->getAPIntValue();
6657       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
6658 
6659       // We can materialise `c1 << c2` into an add immediate, so it's "free",
6660       // and the combine should happen, to potentially allow further combines
6661       // later.
6662       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
6663           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
6664         return true;
6665 
6666       // We can materialise `c1` in an add immediate, so it's "free", and the
6667       // combine should be prevented.
6668       if (C1Int.getMinSignedBits() <= 64 &&
6669           isLegalAddImmediate(C1Int.getSExtValue()))
6670         return false;
6671 
6672       // Neither constant will fit into an immediate, so find materialisation
6673       // costs.
6674       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
6675                                               Subtarget.getFeatureBits(),
6676                                               /*CompressionCost*/true);
6677       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
6678           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
6679           /*CompressionCost*/true);
6680 
6681       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
6682       // combine should be prevented.
6683       if (C1Cost < ShiftedC1Cost)
6684         return false;
6685     }
6686   }
6687   return true;
6688 }
6689 
6690 bool RISCVTargetLowering::targetShrinkDemandedConstant(
6691     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
6692     TargetLoweringOpt &TLO) const {
6693   // Delay this optimization as late as possible.
6694   if (!TLO.LegalOps)
6695     return false;
6696 
6697   EVT VT = Op.getValueType();
6698   if (VT.isVector())
6699     return false;
6700 
6701   // Only handle AND for now.
6702   if (Op.getOpcode() != ISD::AND)
6703     return false;
6704 
6705   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6706   if (!C)
6707     return false;
6708 
6709   const APInt &Mask = C->getAPIntValue();
6710 
6711   // Clear all non-demanded bits initially.
6712   APInt ShrunkMask = Mask & DemandedBits;
6713 
6714   // Try to make a smaller immediate by setting undemanded bits.
6715 
6716   APInt ExpandedMask = Mask | ~DemandedBits;
6717 
6718   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
6719     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
6720   };
6721   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
6722     if (NewMask == Mask)
6723       return true;
6724     SDLoc DL(Op);
6725     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
6726     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
6727     return TLO.CombineTo(Op, NewOp);
6728   };
6729 
6730   // If the shrunk mask fits in sign extended 12 bits, let the target
6731   // independent code apply it.
6732   if (ShrunkMask.isSignedIntN(12))
6733     return false;
6734 
6735   // Preserve (and X, 0xffff) when zext.h is supported.
6736   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
6737     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
6738     if (IsLegalMask(NewMask))
6739       return UseMask(NewMask);
6740   }
6741 
6742   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
6743   if (VT == MVT::i64) {
6744     APInt NewMask = APInt(64, 0xffffffff);
6745     if (IsLegalMask(NewMask))
6746       return UseMask(NewMask);
6747   }
6748 
6749   // For the remaining optimizations, we need to be able to make a negative
6750   // number through a combination of mask and undemanded bits.
6751   if (!ExpandedMask.isNegative())
6752     return false;
6753 
6754   // What is the fewest number of bits we need to represent the negative number.
6755   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
6756 
6757   // Try to make a 12 bit negative immediate. If that fails try to make a 32
6758   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
6759   APInt NewMask = ShrunkMask;
6760   if (MinSignedBits <= 12)
6761     NewMask.setBitsFrom(11);
6762   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
6763     NewMask.setBitsFrom(31);
6764   else
6765     return false;
6766 
6767   // Sanity check that our new mask is a subset of the demanded mask.
6768   assert(IsLegalMask(NewMask));
6769   return UseMask(NewMask);
6770 }
6771 
6772 static void computeGREV(APInt &Src, unsigned ShAmt) {
6773   ShAmt &= Src.getBitWidth() - 1;
6774   uint64_t x = Src.getZExtValue();
6775   if (ShAmt & 1)
6776     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
6777   if (ShAmt & 2)
6778     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
6779   if (ShAmt & 4)
6780     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
6781   if (ShAmt & 8)
6782     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
6783   if (ShAmt & 16)
6784     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
6785   if (ShAmt & 32)
6786     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
6787   Src = x;
6788 }
6789 
6790 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
6791                                                         KnownBits &Known,
6792                                                         const APInt &DemandedElts,
6793                                                         const SelectionDAG &DAG,
6794                                                         unsigned Depth) const {
6795   unsigned BitWidth = Known.getBitWidth();
6796   unsigned Opc = Op.getOpcode();
6797   assert((Opc >= ISD::BUILTIN_OP_END ||
6798           Opc == ISD::INTRINSIC_WO_CHAIN ||
6799           Opc == ISD::INTRINSIC_W_CHAIN ||
6800           Opc == ISD::INTRINSIC_VOID) &&
6801          "Should use MaskedValueIsZero if you don't know whether Op"
6802          " is a target node!");
6803 
6804   Known.resetAll();
6805   switch (Opc) {
6806   default: break;
6807   case RISCVISD::SELECT_CC: {
6808     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
6809     // If we don't know any bits, early out.
6810     if (Known.isUnknown())
6811       break;
6812     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
6813 
6814     // Only known if known in both the LHS and RHS.
6815     Known = KnownBits::commonBits(Known, Known2);
6816     break;
6817   }
6818   case RISCVISD::REMUW: {
6819     KnownBits Known2;
6820     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6821     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6822     // We only care about the lower 32 bits.
6823     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
6824     // Restore the original width by sign extending.
6825     Known = Known.sext(BitWidth);
6826     break;
6827   }
6828   case RISCVISD::DIVUW: {
6829     KnownBits Known2;
6830     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6831     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6832     // We only care about the lower 32 bits.
6833     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
6834     // Restore the original width by sign extending.
6835     Known = Known.sext(BitWidth);
6836     break;
6837   }
6838   case RISCVISD::CTZW: {
6839     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6840     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
6841     unsigned LowBits = Log2_32(PossibleTZ) + 1;
6842     Known.Zero.setBitsFrom(LowBits);
6843     break;
6844   }
6845   case RISCVISD::CLZW: {
6846     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6847     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
6848     unsigned LowBits = Log2_32(PossibleLZ) + 1;
6849     Known.Zero.setBitsFrom(LowBits);
6850     break;
6851   }
6852   case RISCVISD::GREV:
6853   case RISCVISD::GREVW: {
6854     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
6855       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6856       if (Opc == RISCVISD::GREVW)
6857         Known = Known.trunc(32);
6858       unsigned ShAmt = C->getZExtValue();
6859       computeGREV(Known.Zero, ShAmt);
6860       computeGREV(Known.One, ShAmt);
6861       if (Opc == RISCVISD::GREVW)
6862         Known = Known.sext(BitWidth);
6863     }
6864     break;
6865   }
6866   case RISCVISD::READ_VLENB:
6867     // We assume VLENB is at least 16 bytes.
6868     Known.Zero.setLowBits(4);
6869     // We assume VLENB is no more than 65536 / 8 bytes.
6870     Known.Zero.setBitsFrom(14);
6871     break;
6872   case ISD::INTRINSIC_W_CHAIN: {
6873     unsigned IntNo = Op.getConstantOperandVal(1);
6874     switch (IntNo) {
6875     default:
6876       // We can't do anything for most intrinsics.
6877       break;
6878     case Intrinsic::riscv_vsetvli:
6879     case Intrinsic::riscv_vsetvlimax:
6880       // Assume that VL output is positive and would fit in an int32_t.
6881       // TODO: VLEN might be capped at 16 bits in a future V spec update.
6882       if (BitWidth >= 32)
6883         Known.Zero.setBitsFrom(31);
6884       break;
6885     }
6886     break;
6887   }
6888   }
6889 }
6890 
6891 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
6892     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
6893     unsigned Depth) const {
6894   switch (Op.getOpcode()) {
6895   default:
6896     break;
6897   case RISCVISD::SELECT_CC: {
6898     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
6899     if (Tmp == 1) return 1;  // Early out.
6900     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
6901     return std::min(Tmp, Tmp2);
6902   }
6903   case RISCVISD::SLLW:
6904   case RISCVISD::SRAW:
6905   case RISCVISD::SRLW:
6906   case RISCVISD::DIVW:
6907   case RISCVISD::DIVUW:
6908   case RISCVISD::REMUW:
6909   case RISCVISD::ROLW:
6910   case RISCVISD::RORW:
6911   case RISCVISD::GREVW:
6912   case RISCVISD::GORCW:
6913   case RISCVISD::FSLW:
6914   case RISCVISD::FSRW:
6915   case RISCVISD::SHFLW:
6916   case RISCVISD::UNSHFLW:
6917   case RISCVISD::BCOMPRESSW:
6918   case RISCVISD::BDECOMPRESSW:
6919   case RISCVISD::FCVT_W_RTZ_RV64:
6920   case RISCVISD::FCVT_WU_RTZ_RV64:
6921     // TODO: As the result is sign-extended, this is conservatively correct. A
6922     // more precise answer could be calculated for SRAW depending on known
6923     // bits in the shift amount.
6924     return 33;
6925   case RISCVISD::SHFL:
6926   case RISCVISD::UNSHFL: {
6927     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
6928     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
6929     // will stay within the upper 32 bits. If there were more than 32 sign bits
6930     // before there will be at least 33 sign bits after.
6931     if (Op.getValueType() == MVT::i64 &&
6932         isa<ConstantSDNode>(Op.getOperand(1)) &&
6933         (Op.getConstantOperandVal(1) & 0x10) == 0) {
6934       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
6935       if (Tmp > 32)
6936         return 33;
6937     }
6938     break;
6939   }
6940   case RISCVISD::VMV_X_S:
6941     // The number of sign bits of the scalar result is computed by obtaining the
6942     // element type of the input vector operand, subtracting its width from the
6943     // XLEN, and then adding one (sign bit within the element type). If the
6944     // element type is wider than XLen, the least-significant XLEN bits are
6945     // taken.
6946     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
6947       return 1;
6948     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
6949   }
6950 
6951   return 1;
6952 }
6953 
6954 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
6955                                                   MachineBasicBlock *BB) {
6956   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
6957 
6958   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
6959   // Should the count have wrapped while it was being read, we need to try
6960   // again.
6961   // ...
6962   // read:
6963   // rdcycleh x3 # load high word of cycle
6964   // rdcycle  x2 # load low word of cycle
6965   // rdcycleh x4 # load high word of cycle
6966   // bne x3, x4, read # check if high word reads match, otherwise try again
6967   // ...
6968 
6969   MachineFunction &MF = *BB->getParent();
6970   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6971   MachineFunction::iterator It = ++BB->getIterator();
6972 
6973   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
6974   MF.insert(It, LoopMBB);
6975 
6976   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
6977   MF.insert(It, DoneMBB);
6978 
6979   // Transfer the remainder of BB and its successor edges to DoneMBB.
6980   DoneMBB->splice(DoneMBB->begin(), BB,
6981                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6982   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
6983 
6984   BB->addSuccessor(LoopMBB);
6985 
6986   MachineRegisterInfo &RegInfo = MF.getRegInfo();
6987   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
6988   Register LoReg = MI.getOperand(0).getReg();
6989   Register HiReg = MI.getOperand(1).getReg();
6990   DebugLoc DL = MI.getDebugLoc();
6991 
6992   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
6993   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
6994       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
6995       .addReg(RISCV::X0);
6996   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
6997       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
6998       .addReg(RISCV::X0);
6999   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
7000       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
7001       .addReg(RISCV::X0);
7002 
7003   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
7004       .addReg(HiReg)
7005       .addReg(ReadAgainReg)
7006       .addMBB(LoopMBB);
7007 
7008   LoopMBB->addSuccessor(LoopMBB);
7009   LoopMBB->addSuccessor(DoneMBB);
7010 
7011   MI.eraseFromParent();
7012 
7013   return DoneMBB;
7014 }
7015 
7016 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
7017                                              MachineBasicBlock *BB) {
7018   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
7019 
7020   MachineFunction &MF = *BB->getParent();
7021   DebugLoc DL = MI.getDebugLoc();
7022   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7023   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7024   Register LoReg = MI.getOperand(0).getReg();
7025   Register HiReg = MI.getOperand(1).getReg();
7026   Register SrcReg = MI.getOperand(2).getReg();
7027   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
7028   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7029 
7030   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
7031                           RI);
7032   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7033   MachineMemOperand *MMOLo =
7034       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
7035   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7036       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
7037   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
7038       .addFrameIndex(FI)
7039       .addImm(0)
7040       .addMemOperand(MMOLo);
7041   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
7042       .addFrameIndex(FI)
7043       .addImm(4)
7044       .addMemOperand(MMOHi);
7045   MI.eraseFromParent(); // The pseudo instruction is gone now.
7046   return BB;
7047 }
7048 
7049 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
7050                                                  MachineBasicBlock *BB) {
7051   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
7052          "Unexpected instruction");
7053 
7054   MachineFunction &MF = *BB->getParent();
7055   DebugLoc DL = MI.getDebugLoc();
7056   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
7057   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
7058   Register DstReg = MI.getOperand(0).getReg();
7059   Register LoReg = MI.getOperand(1).getReg();
7060   Register HiReg = MI.getOperand(2).getReg();
7061   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
7062   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
7063 
7064   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
7065   MachineMemOperand *MMOLo =
7066       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
7067   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
7068       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
7069   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7070       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
7071       .addFrameIndex(FI)
7072       .addImm(0)
7073       .addMemOperand(MMOLo);
7074   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
7075       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
7076       .addFrameIndex(FI)
7077       .addImm(4)
7078       .addMemOperand(MMOHi);
7079   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
7080   MI.eraseFromParent(); // The pseudo instruction is gone now.
7081   return BB;
7082 }
7083 
7084 static bool isSelectPseudo(MachineInstr &MI) {
7085   switch (MI.getOpcode()) {
7086   default:
7087     return false;
7088   case RISCV::Select_GPR_Using_CC_GPR:
7089   case RISCV::Select_FPR16_Using_CC_GPR:
7090   case RISCV::Select_FPR32_Using_CC_GPR:
7091   case RISCV::Select_FPR64_Using_CC_GPR:
7092     return true;
7093   }
7094 }
7095 
7096 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
7097                                            MachineBasicBlock *BB,
7098                                            const RISCVSubtarget &Subtarget) {
7099   // To "insert" Select_* instructions, we actually have to insert the triangle
7100   // control-flow pattern.  The incoming instructions know the destination vreg
7101   // to set, the condition code register to branch on, the true/false values to
7102   // select between, and the condcode to use to select the appropriate branch.
7103   //
7104   // We produce the following control flow:
7105   //     HeadMBB
7106   //     |  \
7107   //     |  IfFalseMBB
7108   //     | /
7109   //    TailMBB
7110   //
7111   // When we find a sequence of selects we attempt to optimize their emission
7112   // by sharing the control flow. Currently we only handle cases where we have
7113   // multiple selects with the exact same condition (same LHS, RHS and CC).
7114   // The selects may be interleaved with other instructions if the other
7115   // instructions meet some requirements we deem safe:
7116   // - They are debug instructions. Otherwise,
7117   // - They do not have side-effects, do not access memory and their inputs do
7118   //   not depend on the results of the select pseudo-instructions.
7119   // The TrueV/FalseV operands of the selects cannot depend on the result of
7120   // previous selects in the sequence.
7121   // These conditions could be further relaxed. See the X86 target for a
7122   // related approach and more information.
7123   Register LHS = MI.getOperand(1).getReg();
7124   Register RHS = MI.getOperand(2).getReg();
7125   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
7126 
7127   SmallVector<MachineInstr *, 4> SelectDebugValues;
7128   SmallSet<Register, 4> SelectDests;
7129   SelectDests.insert(MI.getOperand(0).getReg());
7130 
7131   MachineInstr *LastSelectPseudo = &MI;
7132 
7133   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
7134        SequenceMBBI != E; ++SequenceMBBI) {
7135     if (SequenceMBBI->isDebugInstr())
7136       continue;
7137     else if (isSelectPseudo(*SequenceMBBI)) {
7138       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
7139           SequenceMBBI->getOperand(2).getReg() != RHS ||
7140           SequenceMBBI->getOperand(3).getImm() != CC ||
7141           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
7142           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
7143         break;
7144       LastSelectPseudo = &*SequenceMBBI;
7145       SequenceMBBI->collectDebugValues(SelectDebugValues);
7146       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
7147     } else {
7148       if (SequenceMBBI->hasUnmodeledSideEffects() ||
7149           SequenceMBBI->mayLoadOrStore())
7150         break;
7151       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
7152             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
7153           }))
7154         break;
7155     }
7156   }
7157 
7158   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
7159   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7160   DebugLoc DL = MI.getDebugLoc();
7161   MachineFunction::iterator I = ++BB->getIterator();
7162 
7163   MachineBasicBlock *HeadMBB = BB;
7164   MachineFunction *F = BB->getParent();
7165   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
7166   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
7167 
7168   F->insert(I, IfFalseMBB);
7169   F->insert(I, TailMBB);
7170 
7171   // Transfer debug instructions associated with the selects to TailMBB.
7172   for (MachineInstr *DebugInstr : SelectDebugValues) {
7173     TailMBB->push_back(DebugInstr->removeFromParent());
7174   }
7175 
7176   // Move all instructions after the sequence to TailMBB.
7177   TailMBB->splice(TailMBB->end(), HeadMBB,
7178                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
7179   // Update machine-CFG edges by transferring all successors of the current
7180   // block to the new block which will contain the Phi nodes for the selects.
7181   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7182   // Set the successors for HeadMBB.
7183   HeadMBB->addSuccessor(IfFalseMBB);
7184   HeadMBB->addSuccessor(TailMBB);
7185 
7186   // Insert appropriate branch.
7187   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7188     .addReg(LHS)
7189     .addReg(RHS)
7190     .addMBB(TailMBB);
7191 
7192   // IfFalseMBB just falls through to TailMBB.
7193   IfFalseMBB->addSuccessor(TailMBB);
7194 
7195   // Create PHIs for all of the select pseudo-instructions.
7196   auto SelectMBBI = MI.getIterator();
7197   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7198   auto InsertionPoint = TailMBB->begin();
7199   while (SelectMBBI != SelectEnd) {
7200     auto Next = std::next(SelectMBBI);
7201     if (isSelectPseudo(*SelectMBBI)) {
7202       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7203       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7204               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7205           .addReg(SelectMBBI->getOperand(4).getReg())
7206           .addMBB(HeadMBB)
7207           .addReg(SelectMBBI->getOperand(5).getReg())
7208           .addMBB(IfFalseMBB);
7209       SelectMBBI->eraseFromParent();
7210     }
7211     SelectMBBI = Next;
7212   }
7213 
7214   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7215   return TailMBB;
7216 }
7217 
7218 MachineBasicBlock *
7219 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7220                                                  MachineBasicBlock *BB) const {
7221   switch (MI.getOpcode()) {
7222   default:
7223     llvm_unreachable("Unexpected instr type to insert");
7224   case RISCV::ReadCycleWide:
7225     assert(!Subtarget.is64Bit() &&
7226            "ReadCycleWrite is only to be used on riscv32");
7227     return emitReadCycleWidePseudo(MI, BB);
7228   case RISCV::Select_GPR_Using_CC_GPR:
7229   case RISCV::Select_FPR16_Using_CC_GPR:
7230   case RISCV::Select_FPR32_Using_CC_GPR:
7231   case RISCV::Select_FPR64_Using_CC_GPR:
7232     return emitSelectPseudo(MI, BB, Subtarget);
7233   case RISCV::BuildPairF64Pseudo:
7234     return emitBuildPairF64Pseudo(MI, BB);
7235   case RISCV::SplitF64Pseudo:
7236     return emitSplitF64Pseudo(MI, BB);
7237   }
7238 }
7239 
7240 // Calling Convention Implementation.
7241 // The expectations for frontend ABI lowering vary from target to target.
7242 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7243 // details, but this is a longer term goal. For now, we simply try to keep the
7244 // role of the frontend as simple and well-defined as possible. The rules can
7245 // be summarised as:
7246 // * Never split up large scalar arguments. We handle them here.
7247 // * If a hardfloat calling convention is being used, and the struct may be
7248 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7249 // available, then pass as two separate arguments. If either the GPRs or FPRs
7250 // are exhausted, then pass according to the rule below.
7251 // * If a struct could never be passed in registers or directly in a stack
7252 // slot (as it is larger than 2*XLEN and the floating point rules don't
7253 // apply), then pass it using a pointer with the byval attribute.
7254 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7255 // word-sized array or a 2*XLEN scalar (depending on alignment).
7256 // * The frontend can determine whether a struct is returned by reference or
7257 // not based on its size and fields. If it will be returned by reference, the
7258 // frontend must modify the prototype so a pointer with the sret annotation is
7259 // passed as the first argument. This is not necessary for large scalar
7260 // returns.
7261 // * Struct return values and varargs should be coerced to structs containing
7262 // register-size fields in the same situations they would be for fixed
7263 // arguments.
7264 
7265 static const MCPhysReg ArgGPRs[] = {
7266   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7267   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7268 };
7269 static const MCPhysReg ArgFPR16s[] = {
7270   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7271   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7272 };
7273 static const MCPhysReg ArgFPR32s[] = {
7274   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7275   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7276 };
7277 static const MCPhysReg ArgFPR64s[] = {
7278   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7279   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7280 };
7281 // This is an interim calling convention and it may be changed in the future.
7282 static const MCPhysReg ArgVRs[] = {
7283     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7284     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7285     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7286 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7287                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7288                                      RISCV::V20M2, RISCV::V22M2};
7289 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7290                                      RISCV::V20M4};
7291 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7292 
7293 // Pass a 2*XLEN argument that has been split into two XLEN values through
7294 // registers or the stack as necessary.
7295 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7296                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7297                                 MVT ValVT2, MVT LocVT2,
7298                                 ISD::ArgFlagsTy ArgFlags2) {
7299   unsigned XLenInBytes = XLen / 8;
7300   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7301     // At least one half can be passed via register.
7302     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7303                                      VA1.getLocVT(), CCValAssign::Full));
7304   } else {
7305     // Both halves must be passed on the stack, with proper alignment.
7306     Align StackAlign =
7307         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7308     State.addLoc(
7309         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7310                             State.AllocateStack(XLenInBytes, StackAlign),
7311                             VA1.getLocVT(), CCValAssign::Full));
7312     State.addLoc(CCValAssign::getMem(
7313         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7314         LocVT2, CCValAssign::Full));
7315     return false;
7316   }
7317 
7318   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7319     // The second half can also be passed via register.
7320     State.addLoc(
7321         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7322   } else {
7323     // The second half is passed via the stack, without additional alignment.
7324     State.addLoc(CCValAssign::getMem(
7325         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7326         LocVT2, CCValAssign::Full));
7327   }
7328 
7329   return false;
7330 }
7331 
7332 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7333                                Optional<unsigned> FirstMaskArgument,
7334                                CCState &State, const RISCVTargetLowering &TLI) {
7335   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7336   if (RC == &RISCV::VRRegClass) {
7337     // Assign the first mask argument to V0.
7338     // This is an interim calling convention and it may be changed in the
7339     // future.
7340     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7341       return State.AllocateReg(RISCV::V0);
7342     return State.AllocateReg(ArgVRs);
7343   }
7344   if (RC == &RISCV::VRM2RegClass)
7345     return State.AllocateReg(ArgVRM2s);
7346   if (RC == &RISCV::VRM4RegClass)
7347     return State.AllocateReg(ArgVRM4s);
7348   if (RC == &RISCV::VRM8RegClass)
7349     return State.AllocateReg(ArgVRM8s);
7350   llvm_unreachable("Unhandled register class for ValueType");
7351 }
7352 
7353 // Implements the RISC-V calling convention. Returns true upon failure.
7354 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7355                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7356                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7357                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7358                      Optional<unsigned> FirstMaskArgument) {
7359   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7360   assert(XLen == 32 || XLen == 64);
7361   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7362 
7363   // Any return value split in to more than two values can't be returned
7364   // directly. Vectors are returned via the available vector registers.
7365   if (!LocVT.isVector() && IsRet && ValNo > 1)
7366     return true;
7367 
7368   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7369   // variadic argument, or if no F16/F32 argument registers are available.
7370   bool UseGPRForF16_F32 = true;
7371   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7372   // variadic argument, or if no F64 argument registers are available.
7373   bool UseGPRForF64 = true;
7374 
7375   switch (ABI) {
7376   default:
7377     llvm_unreachable("Unexpected ABI");
7378   case RISCVABI::ABI_ILP32:
7379   case RISCVABI::ABI_LP64:
7380     break;
7381   case RISCVABI::ABI_ILP32F:
7382   case RISCVABI::ABI_LP64F:
7383     UseGPRForF16_F32 = !IsFixed;
7384     break;
7385   case RISCVABI::ABI_ILP32D:
7386   case RISCVABI::ABI_LP64D:
7387     UseGPRForF16_F32 = !IsFixed;
7388     UseGPRForF64 = !IsFixed;
7389     break;
7390   }
7391 
7392   // FPR16, FPR32, and FPR64 alias each other.
7393   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7394     UseGPRForF16_F32 = true;
7395     UseGPRForF64 = true;
7396   }
7397 
7398   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7399   // similar local variables rather than directly checking against the target
7400   // ABI.
7401 
7402   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7403     LocVT = XLenVT;
7404     LocInfo = CCValAssign::BCvt;
7405   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7406     LocVT = MVT::i64;
7407     LocInfo = CCValAssign::BCvt;
7408   }
7409 
7410   // If this is a variadic argument, the RISC-V calling convention requires
7411   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7412   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7413   // be used regardless of whether the original argument was split during
7414   // legalisation or not. The argument will not be passed by registers if the
7415   // original type is larger than 2*XLEN, so the register alignment rule does
7416   // not apply.
7417   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7418   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7419       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7420     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7421     // Skip 'odd' register if necessary.
7422     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7423       State.AllocateReg(ArgGPRs);
7424   }
7425 
7426   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7427   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7428       State.getPendingArgFlags();
7429 
7430   assert(PendingLocs.size() == PendingArgFlags.size() &&
7431          "PendingLocs and PendingArgFlags out of sync");
7432 
7433   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7434   // registers are exhausted.
7435   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
7436     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
7437            "Can't lower f64 if it is split");
7438     // Depending on available argument GPRS, f64 may be passed in a pair of
7439     // GPRs, split between a GPR and the stack, or passed completely on the
7440     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
7441     // cases.
7442     Register Reg = State.AllocateReg(ArgGPRs);
7443     LocVT = MVT::i32;
7444     if (!Reg) {
7445       unsigned StackOffset = State.AllocateStack(8, Align(8));
7446       State.addLoc(
7447           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7448       return false;
7449     }
7450     if (!State.AllocateReg(ArgGPRs))
7451       State.AllocateStack(4, Align(4));
7452     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7453     return false;
7454   }
7455 
7456   // Fixed-length vectors are located in the corresponding scalable-vector
7457   // container types.
7458   if (ValVT.isFixedLengthVector())
7459     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7460 
7461   // Split arguments might be passed indirectly, so keep track of the pending
7462   // values. Split vectors are passed via a mix of registers and indirectly, so
7463   // treat them as we would any other argument.
7464   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
7465     LocVT = XLenVT;
7466     LocInfo = CCValAssign::Indirect;
7467     PendingLocs.push_back(
7468         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
7469     PendingArgFlags.push_back(ArgFlags);
7470     if (!ArgFlags.isSplitEnd()) {
7471       return false;
7472     }
7473   }
7474 
7475   // If the split argument only had two elements, it should be passed directly
7476   // in registers or on the stack.
7477   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
7478       PendingLocs.size() <= 2) {
7479     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
7480     // Apply the normal calling convention rules to the first half of the
7481     // split argument.
7482     CCValAssign VA = PendingLocs[0];
7483     ISD::ArgFlagsTy AF = PendingArgFlags[0];
7484     PendingLocs.clear();
7485     PendingArgFlags.clear();
7486     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
7487                                ArgFlags);
7488   }
7489 
7490   // Allocate to a register if possible, or else a stack slot.
7491   Register Reg;
7492   unsigned StoreSizeBytes = XLen / 8;
7493   Align StackAlign = Align(XLen / 8);
7494 
7495   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
7496     Reg = State.AllocateReg(ArgFPR16s);
7497   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
7498     Reg = State.AllocateReg(ArgFPR32s);
7499   else if (ValVT == MVT::f64 && !UseGPRForF64)
7500     Reg = State.AllocateReg(ArgFPR64s);
7501   else if (ValVT.isVector()) {
7502     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
7503     if (!Reg) {
7504       // For return values, the vector must be passed fully via registers or
7505       // via the stack.
7506       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
7507       // but we're using all of them.
7508       if (IsRet)
7509         return true;
7510       // Try using a GPR to pass the address
7511       if ((Reg = State.AllocateReg(ArgGPRs))) {
7512         LocVT = XLenVT;
7513         LocInfo = CCValAssign::Indirect;
7514       } else if (ValVT.isScalableVector()) {
7515         report_fatal_error("Unable to pass scalable vector types on the stack");
7516       } else {
7517         // Pass fixed-length vectors on the stack.
7518         LocVT = ValVT;
7519         StoreSizeBytes = ValVT.getStoreSize();
7520         // Align vectors to their element sizes, being careful for vXi1
7521         // vectors.
7522         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7523       }
7524     }
7525   } else {
7526     Reg = State.AllocateReg(ArgGPRs);
7527   }
7528 
7529   unsigned StackOffset =
7530       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
7531 
7532   // If we reach this point and PendingLocs is non-empty, we must be at the
7533   // end of a split argument that must be passed indirectly.
7534   if (!PendingLocs.empty()) {
7535     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
7536     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
7537 
7538     for (auto &It : PendingLocs) {
7539       if (Reg)
7540         It.convertToReg(Reg);
7541       else
7542         It.convertToMem(StackOffset);
7543       State.addLoc(It);
7544     }
7545     PendingLocs.clear();
7546     PendingArgFlags.clear();
7547     return false;
7548   }
7549 
7550   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
7551           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
7552          "Expected an XLenVT or vector types at this stage");
7553 
7554   if (Reg) {
7555     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7556     return false;
7557   }
7558 
7559   // When a floating-point value is passed on the stack, no bit-conversion is
7560   // needed.
7561   if (ValVT.isFloatingPoint()) {
7562     LocVT = ValVT;
7563     LocInfo = CCValAssign::Full;
7564   }
7565   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7566   return false;
7567 }
7568 
7569 template <typename ArgTy>
7570 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
7571   for (const auto &ArgIdx : enumerate(Args)) {
7572     MVT ArgVT = ArgIdx.value().VT;
7573     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
7574       return ArgIdx.index();
7575   }
7576   return None;
7577 }
7578 
7579 void RISCVTargetLowering::analyzeInputArgs(
7580     MachineFunction &MF, CCState &CCInfo,
7581     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
7582     RISCVCCAssignFn Fn) const {
7583   unsigned NumArgs = Ins.size();
7584   FunctionType *FType = MF.getFunction().getFunctionType();
7585 
7586   Optional<unsigned> FirstMaskArgument;
7587   if (Subtarget.hasStdExtV())
7588     FirstMaskArgument = preAssignMask(Ins);
7589 
7590   for (unsigned i = 0; i != NumArgs; ++i) {
7591     MVT ArgVT = Ins[i].VT;
7592     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
7593 
7594     Type *ArgTy = nullptr;
7595     if (IsRet)
7596       ArgTy = FType->getReturnType();
7597     else if (Ins[i].isOrigArg())
7598       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
7599 
7600     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7601     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7602            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
7603            FirstMaskArgument)) {
7604       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
7605                         << EVT(ArgVT).getEVTString() << '\n');
7606       llvm_unreachable(nullptr);
7607     }
7608   }
7609 }
7610 
7611 void RISCVTargetLowering::analyzeOutputArgs(
7612     MachineFunction &MF, CCState &CCInfo,
7613     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
7614     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
7615   unsigned NumArgs = Outs.size();
7616 
7617   Optional<unsigned> FirstMaskArgument;
7618   if (Subtarget.hasStdExtV())
7619     FirstMaskArgument = preAssignMask(Outs);
7620 
7621   for (unsigned i = 0; i != NumArgs; i++) {
7622     MVT ArgVT = Outs[i].VT;
7623     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
7624     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
7625 
7626     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7627     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7628            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
7629            FirstMaskArgument)) {
7630       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
7631                         << EVT(ArgVT).getEVTString() << "\n");
7632       llvm_unreachable(nullptr);
7633     }
7634   }
7635 }
7636 
7637 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
7638 // values.
7639 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
7640                                    const CCValAssign &VA, const SDLoc &DL,
7641                                    const RISCVSubtarget &Subtarget) {
7642   switch (VA.getLocInfo()) {
7643   default:
7644     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7645   case CCValAssign::Full:
7646     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
7647       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
7648     break;
7649   case CCValAssign::BCvt:
7650     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7651       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
7652     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7653       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
7654     else
7655       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
7656     break;
7657   }
7658   return Val;
7659 }
7660 
7661 // The caller is responsible for loading the full value if the argument is
7662 // passed with CCValAssign::Indirect.
7663 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
7664                                 const CCValAssign &VA, const SDLoc &DL,
7665                                 const RISCVTargetLowering &TLI) {
7666   MachineFunction &MF = DAG.getMachineFunction();
7667   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7668   EVT LocVT = VA.getLocVT();
7669   SDValue Val;
7670   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
7671   Register VReg = RegInfo.createVirtualRegister(RC);
7672   RegInfo.addLiveIn(VA.getLocReg(), VReg);
7673   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
7674 
7675   if (VA.getLocInfo() == CCValAssign::Indirect)
7676     return Val;
7677 
7678   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
7679 }
7680 
7681 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
7682                                    const CCValAssign &VA, const SDLoc &DL,
7683                                    const RISCVSubtarget &Subtarget) {
7684   EVT LocVT = VA.getLocVT();
7685 
7686   switch (VA.getLocInfo()) {
7687   default:
7688     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7689   case CCValAssign::Full:
7690     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
7691       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
7692     break;
7693   case CCValAssign::BCvt:
7694     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7695       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
7696     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7697       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
7698     else
7699       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
7700     break;
7701   }
7702   return Val;
7703 }
7704 
7705 // The caller is responsible for loading the full value if the argument is
7706 // passed with CCValAssign::Indirect.
7707 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
7708                                 const CCValAssign &VA, const SDLoc &DL) {
7709   MachineFunction &MF = DAG.getMachineFunction();
7710   MachineFrameInfo &MFI = MF.getFrameInfo();
7711   EVT LocVT = VA.getLocVT();
7712   EVT ValVT = VA.getValVT();
7713   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
7714   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
7715                                  /*Immutable=*/true);
7716   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7717   SDValue Val;
7718 
7719   ISD::LoadExtType ExtType;
7720   switch (VA.getLocInfo()) {
7721   default:
7722     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7723   case CCValAssign::Full:
7724   case CCValAssign::Indirect:
7725   case CCValAssign::BCvt:
7726     ExtType = ISD::NON_EXTLOAD;
7727     break;
7728   }
7729   Val = DAG.getExtLoad(
7730       ExtType, DL, LocVT, Chain, FIN,
7731       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
7732   return Val;
7733 }
7734 
7735 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
7736                                        const CCValAssign &VA, const SDLoc &DL) {
7737   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
7738          "Unexpected VA");
7739   MachineFunction &MF = DAG.getMachineFunction();
7740   MachineFrameInfo &MFI = MF.getFrameInfo();
7741   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7742 
7743   if (VA.isMemLoc()) {
7744     // f64 is passed on the stack.
7745     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
7746     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
7747     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
7748                        MachinePointerInfo::getFixedStack(MF, FI));
7749   }
7750 
7751   assert(VA.isRegLoc() && "Expected register VA assignment");
7752 
7753   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7754   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
7755   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
7756   SDValue Hi;
7757   if (VA.getLocReg() == RISCV::X17) {
7758     // Second half of f64 is passed on the stack.
7759     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
7760     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
7761     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
7762                      MachinePointerInfo::getFixedStack(MF, FI));
7763   } else {
7764     // Second half of f64 is passed in another GPR.
7765     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7766     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
7767     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
7768   }
7769   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
7770 }
7771 
7772 // FastCC has less than 1% performance improvement for some particular
7773 // benchmark. But theoretically, it may has benenfit for some cases.
7774 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
7775                             unsigned ValNo, MVT ValVT, MVT LocVT,
7776                             CCValAssign::LocInfo LocInfo,
7777                             ISD::ArgFlagsTy ArgFlags, CCState &State,
7778                             bool IsFixed, bool IsRet, Type *OrigTy,
7779                             const RISCVTargetLowering &TLI,
7780                             Optional<unsigned> FirstMaskArgument) {
7781 
7782   // X5 and X6 might be used for save-restore libcall.
7783   static const MCPhysReg GPRList[] = {
7784       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
7785       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
7786       RISCV::X29, RISCV::X30, RISCV::X31};
7787 
7788   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
7789     if (unsigned Reg = State.AllocateReg(GPRList)) {
7790       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7791       return false;
7792     }
7793   }
7794 
7795   if (LocVT == MVT::f16) {
7796     static const MCPhysReg FPR16List[] = {
7797         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
7798         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
7799         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
7800         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
7801     if (unsigned Reg = State.AllocateReg(FPR16List)) {
7802       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7803       return false;
7804     }
7805   }
7806 
7807   if (LocVT == MVT::f32) {
7808     static const MCPhysReg FPR32List[] = {
7809         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
7810         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
7811         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
7812         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
7813     if (unsigned Reg = State.AllocateReg(FPR32List)) {
7814       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7815       return false;
7816     }
7817   }
7818 
7819   if (LocVT == MVT::f64) {
7820     static const MCPhysReg FPR64List[] = {
7821         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
7822         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
7823         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
7824         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
7825     if (unsigned Reg = State.AllocateReg(FPR64List)) {
7826       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7827       return false;
7828     }
7829   }
7830 
7831   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
7832     unsigned Offset4 = State.AllocateStack(4, Align(4));
7833     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
7834     return false;
7835   }
7836 
7837   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
7838     unsigned Offset5 = State.AllocateStack(8, Align(8));
7839     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
7840     return false;
7841   }
7842 
7843   if (LocVT.isVector()) {
7844     if (unsigned Reg =
7845             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
7846       // Fixed-length vectors are located in the corresponding scalable-vector
7847       // container types.
7848       if (ValVT.isFixedLengthVector())
7849         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7850       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7851     } else {
7852       // Try and pass the address via a "fast" GPR.
7853       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
7854         LocInfo = CCValAssign::Indirect;
7855         LocVT = TLI.getSubtarget().getXLenVT();
7856         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
7857       } else if (ValVT.isFixedLengthVector()) {
7858         auto StackAlign =
7859             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7860         unsigned StackOffset =
7861             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
7862         State.addLoc(
7863             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7864       } else {
7865         // Can't pass scalable vectors on the stack.
7866         return true;
7867       }
7868     }
7869 
7870     return false;
7871   }
7872 
7873   return true; // CC didn't match.
7874 }
7875 
7876 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
7877                          CCValAssign::LocInfo LocInfo,
7878                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
7879 
7880   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
7881     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
7882     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
7883     static const MCPhysReg GPRList[] = {
7884         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
7885         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
7886     if (unsigned Reg = State.AllocateReg(GPRList)) {
7887       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7888       return false;
7889     }
7890   }
7891 
7892   if (LocVT == MVT::f32) {
7893     // Pass in STG registers: F1, ..., F6
7894     //                        fs0 ... fs5
7895     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
7896                                           RISCV::F18_F, RISCV::F19_F,
7897                                           RISCV::F20_F, RISCV::F21_F};
7898     if (unsigned Reg = State.AllocateReg(FPR32List)) {
7899       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7900       return false;
7901     }
7902   }
7903 
7904   if (LocVT == MVT::f64) {
7905     // Pass in STG registers: D1, ..., D6
7906     //                        fs6 ... fs11
7907     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
7908                                           RISCV::F24_D, RISCV::F25_D,
7909                                           RISCV::F26_D, RISCV::F27_D};
7910     if (unsigned Reg = State.AllocateReg(FPR64List)) {
7911       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7912       return false;
7913     }
7914   }
7915 
7916   report_fatal_error("No registers left in GHC calling convention");
7917   return true;
7918 }
7919 
7920 // Transform physical registers into virtual registers.
7921 SDValue RISCVTargetLowering::LowerFormalArguments(
7922     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
7923     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
7924     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7925 
7926   MachineFunction &MF = DAG.getMachineFunction();
7927 
7928   switch (CallConv) {
7929   default:
7930     report_fatal_error("Unsupported calling convention");
7931   case CallingConv::C:
7932   case CallingConv::Fast:
7933     break;
7934   case CallingConv::GHC:
7935     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
7936         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
7937       report_fatal_error(
7938         "GHC calling convention requires the F and D instruction set extensions");
7939   }
7940 
7941   const Function &Func = MF.getFunction();
7942   if (Func.hasFnAttribute("interrupt")) {
7943     if (!Func.arg_empty())
7944       report_fatal_error(
7945         "Functions with the interrupt attribute cannot have arguments!");
7946 
7947     StringRef Kind =
7948       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
7949 
7950     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
7951       report_fatal_error(
7952         "Function interrupt attribute argument not supported!");
7953   }
7954 
7955   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7956   MVT XLenVT = Subtarget.getXLenVT();
7957   unsigned XLenInBytes = Subtarget.getXLen() / 8;
7958   // Used with vargs to acumulate store chains.
7959   std::vector<SDValue> OutChains;
7960 
7961   // Assign locations to all of the incoming arguments.
7962   SmallVector<CCValAssign, 16> ArgLocs;
7963   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
7964 
7965   if (CallConv == CallingConv::GHC)
7966     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
7967   else
7968     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
7969                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
7970                                                    : CC_RISCV);
7971 
7972   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
7973     CCValAssign &VA = ArgLocs[i];
7974     SDValue ArgValue;
7975     // Passing f64 on RV32D with a soft float ABI must be handled as a special
7976     // case.
7977     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
7978       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
7979     else if (VA.isRegLoc())
7980       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
7981     else
7982       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
7983 
7984     if (VA.getLocInfo() == CCValAssign::Indirect) {
7985       // If the original argument was split and passed by reference (e.g. i128
7986       // on RV32), we need to load all parts of it here (using the same
7987       // address). Vectors may be partly split to registers and partly to the
7988       // stack, in which case the base address is partly offset and subsequent
7989       // stores are relative to that.
7990       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
7991                                    MachinePointerInfo()));
7992       unsigned ArgIndex = Ins[i].OrigArgIndex;
7993       unsigned ArgPartOffset = Ins[i].PartOffset;
7994       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
7995       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
7996         CCValAssign &PartVA = ArgLocs[i + 1];
7997         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
7998         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
7999         if (PartVA.getValVT().isScalableVector())
8000           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8001         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
8002         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
8003                                      MachinePointerInfo()));
8004         ++i;
8005       }
8006       continue;
8007     }
8008     InVals.push_back(ArgValue);
8009   }
8010 
8011   if (IsVarArg) {
8012     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
8013     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
8014     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
8015     MachineFrameInfo &MFI = MF.getFrameInfo();
8016     MachineRegisterInfo &RegInfo = MF.getRegInfo();
8017     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
8018 
8019     // Offset of the first variable argument from stack pointer, and size of
8020     // the vararg save area. For now, the varargs save area is either zero or
8021     // large enough to hold a0-a7.
8022     int VaArgOffset, VarArgsSaveSize;
8023 
8024     // If all registers are allocated, then all varargs must be passed on the
8025     // stack and we don't need to save any argregs.
8026     if (ArgRegs.size() == Idx) {
8027       VaArgOffset = CCInfo.getNextStackOffset();
8028       VarArgsSaveSize = 0;
8029     } else {
8030       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
8031       VaArgOffset = -VarArgsSaveSize;
8032     }
8033 
8034     // Record the frame index of the first variable argument
8035     // which is a value necessary to VASTART.
8036     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8037     RVFI->setVarArgsFrameIndex(FI);
8038 
8039     // If saving an odd number of registers then create an extra stack slot to
8040     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
8041     // offsets to even-numbered registered remain 2*XLEN-aligned.
8042     if (Idx % 2) {
8043       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
8044       VarArgsSaveSize += XLenInBytes;
8045     }
8046 
8047     // Copy the integer registers that may have been used for passing varargs
8048     // to the vararg save area.
8049     for (unsigned I = Idx; I < ArgRegs.size();
8050          ++I, VaArgOffset += XLenInBytes) {
8051       const Register Reg = RegInfo.createVirtualRegister(RC);
8052       RegInfo.addLiveIn(ArgRegs[I], Reg);
8053       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
8054       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
8055       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8056       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
8057                                    MachinePointerInfo::getFixedStack(MF, FI));
8058       cast<StoreSDNode>(Store.getNode())
8059           ->getMemOperand()
8060           ->setValue((Value *)nullptr);
8061       OutChains.push_back(Store);
8062     }
8063     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
8064   }
8065 
8066   // All stores are grouped in one node to allow the matching between
8067   // the size of Ins and InVals. This only happens for vararg functions.
8068   if (!OutChains.empty()) {
8069     OutChains.push_back(Chain);
8070     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
8071   }
8072 
8073   return Chain;
8074 }
8075 
8076 /// isEligibleForTailCallOptimization - Check whether the call is eligible
8077 /// for tail call optimization.
8078 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
8079 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
8080     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
8081     const SmallVector<CCValAssign, 16> &ArgLocs) const {
8082 
8083   auto &Callee = CLI.Callee;
8084   auto CalleeCC = CLI.CallConv;
8085   auto &Outs = CLI.Outs;
8086   auto &Caller = MF.getFunction();
8087   auto CallerCC = Caller.getCallingConv();
8088 
8089   // Exception-handling functions need a special set of instructions to
8090   // indicate a return to the hardware. Tail-calling another function would
8091   // probably break this.
8092   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
8093   // should be expanded as new function attributes are introduced.
8094   if (Caller.hasFnAttribute("interrupt"))
8095     return false;
8096 
8097   // Do not tail call opt if the stack is used to pass parameters.
8098   if (CCInfo.getNextStackOffset() != 0)
8099     return false;
8100 
8101   // Do not tail call opt if any parameters need to be passed indirectly.
8102   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
8103   // passed indirectly. So the address of the value will be passed in a
8104   // register, or if not available, then the address is put on the stack. In
8105   // order to pass indirectly, space on the stack often needs to be allocated
8106   // in order to store the value. In this case the CCInfo.getNextStackOffset()
8107   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
8108   // are passed CCValAssign::Indirect.
8109   for (auto &VA : ArgLocs)
8110     if (VA.getLocInfo() == CCValAssign::Indirect)
8111       return false;
8112 
8113   // Do not tail call opt if either caller or callee uses struct return
8114   // semantics.
8115   auto IsCallerStructRet = Caller.hasStructRetAttr();
8116   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
8117   if (IsCallerStructRet || IsCalleeStructRet)
8118     return false;
8119 
8120   // Externally-defined functions with weak linkage should not be
8121   // tail-called. The behaviour of branch instructions in this situation (as
8122   // used for tail calls) is implementation-defined, so we cannot rely on the
8123   // linker replacing the tail call with a return.
8124   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
8125     const GlobalValue *GV = G->getGlobal();
8126     if (GV->hasExternalWeakLinkage())
8127       return false;
8128   }
8129 
8130   // The callee has to preserve all registers the caller needs to preserve.
8131   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
8132   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
8133   if (CalleeCC != CallerCC) {
8134     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
8135     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
8136       return false;
8137   }
8138 
8139   // Byval parameters hand the function a pointer directly into the stack area
8140   // we want to reuse during a tail call. Working around this *is* possible
8141   // but less efficient and uglier in LowerCall.
8142   for (auto &Arg : Outs)
8143     if (Arg.Flags.isByVal())
8144       return false;
8145 
8146   return true;
8147 }
8148 
8149 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
8150   return DAG.getDataLayout().getPrefTypeAlign(
8151       VT.getTypeForEVT(*DAG.getContext()));
8152 }
8153 
8154 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
8155 // and output parameter nodes.
8156 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
8157                                        SmallVectorImpl<SDValue> &InVals) const {
8158   SelectionDAG &DAG = CLI.DAG;
8159   SDLoc &DL = CLI.DL;
8160   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
8161   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
8162   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
8163   SDValue Chain = CLI.Chain;
8164   SDValue Callee = CLI.Callee;
8165   bool &IsTailCall = CLI.IsTailCall;
8166   CallingConv::ID CallConv = CLI.CallConv;
8167   bool IsVarArg = CLI.IsVarArg;
8168   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8169   MVT XLenVT = Subtarget.getXLenVT();
8170 
8171   MachineFunction &MF = DAG.getMachineFunction();
8172 
8173   // Analyze the operands of the call, assigning locations to each operand.
8174   SmallVector<CCValAssign, 16> ArgLocs;
8175   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
8176 
8177   if (CallConv == CallingConv::GHC)
8178     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
8179   else
8180     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8181                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8182                                                     : CC_RISCV);
8183 
8184   // Check if it's really possible to do a tail call.
8185   if (IsTailCall)
8186     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8187 
8188   if (IsTailCall)
8189     ++NumTailCalls;
8190   else if (CLI.CB && CLI.CB->isMustTailCall())
8191     report_fatal_error("failed to perform tail call elimination on a call "
8192                        "site marked musttail");
8193 
8194   // Get a count of how many bytes are to be pushed on the stack.
8195   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8196 
8197   // Create local copies for byval args
8198   SmallVector<SDValue, 8> ByValArgs;
8199   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8200     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8201     if (!Flags.isByVal())
8202       continue;
8203 
8204     SDValue Arg = OutVals[i];
8205     unsigned Size = Flags.getByValSize();
8206     Align Alignment = Flags.getNonZeroByValAlign();
8207 
8208     int FI =
8209         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8210     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8211     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8212 
8213     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8214                           /*IsVolatile=*/false,
8215                           /*AlwaysInline=*/false, IsTailCall,
8216                           MachinePointerInfo(), MachinePointerInfo());
8217     ByValArgs.push_back(FIPtr);
8218   }
8219 
8220   if (!IsTailCall)
8221     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8222 
8223   // Copy argument values to their designated locations.
8224   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8225   SmallVector<SDValue, 8> MemOpChains;
8226   SDValue StackPtr;
8227   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8228     CCValAssign &VA = ArgLocs[i];
8229     SDValue ArgValue = OutVals[i];
8230     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8231 
8232     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8233     bool IsF64OnRV32DSoftABI =
8234         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8235     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8236       SDValue SplitF64 = DAG.getNode(
8237           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8238       SDValue Lo = SplitF64.getValue(0);
8239       SDValue Hi = SplitF64.getValue(1);
8240 
8241       Register RegLo = VA.getLocReg();
8242       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8243 
8244       if (RegLo == RISCV::X17) {
8245         // Second half of f64 is passed on the stack.
8246         // Work out the address of the stack slot.
8247         if (!StackPtr.getNode())
8248           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8249         // Emit the store.
8250         MemOpChains.push_back(
8251             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8252       } else {
8253         // Second half of f64 is passed in another GPR.
8254         assert(RegLo < RISCV::X31 && "Invalid register pair");
8255         Register RegHigh = RegLo + 1;
8256         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8257       }
8258       continue;
8259     }
8260 
8261     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8262     // as any other MemLoc.
8263 
8264     // Promote the value if needed.
8265     // For now, only handle fully promoted and indirect arguments.
8266     if (VA.getLocInfo() == CCValAssign::Indirect) {
8267       // Store the argument in a stack slot and pass its address.
8268       Align StackAlign =
8269           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8270                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8271       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8272       // If the original argument was split (e.g. i128), we need
8273       // to store the required parts of it here (and pass just one address).
8274       // Vectors may be partly split to registers and partly to the stack, in
8275       // which case the base address is partly offset and subsequent stores are
8276       // relative to that.
8277       unsigned ArgIndex = Outs[i].OrigArgIndex;
8278       unsigned ArgPartOffset = Outs[i].PartOffset;
8279       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8280       // Calculate the total size to store. We don't have access to what we're
8281       // actually storing other than performing the loop and collecting the
8282       // info.
8283       SmallVector<std::pair<SDValue, SDValue>> Parts;
8284       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8285         SDValue PartValue = OutVals[i + 1];
8286         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8287         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8288         EVT PartVT = PartValue.getValueType();
8289         if (PartVT.isScalableVector())
8290           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8291         StoredSize += PartVT.getStoreSize();
8292         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8293         Parts.push_back(std::make_pair(PartValue, Offset));
8294         ++i;
8295       }
8296       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8297       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8298       MemOpChains.push_back(
8299           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8300                        MachinePointerInfo::getFixedStack(MF, FI)));
8301       for (const auto &Part : Parts) {
8302         SDValue PartValue = Part.first;
8303         SDValue PartOffset = Part.second;
8304         SDValue Address =
8305             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8306         MemOpChains.push_back(
8307             DAG.getStore(Chain, DL, PartValue, Address,
8308                          MachinePointerInfo::getFixedStack(MF, FI)));
8309       }
8310       ArgValue = SpillSlot;
8311     } else {
8312       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8313     }
8314 
8315     // Use local copy if it is a byval arg.
8316     if (Flags.isByVal())
8317       ArgValue = ByValArgs[j++];
8318 
8319     if (VA.isRegLoc()) {
8320       // Queue up the argument copies and emit them at the end.
8321       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8322     } else {
8323       assert(VA.isMemLoc() && "Argument not register or memory");
8324       assert(!IsTailCall && "Tail call not allowed if stack is used "
8325                             "for passing parameters");
8326 
8327       // Work out the address of the stack slot.
8328       if (!StackPtr.getNode())
8329         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8330       SDValue Address =
8331           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8332                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8333 
8334       // Emit the store.
8335       MemOpChains.push_back(
8336           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8337     }
8338   }
8339 
8340   // Join the stores, which are independent of one another.
8341   if (!MemOpChains.empty())
8342     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8343 
8344   SDValue Glue;
8345 
8346   // Build a sequence of copy-to-reg nodes, chained and glued together.
8347   for (auto &Reg : RegsToPass) {
8348     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8349     Glue = Chain.getValue(1);
8350   }
8351 
8352   // Validate that none of the argument registers have been marked as
8353   // reserved, if so report an error. Do the same for the return address if this
8354   // is not a tailcall.
8355   validateCCReservedRegs(RegsToPass, MF);
8356   if (!IsTailCall &&
8357       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8358     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8359         MF.getFunction(),
8360         "Return address register required, but has been reserved."});
8361 
8362   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8363   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8364   // split it and then direct call can be matched by PseudoCALL.
8365   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8366     const GlobalValue *GV = S->getGlobal();
8367 
8368     unsigned OpFlags = RISCVII::MO_CALL;
8369     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8370       OpFlags = RISCVII::MO_PLT;
8371 
8372     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8373   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8374     unsigned OpFlags = RISCVII::MO_CALL;
8375 
8376     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8377                                                  nullptr))
8378       OpFlags = RISCVII::MO_PLT;
8379 
8380     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8381   }
8382 
8383   // The first call operand is the chain and the second is the target address.
8384   SmallVector<SDValue, 8> Ops;
8385   Ops.push_back(Chain);
8386   Ops.push_back(Callee);
8387 
8388   // Add argument registers to the end of the list so that they are
8389   // known live into the call.
8390   for (auto &Reg : RegsToPass)
8391     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8392 
8393   if (!IsTailCall) {
8394     // Add a register mask operand representing the call-preserved registers.
8395     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8396     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8397     assert(Mask && "Missing call preserved mask for calling convention");
8398     Ops.push_back(DAG.getRegisterMask(Mask));
8399   }
8400 
8401   // Glue the call to the argument copies, if any.
8402   if (Glue.getNode())
8403     Ops.push_back(Glue);
8404 
8405   // Emit the call.
8406   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8407 
8408   if (IsTailCall) {
8409     MF.getFrameInfo().setHasTailCall();
8410     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8411   }
8412 
8413   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8414   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8415   Glue = Chain.getValue(1);
8416 
8417   // Mark the end of the call, which is glued to the call itself.
8418   Chain = DAG.getCALLSEQ_END(Chain,
8419                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8420                              DAG.getConstant(0, DL, PtrVT, true),
8421                              Glue, DL);
8422   Glue = Chain.getValue(1);
8423 
8424   // Assign locations to each value returned by this call.
8425   SmallVector<CCValAssign, 16> RVLocs;
8426   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8427   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8428 
8429   // Copy all of the result registers out of their specified physreg.
8430   for (auto &VA : RVLocs) {
8431     // Copy the value out
8432     SDValue RetValue =
8433         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8434     // Glue the RetValue to the end of the call sequence
8435     Chain = RetValue.getValue(1);
8436     Glue = RetValue.getValue(2);
8437 
8438     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8439       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
8440       SDValue RetValue2 =
8441           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
8442       Chain = RetValue2.getValue(1);
8443       Glue = RetValue2.getValue(2);
8444       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
8445                              RetValue2);
8446     }
8447 
8448     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
8449 
8450     InVals.push_back(RetValue);
8451   }
8452 
8453   return Chain;
8454 }
8455 
8456 bool RISCVTargetLowering::CanLowerReturn(
8457     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
8458     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
8459   SmallVector<CCValAssign, 16> RVLocs;
8460   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
8461 
8462   Optional<unsigned> FirstMaskArgument;
8463   if (Subtarget.hasStdExtV())
8464     FirstMaskArgument = preAssignMask(Outs);
8465 
8466   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8467     MVT VT = Outs[i].VT;
8468     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8469     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8470     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
8471                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
8472                  *this, FirstMaskArgument))
8473       return false;
8474   }
8475   return true;
8476 }
8477 
8478 SDValue
8479 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
8480                                  bool IsVarArg,
8481                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
8482                                  const SmallVectorImpl<SDValue> &OutVals,
8483                                  const SDLoc &DL, SelectionDAG &DAG) const {
8484   const MachineFunction &MF = DAG.getMachineFunction();
8485   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8486 
8487   // Stores the assignment of the return value to a location.
8488   SmallVector<CCValAssign, 16> RVLocs;
8489 
8490   // Info about the registers and stack slot.
8491   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
8492                  *DAG.getContext());
8493 
8494   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
8495                     nullptr, CC_RISCV);
8496 
8497   if (CallConv == CallingConv::GHC && !RVLocs.empty())
8498     report_fatal_error("GHC functions return void only");
8499 
8500   SDValue Glue;
8501   SmallVector<SDValue, 4> RetOps(1, Chain);
8502 
8503   // Copy the result values into the output registers.
8504   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
8505     SDValue Val = OutVals[i];
8506     CCValAssign &VA = RVLocs[i];
8507     assert(VA.isRegLoc() && "Can only return in registers!");
8508 
8509     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8510       // Handle returning f64 on RV32D with a soft float ABI.
8511       assert(VA.isRegLoc() && "Expected return via registers");
8512       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
8513                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
8514       SDValue Lo = SplitF64.getValue(0);
8515       SDValue Hi = SplitF64.getValue(1);
8516       Register RegLo = VA.getLocReg();
8517       assert(RegLo < RISCV::X31 && "Invalid register pair");
8518       Register RegHi = RegLo + 1;
8519 
8520       if (STI.isRegisterReservedByUser(RegLo) ||
8521           STI.isRegisterReservedByUser(RegHi))
8522         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8523             MF.getFunction(),
8524             "Return value register required, but has been reserved."});
8525 
8526       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
8527       Glue = Chain.getValue(1);
8528       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
8529       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
8530       Glue = Chain.getValue(1);
8531       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
8532     } else {
8533       // Handle a 'normal' return.
8534       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
8535       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
8536 
8537       if (STI.isRegisterReservedByUser(VA.getLocReg()))
8538         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8539             MF.getFunction(),
8540             "Return value register required, but has been reserved."});
8541 
8542       // Guarantee that all emitted copies are stuck together.
8543       Glue = Chain.getValue(1);
8544       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
8545     }
8546   }
8547 
8548   RetOps[0] = Chain; // Update chain.
8549 
8550   // Add the glue node if we have it.
8551   if (Glue.getNode()) {
8552     RetOps.push_back(Glue);
8553   }
8554 
8555   unsigned RetOpc = RISCVISD::RET_FLAG;
8556   // Interrupt service routines use different return instructions.
8557   const Function &Func = DAG.getMachineFunction().getFunction();
8558   if (Func.hasFnAttribute("interrupt")) {
8559     if (!Func.getReturnType()->isVoidTy())
8560       report_fatal_error(
8561           "Functions with the interrupt attribute must have void return type!");
8562 
8563     MachineFunction &MF = DAG.getMachineFunction();
8564     StringRef Kind =
8565       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8566 
8567     if (Kind == "user")
8568       RetOpc = RISCVISD::URET_FLAG;
8569     else if (Kind == "supervisor")
8570       RetOpc = RISCVISD::SRET_FLAG;
8571     else
8572       RetOpc = RISCVISD::MRET_FLAG;
8573   }
8574 
8575   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
8576 }
8577 
8578 void RISCVTargetLowering::validateCCReservedRegs(
8579     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
8580     MachineFunction &MF) const {
8581   const Function &F = MF.getFunction();
8582   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8583 
8584   if (llvm::any_of(Regs, [&STI](auto Reg) {
8585         return STI.isRegisterReservedByUser(Reg.first);
8586       }))
8587     F.getContext().diagnose(DiagnosticInfoUnsupported{
8588         F, "Argument register required, but has been reserved."});
8589 }
8590 
8591 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
8592   return CI->isTailCall();
8593 }
8594 
8595 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
8596 #define NODE_NAME_CASE(NODE)                                                   \
8597   case RISCVISD::NODE:                                                         \
8598     return "RISCVISD::" #NODE;
8599   // clang-format off
8600   switch ((RISCVISD::NodeType)Opcode) {
8601   case RISCVISD::FIRST_NUMBER:
8602     break;
8603   NODE_NAME_CASE(RET_FLAG)
8604   NODE_NAME_CASE(URET_FLAG)
8605   NODE_NAME_CASE(SRET_FLAG)
8606   NODE_NAME_CASE(MRET_FLAG)
8607   NODE_NAME_CASE(CALL)
8608   NODE_NAME_CASE(SELECT_CC)
8609   NODE_NAME_CASE(BR_CC)
8610   NODE_NAME_CASE(BuildPairF64)
8611   NODE_NAME_CASE(SplitF64)
8612   NODE_NAME_CASE(TAIL)
8613   NODE_NAME_CASE(MULHSU)
8614   NODE_NAME_CASE(SLLW)
8615   NODE_NAME_CASE(SRAW)
8616   NODE_NAME_CASE(SRLW)
8617   NODE_NAME_CASE(DIVW)
8618   NODE_NAME_CASE(DIVUW)
8619   NODE_NAME_CASE(REMUW)
8620   NODE_NAME_CASE(ROLW)
8621   NODE_NAME_CASE(RORW)
8622   NODE_NAME_CASE(CLZW)
8623   NODE_NAME_CASE(CTZW)
8624   NODE_NAME_CASE(FSLW)
8625   NODE_NAME_CASE(FSRW)
8626   NODE_NAME_CASE(FSL)
8627   NODE_NAME_CASE(FSR)
8628   NODE_NAME_CASE(FMV_H_X)
8629   NODE_NAME_CASE(FMV_X_ANYEXTH)
8630   NODE_NAME_CASE(FMV_W_X_RV64)
8631   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
8632   NODE_NAME_CASE(FCVT_X_RTZ)
8633   NODE_NAME_CASE(FCVT_XU_RTZ)
8634   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
8635   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
8636   NODE_NAME_CASE(READ_CYCLE_WIDE)
8637   NODE_NAME_CASE(GREV)
8638   NODE_NAME_CASE(GREVW)
8639   NODE_NAME_CASE(GORC)
8640   NODE_NAME_CASE(GORCW)
8641   NODE_NAME_CASE(SHFL)
8642   NODE_NAME_CASE(SHFLW)
8643   NODE_NAME_CASE(UNSHFL)
8644   NODE_NAME_CASE(UNSHFLW)
8645   NODE_NAME_CASE(BCOMPRESS)
8646   NODE_NAME_CASE(BCOMPRESSW)
8647   NODE_NAME_CASE(BDECOMPRESS)
8648   NODE_NAME_CASE(BDECOMPRESSW)
8649   NODE_NAME_CASE(VMV_V_X_VL)
8650   NODE_NAME_CASE(VFMV_V_F_VL)
8651   NODE_NAME_CASE(VMV_X_S)
8652   NODE_NAME_CASE(VMV_S_X_VL)
8653   NODE_NAME_CASE(VFMV_S_F_VL)
8654   NODE_NAME_CASE(SPLAT_VECTOR_I64)
8655   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
8656   NODE_NAME_CASE(READ_VLENB)
8657   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
8658   NODE_NAME_CASE(VSLIDEUP_VL)
8659   NODE_NAME_CASE(VSLIDE1UP_VL)
8660   NODE_NAME_CASE(VSLIDEDOWN_VL)
8661   NODE_NAME_CASE(VSLIDE1DOWN_VL)
8662   NODE_NAME_CASE(VID_VL)
8663   NODE_NAME_CASE(VFNCVT_ROD_VL)
8664   NODE_NAME_CASE(VECREDUCE_ADD_VL)
8665   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
8666   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
8667   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
8668   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
8669   NODE_NAME_CASE(VECREDUCE_AND_VL)
8670   NODE_NAME_CASE(VECREDUCE_OR_VL)
8671   NODE_NAME_CASE(VECREDUCE_XOR_VL)
8672   NODE_NAME_CASE(VECREDUCE_FADD_VL)
8673   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
8674   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
8675   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
8676   NODE_NAME_CASE(ADD_VL)
8677   NODE_NAME_CASE(AND_VL)
8678   NODE_NAME_CASE(MUL_VL)
8679   NODE_NAME_CASE(OR_VL)
8680   NODE_NAME_CASE(SDIV_VL)
8681   NODE_NAME_CASE(SHL_VL)
8682   NODE_NAME_CASE(SREM_VL)
8683   NODE_NAME_CASE(SRA_VL)
8684   NODE_NAME_CASE(SRL_VL)
8685   NODE_NAME_CASE(SUB_VL)
8686   NODE_NAME_CASE(UDIV_VL)
8687   NODE_NAME_CASE(UREM_VL)
8688   NODE_NAME_CASE(XOR_VL)
8689   NODE_NAME_CASE(SADDSAT_VL)
8690   NODE_NAME_CASE(UADDSAT_VL)
8691   NODE_NAME_CASE(SSUBSAT_VL)
8692   NODE_NAME_CASE(USUBSAT_VL)
8693   NODE_NAME_CASE(FADD_VL)
8694   NODE_NAME_CASE(FSUB_VL)
8695   NODE_NAME_CASE(FMUL_VL)
8696   NODE_NAME_CASE(FDIV_VL)
8697   NODE_NAME_CASE(FNEG_VL)
8698   NODE_NAME_CASE(FABS_VL)
8699   NODE_NAME_CASE(FSQRT_VL)
8700   NODE_NAME_CASE(FMA_VL)
8701   NODE_NAME_CASE(FCOPYSIGN_VL)
8702   NODE_NAME_CASE(SMIN_VL)
8703   NODE_NAME_CASE(SMAX_VL)
8704   NODE_NAME_CASE(UMIN_VL)
8705   NODE_NAME_CASE(UMAX_VL)
8706   NODE_NAME_CASE(FMINNUM_VL)
8707   NODE_NAME_CASE(FMAXNUM_VL)
8708   NODE_NAME_CASE(MULHS_VL)
8709   NODE_NAME_CASE(MULHU_VL)
8710   NODE_NAME_CASE(FP_TO_SINT_VL)
8711   NODE_NAME_CASE(FP_TO_UINT_VL)
8712   NODE_NAME_CASE(SINT_TO_FP_VL)
8713   NODE_NAME_CASE(UINT_TO_FP_VL)
8714   NODE_NAME_CASE(FP_EXTEND_VL)
8715   NODE_NAME_CASE(FP_ROUND_VL)
8716   NODE_NAME_CASE(VWMUL_VL)
8717   NODE_NAME_CASE(VWMULU_VL)
8718   NODE_NAME_CASE(SETCC_VL)
8719   NODE_NAME_CASE(VSELECT_VL)
8720   NODE_NAME_CASE(VMAND_VL)
8721   NODE_NAME_CASE(VMOR_VL)
8722   NODE_NAME_CASE(VMXOR_VL)
8723   NODE_NAME_CASE(VMCLR_VL)
8724   NODE_NAME_CASE(VMSET_VL)
8725   NODE_NAME_CASE(VRGATHER_VX_VL)
8726   NODE_NAME_CASE(VRGATHER_VV_VL)
8727   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
8728   NODE_NAME_CASE(VSEXT_VL)
8729   NODE_NAME_CASE(VZEXT_VL)
8730   NODE_NAME_CASE(VPOPC_VL)
8731   NODE_NAME_CASE(VLE_VL)
8732   NODE_NAME_CASE(VSE_VL)
8733   NODE_NAME_CASE(READ_CSR)
8734   NODE_NAME_CASE(WRITE_CSR)
8735   NODE_NAME_CASE(SWAP_CSR)
8736   }
8737   // clang-format on
8738   return nullptr;
8739 #undef NODE_NAME_CASE
8740 }
8741 
8742 /// getConstraintType - Given a constraint letter, return the type of
8743 /// constraint it is for this target.
8744 RISCVTargetLowering::ConstraintType
8745 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
8746   if (Constraint.size() == 1) {
8747     switch (Constraint[0]) {
8748     default:
8749       break;
8750     case 'f':
8751       return C_RegisterClass;
8752     case 'I':
8753     case 'J':
8754     case 'K':
8755       return C_Immediate;
8756     case 'A':
8757       return C_Memory;
8758     case 'S': // A symbolic address
8759       return C_Other;
8760     }
8761   } else {
8762     if (Constraint == "vr" || Constraint == "vm")
8763       return C_RegisterClass;
8764   }
8765   return TargetLowering::getConstraintType(Constraint);
8766 }
8767 
8768 std::pair<unsigned, const TargetRegisterClass *>
8769 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
8770                                                   StringRef Constraint,
8771                                                   MVT VT) const {
8772   // First, see if this is a constraint that directly corresponds to a
8773   // RISCV register class.
8774   if (Constraint.size() == 1) {
8775     switch (Constraint[0]) {
8776     case 'r':
8777       return std::make_pair(0U, &RISCV::GPRRegClass);
8778     case 'f':
8779       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
8780         return std::make_pair(0U, &RISCV::FPR16RegClass);
8781       if (Subtarget.hasStdExtF() && VT == MVT::f32)
8782         return std::make_pair(0U, &RISCV::FPR32RegClass);
8783       if (Subtarget.hasStdExtD() && VT == MVT::f64)
8784         return std::make_pair(0U, &RISCV::FPR64RegClass);
8785       break;
8786     default:
8787       break;
8788     }
8789   } else {
8790     if (Constraint == "vr") {
8791       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
8792                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
8793         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
8794           return std::make_pair(0U, RC);
8795       }
8796     } else if (Constraint == "vm") {
8797       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
8798         return std::make_pair(0U, &RISCV::VMRegClass);
8799     }
8800   }
8801 
8802   // Clang will correctly decode the usage of register name aliases into their
8803   // official names. However, other frontends like `rustc` do not. This allows
8804   // users of these frontends to use the ABI names for registers in LLVM-style
8805   // register constraints.
8806   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
8807                                .Case("{zero}", RISCV::X0)
8808                                .Case("{ra}", RISCV::X1)
8809                                .Case("{sp}", RISCV::X2)
8810                                .Case("{gp}", RISCV::X3)
8811                                .Case("{tp}", RISCV::X4)
8812                                .Case("{t0}", RISCV::X5)
8813                                .Case("{t1}", RISCV::X6)
8814                                .Case("{t2}", RISCV::X7)
8815                                .Cases("{s0}", "{fp}", RISCV::X8)
8816                                .Case("{s1}", RISCV::X9)
8817                                .Case("{a0}", RISCV::X10)
8818                                .Case("{a1}", RISCV::X11)
8819                                .Case("{a2}", RISCV::X12)
8820                                .Case("{a3}", RISCV::X13)
8821                                .Case("{a4}", RISCV::X14)
8822                                .Case("{a5}", RISCV::X15)
8823                                .Case("{a6}", RISCV::X16)
8824                                .Case("{a7}", RISCV::X17)
8825                                .Case("{s2}", RISCV::X18)
8826                                .Case("{s3}", RISCV::X19)
8827                                .Case("{s4}", RISCV::X20)
8828                                .Case("{s5}", RISCV::X21)
8829                                .Case("{s6}", RISCV::X22)
8830                                .Case("{s7}", RISCV::X23)
8831                                .Case("{s8}", RISCV::X24)
8832                                .Case("{s9}", RISCV::X25)
8833                                .Case("{s10}", RISCV::X26)
8834                                .Case("{s11}", RISCV::X27)
8835                                .Case("{t3}", RISCV::X28)
8836                                .Case("{t4}", RISCV::X29)
8837                                .Case("{t5}", RISCV::X30)
8838                                .Case("{t6}", RISCV::X31)
8839                                .Default(RISCV::NoRegister);
8840   if (XRegFromAlias != RISCV::NoRegister)
8841     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
8842 
8843   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
8844   // TableGen record rather than the AsmName to choose registers for InlineAsm
8845   // constraints, plus we want to match those names to the widest floating point
8846   // register type available, manually select floating point registers here.
8847   //
8848   // The second case is the ABI name of the register, so that frontends can also
8849   // use the ABI names in register constraint lists.
8850   if (Subtarget.hasStdExtF()) {
8851     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
8852                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
8853                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
8854                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
8855                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
8856                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
8857                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
8858                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
8859                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
8860                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
8861                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
8862                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
8863                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
8864                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
8865                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
8866                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
8867                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
8868                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
8869                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
8870                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
8871                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
8872                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
8873                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
8874                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
8875                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
8876                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
8877                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
8878                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
8879                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
8880                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
8881                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
8882                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
8883                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
8884                         .Default(RISCV::NoRegister);
8885     if (FReg != RISCV::NoRegister) {
8886       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
8887       if (Subtarget.hasStdExtD()) {
8888         unsigned RegNo = FReg - RISCV::F0_F;
8889         unsigned DReg = RISCV::F0_D + RegNo;
8890         return std::make_pair(DReg, &RISCV::FPR64RegClass);
8891       }
8892       return std::make_pair(FReg, &RISCV::FPR32RegClass);
8893     }
8894   }
8895 
8896   if (Subtarget.hasStdExtV()) {
8897     Register VReg = StringSwitch<Register>(Constraint.lower())
8898                         .Case("{v0}", RISCV::V0)
8899                         .Case("{v1}", RISCV::V1)
8900                         .Case("{v2}", RISCV::V2)
8901                         .Case("{v3}", RISCV::V3)
8902                         .Case("{v4}", RISCV::V4)
8903                         .Case("{v5}", RISCV::V5)
8904                         .Case("{v6}", RISCV::V6)
8905                         .Case("{v7}", RISCV::V7)
8906                         .Case("{v8}", RISCV::V8)
8907                         .Case("{v9}", RISCV::V9)
8908                         .Case("{v10}", RISCV::V10)
8909                         .Case("{v11}", RISCV::V11)
8910                         .Case("{v12}", RISCV::V12)
8911                         .Case("{v13}", RISCV::V13)
8912                         .Case("{v14}", RISCV::V14)
8913                         .Case("{v15}", RISCV::V15)
8914                         .Case("{v16}", RISCV::V16)
8915                         .Case("{v17}", RISCV::V17)
8916                         .Case("{v18}", RISCV::V18)
8917                         .Case("{v19}", RISCV::V19)
8918                         .Case("{v20}", RISCV::V20)
8919                         .Case("{v21}", RISCV::V21)
8920                         .Case("{v22}", RISCV::V22)
8921                         .Case("{v23}", RISCV::V23)
8922                         .Case("{v24}", RISCV::V24)
8923                         .Case("{v25}", RISCV::V25)
8924                         .Case("{v26}", RISCV::V26)
8925                         .Case("{v27}", RISCV::V27)
8926                         .Case("{v28}", RISCV::V28)
8927                         .Case("{v29}", RISCV::V29)
8928                         .Case("{v30}", RISCV::V30)
8929                         .Case("{v31}", RISCV::V31)
8930                         .Default(RISCV::NoRegister);
8931     if (VReg != RISCV::NoRegister) {
8932       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
8933         return std::make_pair(VReg, &RISCV::VMRegClass);
8934       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
8935         return std::make_pair(VReg, &RISCV::VRRegClass);
8936       for (const auto *RC :
8937            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
8938         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
8939           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
8940           return std::make_pair(VReg, RC);
8941         }
8942       }
8943     }
8944   }
8945 
8946   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8947 }
8948 
8949 unsigned
8950 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
8951   // Currently only support length 1 constraints.
8952   if (ConstraintCode.size() == 1) {
8953     switch (ConstraintCode[0]) {
8954     case 'A':
8955       return InlineAsm::Constraint_A;
8956     default:
8957       break;
8958     }
8959   }
8960 
8961   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
8962 }
8963 
8964 void RISCVTargetLowering::LowerAsmOperandForConstraint(
8965     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
8966     SelectionDAG &DAG) const {
8967   // Currently only support length 1 constraints.
8968   if (Constraint.length() == 1) {
8969     switch (Constraint[0]) {
8970     case 'I':
8971       // Validate & create a 12-bit signed immediate operand.
8972       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
8973         uint64_t CVal = C->getSExtValue();
8974         if (isInt<12>(CVal))
8975           Ops.push_back(
8976               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
8977       }
8978       return;
8979     case 'J':
8980       // Validate & create an integer zero operand.
8981       if (auto *C = dyn_cast<ConstantSDNode>(Op))
8982         if (C->getZExtValue() == 0)
8983           Ops.push_back(
8984               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
8985       return;
8986     case 'K':
8987       // Validate & create a 5-bit unsigned immediate operand.
8988       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
8989         uint64_t CVal = C->getZExtValue();
8990         if (isUInt<5>(CVal))
8991           Ops.push_back(
8992               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
8993       }
8994       return;
8995     case 'S':
8996       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8997         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
8998                                                  GA->getValueType(0)));
8999       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
9000         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
9001                                                 BA->getValueType(0)));
9002       }
9003       return;
9004     default:
9005       break;
9006     }
9007   }
9008   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9009 }
9010 
9011 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
9012                                                    Instruction *Inst,
9013                                                    AtomicOrdering Ord) const {
9014   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
9015     return Builder.CreateFence(Ord);
9016   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
9017     return Builder.CreateFence(AtomicOrdering::Release);
9018   return nullptr;
9019 }
9020 
9021 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
9022                                                     Instruction *Inst,
9023                                                     AtomicOrdering Ord) const {
9024   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
9025     return Builder.CreateFence(AtomicOrdering::Acquire);
9026   return nullptr;
9027 }
9028 
9029 TargetLowering::AtomicExpansionKind
9030 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9031   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
9032   // point operations can't be used in an lr/sc sequence without breaking the
9033   // forward-progress guarantee.
9034   if (AI->isFloatingPointOperation())
9035     return AtomicExpansionKind::CmpXChg;
9036 
9037   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9038   if (Size == 8 || Size == 16)
9039     return AtomicExpansionKind::MaskedIntrinsic;
9040   return AtomicExpansionKind::None;
9041 }
9042 
9043 static Intrinsic::ID
9044 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
9045   if (XLen == 32) {
9046     switch (BinOp) {
9047     default:
9048       llvm_unreachable("Unexpected AtomicRMW BinOp");
9049     case AtomicRMWInst::Xchg:
9050       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
9051     case AtomicRMWInst::Add:
9052       return Intrinsic::riscv_masked_atomicrmw_add_i32;
9053     case AtomicRMWInst::Sub:
9054       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
9055     case AtomicRMWInst::Nand:
9056       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
9057     case AtomicRMWInst::Max:
9058       return Intrinsic::riscv_masked_atomicrmw_max_i32;
9059     case AtomicRMWInst::Min:
9060       return Intrinsic::riscv_masked_atomicrmw_min_i32;
9061     case AtomicRMWInst::UMax:
9062       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
9063     case AtomicRMWInst::UMin:
9064       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
9065     }
9066   }
9067 
9068   if (XLen == 64) {
9069     switch (BinOp) {
9070     default:
9071       llvm_unreachable("Unexpected AtomicRMW BinOp");
9072     case AtomicRMWInst::Xchg:
9073       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
9074     case AtomicRMWInst::Add:
9075       return Intrinsic::riscv_masked_atomicrmw_add_i64;
9076     case AtomicRMWInst::Sub:
9077       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
9078     case AtomicRMWInst::Nand:
9079       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
9080     case AtomicRMWInst::Max:
9081       return Intrinsic::riscv_masked_atomicrmw_max_i64;
9082     case AtomicRMWInst::Min:
9083       return Intrinsic::riscv_masked_atomicrmw_min_i64;
9084     case AtomicRMWInst::UMax:
9085       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
9086     case AtomicRMWInst::UMin:
9087       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
9088     }
9089   }
9090 
9091   llvm_unreachable("Unexpected XLen\n");
9092 }
9093 
9094 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
9095     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
9096     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
9097   unsigned XLen = Subtarget.getXLen();
9098   Value *Ordering =
9099       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
9100   Type *Tys[] = {AlignedAddr->getType()};
9101   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
9102       AI->getModule(),
9103       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
9104 
9105   if (XLen == 64) {
9106     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
9107     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9108     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
9109   }
9110 
9111   Value *Result;
9112 
9113   // Must pass the shift amount needed to sign extend the loaded value prior
9114   // to performing a signed comparison for min/max. ShiftAmt is the number of
9115   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
9116   // is the number of bits to left+right shift the value in order to
9117   // sign-extend.
9118   if (AI->getOperation() == AtomicRMWInst::Min ||
9119       AI->getOperation() == AtomicRMWInst::Max) {
9120     const DataLayout &DL = AI->getModule()->getDataLayout();
9121     unsigned ValWidth =
9122         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
9123     Value *SextShamt =
9124         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
9125     Result = Builder.CreateCall(LrwOpScwLoop,
9126                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
9127   } else {
9128     Result =
9129         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
9130   }
9131 
9132   if (XLen == 64)
9133     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9134   return Result;
9135 }
9136 
9137 TargetLowering::AtomicExpansionKind
9138 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
9139     AtomicCmpXchgInst *CI) const {
9140   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
9141   if (Size == 8 || Size == 16)
9142     return AtomicExpansionKind::MaskedIntrinsic;
9143   return AtomicExpansionKind::None;
9144 }
9145 
9146 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
9147     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
9148     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
9149   unsigned XLen = Subtarget.getXLen();
9150   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
9151   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
9152   if (XLen == 64) {
9153     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
9154     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
9155     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
9156     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
9157   }
9158   Type *Tys[] = {AlignedAddr->getType()};
9159   Function *MaskedCmpXchg =
9160       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
9161   Value *Result = Builder.CreateCall(
9162       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
9163   if (XLen == 64)
9164     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
9165   return Result;
9166 }
9167 
9168 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
9169   return false;
9170 }
9171 
9172 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
9173                                                      EVT VT) const {
9174   VT = VT.getScalarType();
9175 
9176   if (!VT.isSimple())
9177     return false;
9178 
9179   switch (VT.getSimpleVT().SimpleTy) {
9180   case MVT::f16:
9181     return Subtarget.hasStdExtZfh();
9182   case MVT::f32:
9183     return Subtarget.hasStdExtF();
9184   case MVT::f64:
9185     return Subtarget.hasStdExtD();
9186   default:
9187     break;
9188   }
9189 
9190   return false;
9191 }
9192 
9193 Register RISCVTargetLowering::getExceptionPointerRegister(
9194     const Constant *PersonalityFn) const {
9195   return RISCV::X10;
9196 }
9197 
9198 Register RISCVTargetLowering::getExceptionSelectorRegister(
9199     const Constant *PersonalityFn) const {
9200   return RISCV::X11;
9201 }
9202 
9203 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9204   // Return false to suppress the unnecessary extensions if the LibCall
9205   // arguments or return value is f32 type for LP64 ABI.
9206   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9207   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9208     return false;
9209 
9210   return true;
9211 }
9212 
9213 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9214   if (Subtarget.is64Bit() && Type == MVT::i32)
9215     return true;
9216 
9217   return IsSigned;
9218 }
9219 
9220 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9221                                                  SDValue C) const {
9222   // Check integral scalar types.
9223   if (VT.isScalarInteger()) {
9224     // Omit the optimization if the sub target has the M extension and the data
9225     // size exceeds XLen.
9226     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9227       return false;
9228     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9229       // Break the MUL to a SLLI and an ADD/SUB.
9230       const APInt &Imm = ConstNode->getAPIntValue();
9231       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9232           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9233         return true;
9234       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9235       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9236           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9237            (Imm - 8).isPowerOf2()))
9238         return true;
9239       // Omit the following optimization if the sub target has the M extension
9240       // and the data size >= XLen.
9241       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9242         return false;
9243       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9244       // a pair of LUI/ADDI.
9245       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9246         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9247         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9248             (1 - ImmS).isPowerOf2())
9249         return true;
9250       }
9251     }
9252   }
9253 
9254   return false;
9255 }
9256 
9257 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9258     const SDValue &AddNode, const SDValue &ConstNode) const {
9259   // Let the DAGCombiner decide for vectors.
9260   EVT VT = AddNode.getValueType();
9261   if (VT.isVector())
9262     return true;
9263 
9264   // Let the DAGCombiner decide for larger types.
9265   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9266     return true;
9267 
9268   // It is worse if c1 is simm12 while c1*c2 is not.
9269   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9270   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9271   const APInt &C1 = C1Node->getAPIntValue();
9272   const APInt &C2 = C2Node->getAPIntValue();
9273   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9274     return false;
9275 
9276   // Default to true and let the DAGCombiner decide.
9277   return true;
9278 }
9279 
9280 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9281     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9282     bool *Fast) const {
9283   if (!VT.isVector())
9284     return false;
9285 
9286   EVT ElemVT = VT.getVectorElementType();
9287   if (Alignment >= ElemVT.getStoreSize()) {
9288     if (Fast)
9289       *Fast = true;
9290     return true;
9291   }
9292 
9293   return false;
9294 }
9295 
9296 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9297     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9298     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9299   bool IsABIRegCopy = CC.hasValue();
9300   EVT ValueVT = Val.getValueType();
9301   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9302     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9303     // and cast to f32.
9304     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9305     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9306     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9307                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9308     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9309     Parts[0] = Val;
9310     return true;
9311   }
9312 
9313   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9314     LLVMContext &Context = *DAG.getContext();
9315     EVT ValueEltVT = ValueVT.getVectorElementType();
9316     EVT PartEltVT = PartVT.getVectorElementType();
9317     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9318     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9319     if (PartVTBitSize % ValueVTBitSize == 0) {
9320       // If the element types are different, bitcast to the same element type of
9321       // PartVT first.
9322       if (ValueEltVT != PartEltVT) {
9323         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9324         assert(Count != 0 && "The number of element should not be zero.");
9325         EVT SameEltTypeVT =
9326             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9327         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9328       }
9329       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9330                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9331       Parts[0] = Val;
9332       return true;
9333     }
9334   }
9335   return false;
9336 }
9337 
9338 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9339     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9340     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9341   bool IsABIRegCopy = CC.hasValue();
9342   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9343     SDValue Val = Parts[0];
9344 
9345     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9346     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9347     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9348     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9349     return Val;
9350   }
9351 
9352   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9353     LLVMContext &Context = *DAG.getContext();
9354     SDValue Val = Parts[0];
9355     EVT ValueEltVT = ValueVT.getVectorElementType();
9356     EVT PartEltVT = PartVT.getVectorElementType();
9357     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9358     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9359     if (PartVTBitSize % ValueVTBitSize == 0) {
9360       EVT SameEltTypeVT = ValueVT;
9361       // If the element types are different, convert it to the same element type
9362       // of PartVT.
9363       if (ValueEltVT != PartEltVT) {
9364         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9365         assert(Count != 0 && "The number of element should not be zero.");
9366         SameEltTypeVT =
9367             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9368       }
9369       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9370                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9371       if (ValueEltVT != PartEltVT)
9372         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9373       return Val;
9374     }
9375   }
9376   return SDValue();
9377 }
9378 
9379 #define GET_REGISTER_MATCHER
9380 #include "RISCVGenAsmMatcher.inc"
9381 
9382 Register
9383 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9384                                        const MachineFunction &MF) const {
9385   Register Reg = MatchRegisterAltName(RegName);
9386   if (Reg == RISCV::NoRegister)
9387     Reg = MatchRegisterName(RegName);
9388   if (Reg == RISCV::NoRegister)
9389     report_fatal_error(
9390         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9391   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9392   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9393     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9394                              StringRef(RegName) + "\"."));
9395   return Reg;
9396 }
9397 
9398 namespace llvm {
9399 namespace RISCVVIntrinsicsTable {
9400 
9401 #define GET_RISCVVIntrinsicsTable_IMPL
9402 #include "RISCVGenSearchableTables.inc"
9403 
9404 } // namespace RISCVVIntrinsicsTable
9405 
9406 } // namespace llvm
9407