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