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