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