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