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