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/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
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     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
269     // BSWAP i8 doesn't exist.
270     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
271     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
272 
273     if (Subtarget.is64Bit()) {
274       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
275       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
276     }
277   } else {
278     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
279     // pattern match it directly in isel.
280     setOperationAction(ISD::BSWAP, XLenVT,
281                        Subtarget.hasStdExtZbb() ? Legal : Expand);
282   }
283 
284   if (Subtarget.hasStdExtZbb()) {
285     setOperationAction(ISD::SMIN, XLenVT, Legal);
286     setOperationAction(ISD::SMAX, XLenVT, Legal);
287     setOperationAction(ISD::UMIN, XLenVT, Legal);
288     setOperationAction(ISD::UMAX, XLenVT, Legal);
289 
290     if (Subtarget.is64Bit()) {
291       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
292       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
293       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
294       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
295     }
296   } else {
297     setOperationAction(ISD::CTTZ, XLenVT, Expand);
298     setOperationAction(ISD::CTLZ, XLenVT, Expand);
299     setOperationAction(ISD::CTPOP, XLenVT, Expand);
300   }
301 
302   if (Subtarget.hasStdExtZbt()) {
303     setOperationAction(ISD::FSHL, XLenVT, Custom);
304     setOperationAction(ISD::FSHR, XLenVT, Custom);
305     setOperationAction(ISD::SELECT, XLenVT, Legal);
306 
307     if (Subtarget.is64Bit()) {
308       setOperationAction(ISD::FSHL, MVT::i32, Custom);
309       setOperationAction(ISD::FSHR, MVT::i32, Custom);
310     }
311   } else {
312     setOperationAction(ISD::SELECT, XLenVT, Custom);
313   }
314 
315   static const ISD::CondCode FPCCToExpand[] = {
316       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
317       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
318       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
319 
320   static const ISD::NodeType FPOpToExpand[] = {
321       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
322       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
323 
324   if (Subtarget.hasStdExtZfh())
325     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
326 
327   if (Subtarget.hasStdExtZfh()) {
328     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
329     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
330     setOperationAction(ISD::LRINT, MVT::f16, Legal);
331     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
332     setOperationAction(ISD::LROUND, MVT::f16, Legal);
333     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
334     setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal);
335     setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal);
336     setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal);
337     setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal);
338     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
339     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
340     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
341     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
342     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
343     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
344     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
345     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
346     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal);
348     for (auto CC : FPCCToExpand)
349       setCondCodeAction(CC, MVT::f16, Expand);
350     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT, MVT::f16, Custom);
352     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
353 
354     setOperationAction(ISD::FREM,       MVT::f16, Promote);
355     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
356     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
357     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
358     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
359     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
360     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
361     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
362     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
363     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
364     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
365     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
366     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
367     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
368     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
369     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
370     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
371     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
372 
373     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
374     // complete support for all operations in LegalizeDAG.
375 
376     // We need to custom promote this.
377     if (Subtarget.is64Bit())
378       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
379   }
380 
381   if (Subtarget.hasStdExtF()) {
382     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
383     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
384     setOperationAction(ISD::LRINT, MVT::f32, Legal);
385     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
386     setOperationAction(ISD::LROUND, MVT::f32, Legal);
387     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
388     setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal);
389     setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal);
390     setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal);
391     setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal);
392     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
393     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
394     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
395     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
396     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
397     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
398     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
399     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
400     for (auto CC : FPCCToExpand)
401       setCondCodeAction(CC, MVT::f32, Expand);
402     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
403     setOperationAction(ISD::SELECT, MVT::f32, Custom);
404     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
405     for (auto Op : FPOpToExpand)
406       setOperationAction(Op, MVT::f32, Expand);
407     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
408     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
409   }
410 
411   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
412     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
413 
414   if (Subtarget.hasStdExtD()) {
415     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
416     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
417     setOperationAction(ISD::LRINT, MVT::f64, Legal);
418     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
419     setOperationAction(ISD::LROUND, MVT::f64, Legal);
420     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
421     setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal);
422     setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal);
423     setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal);
424     setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal);
425     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
426     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
427     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
428     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
429     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
431     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
432     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
433     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
435     for (auto CC : FPCCToExpand)
436       setCondCodeAction(CC, MVT::f64, Expand);
437     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
438     setOperationAction(ISD::SELECT, MVT::f64, Custom);
439     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
440     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
441     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
442     for (auto Op : FPOpToExpand)
443       setOperationAction(Op, MVT::f64, Expand);
444     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
445     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
446   }
447 
448   if (Subtarget.is64Bit()) {
449     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
450     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
451     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
452     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
453   }
454 
455   if (Subtarget.hasStdExtF()) {
456     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
457     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
458 
459     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
460     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
461     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
462     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
463 
464     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
465     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
466   }
467 
468   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
469   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
470   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
471   setOperationAction(ISD::JumpTable, XLenVT, Custom);
472 
473   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
474 
475   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
476   // Unfortunately this can't be determined just from the ISA naming string.
477   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
478                      Subtarget.is64Bit() ? Legal : Custom);
479 
480   setOperationAction(ISD::TRAP, MVT::Other, Legal);
481   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
482   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
483   if (Subtarget.is64Bit())
484     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
485 
486   if (Subtarget.hasStdExtA()) {
487     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
488     setMinCmpXchgSizeInBits(32);
489   } else {
490     setMaxAtomicSizeInBitsSupported(0);
491   }
492 
493   setBooleanContents(ZeroOrOneBooleanContent);
494 
495   if (Subtarget.hasVInstructions()) {
496     setBooleanVectorContents(ZeroOrOneBooleanContent);
497 
498     setOperationAction(ISD::VSCALE, XLenVT, Custom);
499 
500     // RVV intrinsics may have illegal operands.
501     // We also need to custom legalize vmv.x.s.
502     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
503     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
504     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
505     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
506     if (Subtarget.is64Bit()) {
507       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
508     } else {
509       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
510       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
511     }
512 
513     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
514     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
515 
516     static const unsigned IntegerVPOps[] = {
517         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
518         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
519         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
520         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
521         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
522         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
523         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
524         ISD::VP_SELECT};
525 
526     static const unsigned FloatingPointVPOps[] = {
527         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
528         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
529         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_SELECT};
530 
531     if (!Subtarget.is64Bit()) {
532       // We must custom-lower certain vXi64 operations on RV32 due to the vector
533       // element type being illegal.
534       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
535       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
536 
537       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
538       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
539       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
540       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
541       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
542       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
543       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
544       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
545 
546       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
547       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
548       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
549       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
550       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
551       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
552       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
553       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
554     }
555 
556     for (MVT VT : BoolVecVTs) {
557       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
558 
559       // Mask VTs are custom-expanded into a series of standard nodes
560       setOperationAction(ISD::TRUNCATE, VT, Custom);
561       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
562       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
563       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
564 
565       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
566       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
567 
568       setOperationAction(ISD::SELECT, VT, Custom);
569       setOperationAction(ISD::SELECT_CC, VT, Expand);
570       setOperationAction(ISD::VSELECT, VT, Expand);
571       setOperationAction(ISD::VP_SELECT, VT, Expand);
572 
573       setOperationAction(ISD::VP_AND, VT, Custom);
574       setOperationAction(ISD::VP_OR, VT, Custom);
575       setOperationAction(ISD::VP_XOR, VT, Custom);
576 
577       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
578       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
579       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
580 
581       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
582       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
583       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
584 
585       // RVV has native int->float & float->int conversions where the
586       // element type sizes are within one power-of-two of each other. Any
587       // wider distances between type sizes have to be lowered as sequences
588       // which progressively narrow the gap in stages.
589       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
590       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
591       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
592       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
593 
594       // Expand all extending loads to types larger than this, and truncating
595       // stores from types larger than this.
596       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
597         setTruncStoreAction(OtherVT, VT, Expand);
598         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
599         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
600         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
601       }
602     }
603 
604     for (MVT VT : IntVecVTs) {
605       if (VT.getVectorElementType() == MVT::i64 &&
606           !Subtarget.hasVInstructionsI64())
607         continue;
608 
609       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
610       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
611 
612       // Vectors implement MULHS/MULHU.
613       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
614       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
615 
616       setOperationAction(ISD::SMIN, VT, Legal);
617       setOperationAction(ISD::SMAX, VT, Legal);
618       setOperationAction(ISD::UMIN, VT, Legal);
619       setOperationAction(ISD::UMAX, VT, Legal);
620 
621       setOperationAction(ISD::ROTL, VT, Expand);
622       setOperationAction(ISD::ROTR, VT, Expand);
623 
624       setOperationAction(ISD::CTTZ, VT, Expand);
625       setOperationAction(ISD::CTLZ, VT, Expand);
626       setOperationAction(ISD::CTPOP, VT, Expand);
627 
628       setOperationAction(ISD::BSWAP, VT, Expand);
629 
630       // Custom-lower extensions and truncations from/to mask types.
631       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
632       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
633       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
634 
635       // RVV has native int->float & float->int conversions where the
636       // element type sizes are within one power-of-two of each other. Any
637       // wider distances between type sizes have to be lowered as sequences
638       // which progressively narrow the gap in stages.
639       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
640       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
641       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
642       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
643 
644       setOperationAction(ISD::SADDSAT, VT, Legal);
645       setOperationAction(ISD::UADDSAT, VT, Legal);
646       setOperationAction(ISD::SSUBSAT, VT, Legal);
647       setOperationAction(ISD::USUBSAT, VT, Legal);
648 
649       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
650       // nodes which truncate by one power of two at a time.
651       setOperationAction(ISD::TRUNCATE, VT, Custom);
652 
653       // Custom-lower insert/extract operations to simplify patterns.
654       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
655       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
656 
657       // Custom-lower reduction operations to set up the corresponding custom
658       // nodes' operands.
659       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
660       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
661       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
662       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
663       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
664       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
665       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
666       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
667 
668       for (unsigned VPOpc : IntegerVPOps)
669         setOperationAction(VPOpc, VT, Custom);
670 
671       setOperationAction(ISD::LOAD, VT, Custom);
672       setOperationAction(ISD::STORE, VT, Custom);
673 
674       setOperationAction(ISD::MLOAD, VT, Custom);
675       setOperationAction(ISD::MSTORE, VT, Custom);
676       setOperationAction(ISD::MGATHER, VT, Custom);
677       setOperationAction(ISD::MSCATTER, VT, Custom);
678 
679       setOperationAction(ISD::VP_LOAD, VT, Custom);
680       setOperationAction(ISD::VP_STORE, VT, Custom);
681       setOperationAction(ISD::VP_GATHER, VT, Custom);
682       setOperationAction(ISD::VP_SCATTER, VT, Custom);
683 
684       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
685       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
686       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
687 
688       setOperationAction(ISD::SELECT, VT, Custom);
689       setOperationAction(ISD::SELECT_CC, VT, Expand);
690 
691       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
692       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
693 
694       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
695         setTruncStoreAction(VT, OtherVT, Expand);
696         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
697         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
698         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
699       }
700 
701       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
702       // type that can represent the value exactly.
703       if (VT.getVectorElementType() != MVT::i64) {
704         MVT FloatEltVT =
705             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
706         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
707         if (isTypeLegal(FloatVT)) {
708           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
709           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
710         }
711       }
712     }
713 
714     // Expand various CCs to best match the RVV ISA, which natively supports UNE
715     // but no other unordered comparisons, and supports all ordered comparisons
716     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
717     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
718     // and we pattern-match those back to the "original", swapping operands once
719     // more. This way we catch both operations and both "vf" and "fv" forms with
720     // fewer patterns.
721     static const ISD::CondCode VFPCCToExpand[] = {
722         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
723         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
724         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
725     };
726 
727     // Sets common operation actions on RVV floating-point vector types.
728     const auto SetCommonVFPActions = [&](MVT VT) {
729       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
730       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
731       // sizes are within one power-of-two of each other. Therefore conversions
732       // between vXf16 and vXf64 must be lowered as sequences which convert via
733       // vXf32.
734       setOperationAction(ISD::FP_ROUND, VT, Custom);
735       setOperationAction(ISD::FP_EXTEND, VT, Custom);
736       // Custom-lower insert/extract operations to simplify patterns.
737       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
738       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739       // Expand various condition codes (explained above).
740       for (auto CC : VFPCCToExpand)
741         setCondCodeAction(CC, VT, Expand);
742 
743       setOperationAction(ISD::FMINNUM, VT, Legal);
744       setOperationAction(ISD::FMAXNUM, VT, Legal);
745 
746       setOperationAction(ISD::FTRUNC, VT, Custom);
747       setOperationAction(ISD::FCEIL, VT, Custom);
748       setOperationAction(ISD::FFLOOR, VT, Custom);
749 
750       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
751       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
752       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
753       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
754 
755       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
756 
757       setOperationAction(ISD::LOAD, VT, Custom);
758       setOperationAction(ISD::STORE, VT, Custom);
759 
760       setOperationAction(ISD::MLOAD, VT, Custom);
761       setOperationAction(ISD::MSTORE, VT, Custom);
762       setOperationAction(ISD::MGATHER, VT, Custom);
763       setOperationAction(ISD::MSCATTER, VT, Custom);
764 
765       setOperationAction(ISD::VP_LOAD, VT, Custom);
766       setOperationAction(ISD::VP_STORE, VT, Custom);
767       setOperationAction(ISD::VP_GATHER, VT, Custom);
768       setOperationAction(ISD::VP_SCATTER, VT, Custom);
769 
770       setOperationAction(ISD::SELECT, VT, Custom);
771       setOperationAction(ISD::SELECT_CC, VT, Expand);
772 
773       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
774       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
775       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
776 
777       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
778 
779       for (unsigned VPOpc : FloatingPointVPOps)
780         setOperationAction(VPOpc, VT, Custom);
781     };
782 
783     // Sets common extload/truncstore actions on RVV floating-point vector
784     // types.
785     const auto SetCommonVFPExtLoadTruncStoreActions =
786         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
787           for (auto SmallVT : SmallerVTs) {
788             setTruncStoreAction(VT, SmallVT, Expand);
789             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
790           }
791         };
792 
793     if (Subtarget.hasVInstructionsF16())
794       for (MVT VT : F16VecVTs)
795         SetCommonVFPActions(VT);
796 
797     for (MVT VT : F32VecVTs) {
798       if (Subtarget.hasVInstructionsF32())
799         SetCommonVFPActions(VT);
800       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
801     }
802 
803     for (MVT VT : F64VecVTs) {
804       if (Subtarget.hasVInstructionsF64())
805         SetCommonVFPActions(VT);
806       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
807       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
808     }
809 
810     if (Subtarget.useRVVForFixedLengthVectors()) {
811       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
812         if (!useRVVForFixedLengthVectorVT(VT))
813           continue;
814 
815         // By default everything must be expanded.
816         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
817           setOperationAction(Op, VT, Expand);
818         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
819           setTruncStoreAction(VT, OtherVT, Expand);
820           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
821           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
822           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
823         }
824 
825         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
826         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
827         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
828 
829         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
830         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
831 
832         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
833         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
834 
835         setOperationAction(ISD::LOAD, VT, Custom);
836         setOperationAction(ISD::STORE, VT, Custom);
837 
838         setOperationAction(ISD::SETCC, VT, Custom);
839 
840         setOperationAction(ISD::SELECT, VT, Custom);
841 
842         setOperationAction(ISD::TRUNCATE, VT, Custom);
843 
844         setOperationAction(ISD::BITCAST, VT, Custom);
845 
846         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
847         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
848         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
849 
850         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
851         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
852         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
853 
854         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
855         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
856         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
857         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
858 
859         // Operations below are different for between masks and other vectors.
860         if (VT.getVectorElementType() == MVT::i1) {
861           setOperationAction(ISD::VP_AND, VT, Custom);
862           setOperationAction(ISD::VP_OR, VT, Custom);
863           setOperationAction(ISD::VP_XOR, VT, Custom);
864           setOperationAction(ISD::AND, VT, Custom);
865           setOperationAction(ISD::OR, VT, Custom);
866           setOperationAction(ISD::XOR, VT, Custom);
867           continue;
868         }
869 
870         // Use SPLAT_VECTOR to prevent type legalization from destroying the
871         // splats when type legalizing i64 scalar on RV32.
872         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
873         // improvements first.
874         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
875           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
876           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
877         }
878 
879         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
880         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
881 
882         setOperationAction(ISD::MLOAD, VT, Custom);
883         setOperationAction(ISD::MSTORE, VT, Custom);
884         setOperationAction(ISD::MGATHER, VT, Custom);
885         setOperationAction(ISD::MSCATTER, VT, Custom);
886 
887         setOperationAction(ISD::VP_LOAD, VT, Custom);
888         setOperationAction(ISD::VP_STORE, VT, Custom);
889         setOperationAction(ISD::VP_GATHER, VT, Custom);
890         setOperationAction(ISD::VP_SCATTER, VT, Custom);
891 
892         setOperationAction(ISD::ADD, VT, Custom);
893         setOperationAction(ISD::MUL, VT, Custom);
894         setOperationAction(ISD::SUB, VT, Custom);
895         setOperationAction(ISD::AND, VT, Custom);
896         setOperationAction(ISD::OR, VT, Custom);
897         setOperationAction(ISD::XOR, VT, Custom);
898         setOperationAction(ISD::SDIV, VT, Custom);
899         setOperationAction(ISD::SREM, VT, Custom);
900         setOperationAction(ISD::UDIV, VT, Custom);
901         setOperationAction(ISD::UREM, VT, Custom);
902         setOperationAction(ISD::SHL, VT, Custom);
903         setOperationAction(ISD::SRA, VT, Custom);
904         setOperationAction(ISD::SRL, VT, Custom);
905 
906         setOperationAction(ISD::SMIN, VT, Custom);
907         setOperationAction(ISD::SMAX, VT, Custom);
908         setOperationAction(ISD::UMIN, VT, Custom);
909         setOperationAction(ISD::UMAX, VT, Custom);
910         setOperationAction(ISD::ABS,  VT, Custom);
911 
912         setOperationAction(ISD::MULHS, VT, Custom);
913         setOperationAction(ISD::MULHU, VT, Custom);
914 
915         setOperationAction(ISD::SADDSAT, VT, Custom);
916         setOperationAction(ISD::UADDSAT, VT, Custom);
917         setOperationAction(ISD::SSUBSAT, VT, Custom);
918         setOperationAction(ISD::USUBSAT, VT, Custom);
919 
920         setOperationAction(ISD::VSELECT, VT, Custom);
921         setOperationAction(ISD::SELECT_CC, VT, Expand);
922 
923         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
924         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
925         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
926 
927         // Custom-lower reduction operations to set up the corresponding custom
928         // nodes' operands.
929         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
930         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
931         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
932         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
933         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
934 
935         for (unsigned VPOpc : IntegerVPOps)
936           setOperationAction(VPOpc, VT, Custom);
937 
938         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
939         // type that can represent the value exactly.
940         if (VT.getVectorElementType() != MVT::i64) {
941           MVT FloatEltVT =
942               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
943           EVT FloatVT =
944               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
945           if (isTypeLegal(FloatVT)) {
946             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
947             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
948           }
949         }
950       }
951 
952       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
953         if (!useRVVForFixedLengthVectorVT(VT))
954           continue;
955 
956         // By default everything must be expanded.
957         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
958           setOperationAction(Op, VT, Expand);
959         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
960           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
961           setTruncStoreAction(VT, OtherVT, Expand);
962         }
963 
964         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
965         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
966         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
967 
968         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
969         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
970         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
971         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
972         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
973 
974         setOperationAction(ISD::LOAD, VT, Custom);
975         setOperationAction(ISD::STORE, VT, Custom);
976         setOperationAction(ISD::MLOAD, VT, Custom);
977         setOperationAction(ISD::MSTORE, VT, Custom);
978         setOperationAction(ISD::MGATHER, VT, Custom);
979         setOperationAction(ISD::MSCATTER, VT, Custom);
980 
981         setOperationAction(ISD::VP_LOAD, VT, Custom);
982         setOperationAction(ISD::VP_STORE, VT, Custom);
983         setOperationAction(ISD::VP_GATHER, VT, Custom);
984         setOperationAction(ISD::VP_SCATTER, VT, Custom);
985 
986         setOperationAction(ISD::FADD, VT, Custom);
987         setOperationAction(ISD::FSUB, VT, Custom);
988         setOperationAction(ISD::FMUL, VT, Custom);
989         setOperationAction(ISD::FDIV, VT, Custom);
990         setOperationAction(ISD::FNEG, VT, Custom);
991         setOperationAction(ISD::FABS, VT, Custom);
992         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
993         setOperationAction(ISD::FSQRT, VT, Custom);
994         setOperationAction(ISD::FMA, VT, Custom);
995         setOperationAction(ISD::FMINNUM, VT, Custom);
996         setOperationAction(ISD::FMAXNUM, VT, Custom);
997 
998         setOperationAction(ISD::FP_ROUND, VT, Custom);
999         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1000 
1001         setOperationAction(ISD::FTRUNC, VT, Custom);
1002         setOperationAction(ISD::FCEIL, VT, Custom);
1003         setOperationAction(ISD::FFLOOR, VT, Custom);
1004 
1005         for (auto CC : VFPCCToExpand)
1006           setCondCodeAction(CC, VT, Expand);
1007 
1008         setOperationAction(ISD::VSELECT, VT, Custom);
1009         setOperationAction(ISD::SELECT, VT, Custom);
1010         setOperationAction(ISD::SELECT_CC, VT, Expand);
1011 
1012         setOperationAction(ISD::BITCAST, VT, Custom);
1013 
1014         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1015         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1016         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1017         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1018 
1019         for (unsigned VPOpc : FloatingPointVPOps)
1020           setOperationAction(VPOpc, VT, Custom);
1021       }
1022 
1023       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1024       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1025       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1026       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1027       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1028       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1029       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1030       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1031     }
1032   }
1033 
1034   // Function alignments.
1035   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1036   setMinFunctionAlignment(FunctionAlignment);
1037   setPrefFunctionAlignment(FunctionAlignment);
1038 
1039   setMinimumJumpTableEntries(5);
1040 
1041   // Jumps are expensive, compared to logic
1042   setJumpIsExpensive();
1043 
1044   setTargetDAGCombine(ISD::ADD);
1045   setTargetDAGCombine(ISD::SUB);
1046   setTargetDAGCombine(ISD::AND);
1047   setTargetDAGCombine(ISD::OR);
1048   setTargetDAGCombine(ISD::XOR);
1049   setTargetDAGCombine(ISD::ANY_EXTEND);
1050   if (Subtarget.hasStdExtF()) {
1051     setTargetDAGCombine(ISD::ZERO_EXTEND);
1052     setTargetDAGCombine(ISD::FP_TO_SINT);
1053     setTargetDAGCombine(ISD::FP_TO_UINT);
1054   }
1055   if (Subtarget.hasVInstructions()) {
1056     setTargetDAGCombine(ISD::FCOPYSIGN);
1057     setTargetDAGCombine(ISD::MGATHER);
1058     setTargetDAGCombine(ISD::MSCATTER);
1059     setTargetDAGCombine(ISD::VP_GATHER);
1060     setTargetDAGCombine(ISD::VP_SCATTER);
1061     setTargetDAGCombine(ISD::SRA);
1062     setTargetDAGCombine(ISD::SRL);
1063     setTargetDAGCombine(ISD::SHL);
1064     setTargetDAGCombine(ISD::STORE);
1065   }
1066 }
1067 
1068 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1069                                             LLVMContext &Context,
1070                                             EVT VT) const {
1071   if (!VT.isVector())
1072     return getPointerTy(DL);
1073   if (Subtarget.hasVInstructions() &&
1074       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1075     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1076   return VT.changeVectorElementTypeToInteger();
1077 }
1078 
1079 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1080   return Subtarget.getXLenVT();
1081 }
1082 
1083 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1084                                              const CallInst &I,
1085                                              MachineFunction &MF,
1086                                              unsigned Intrinsic) const {
1087   auto &DL = I.getModule()->getDataLayout();
1088   switch (Intrinsic) {
1089   default:
1090     return false;
1091   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1092   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1093   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1099   case Intrinsic::riscv_masked_cmpxchg_i32: {
1100     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
1101     Info.opc = ISD::INTRINSIC_W_CHAIN;
1102     Info.memVT = MVT::getVT(PtrTy->getElementType());
1103     Info.ptrVal = I.getArgOperand(0);
1104     Info.offset = 0;
1105     Info.align = Align(4);
1106     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1107                  MachineMemOperand::MOVolatile;
1108     return true;
1109   }
1110   case Intrinsic::riscv_masked_strided_load:
1111     Info.opc = ISD::INTRINSIC_W_CHAIN;
1112     Info.ptrVal = I.getArgOperand(1);
1113     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1114     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1115     Info.size = MemoryLocation::UnknownSize;
1116     Info.flags |= MachineMemOperand::MOLoad;
1117     return true;
1118   case Intrinsic::riscv_masked_strided_store:
1119     Info.opc = ISD::INTRINSIC_VOID;
1120     Info.ptrVal = I.getArgOperand(1);
1121     Info.memVT =
1122         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1123     Info.align = Align(
1124         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1125         8);
1126     Info.size = MemoryLocation::UnknownSize;
1127     Info.flags |= MachineMemOperand::MOStore;
1128     return true;
1129   }
1130 }
1131 
1132 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1133                                                 const AddrMode &AM, Type *Ty,
1134                                                 unsigned AS,
1135                                                 Instruction *I) const {
1136   // No global is ever allowed as a base.
1137   if (AM.BaseGV)
1138     return false;
1139 
1140   // Require a 12-bit signed offset.
1141   if (!isInt<12>(AM.BaseOffs))
1142     return false;
1143 
1144   switch (AM.Scale) {
1145   case 0: // "r+i" or just "i", depending on HasBaseReg.
1146     break;
1147   case 1:
1148     if (!AM.HasBaseReg) // allow "r+i".
1149       break;
1150     return false; // disallow "r+r" or "r+r+i".
1151   default:
1152     return false;
1153   }
1154 
1155   return true;
1156 }
1157 
1158 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1159   return isInt<12>(Imm);
1160 }
1161 
1162 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1163   return isInt<12>(Imm);
1164 }
1165 
1166 // On RV32, 64-bit integers are split into their high and low parts and held
1167 // in two different registers, so the trunc is free since the low register can
1168 // just be used.
1169 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1170   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1171     return false;
1172   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1173   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1174   return (SrcBits == 64 && DestBits == 32);
1175 }
1176 
1177 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1178   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1179       !SrcVT.isInteger() || !DstVT.isInteger())
1180     return false;
1181   unsigned SrcBits = SrcVT.getSizeInBits();
1182   unsigned DestBits = DstVT.getSizeInBits();
1183   return (SrcBits == 64 && DestBits == 32);
1184 }
1185 
1186 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1187   // Zexts are free if they can be combined with a load.
1188   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1189   // poorly with type legalization of compares preferring sext.
1190   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1191     EVT MemVT = LD->getMemoryVT();
1192     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1193         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1194          LD->getExtensionType() == ISD::ZEXTLOAD))
1195       return true;
1196   }
1197 
1198   return TargetLowering::isZExtFree(Val, VT2);
1199 }
1200 
1201 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1202   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1203 }
1204 
1205 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1206   return Subtarget.hasStdExtZbb();
1207 }
1208 
1209 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1210   return Subtarget.hasStdExtZbb();
1211 }
1212 
1213 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1214   EVT VT = Y.getValueType();
1215 
1216   // FIXME: Support vectors once we have tests.
1217   if (VT.isVector())
1218     return false;
1219 
1220   return Subtarget.hasStdExtZbb() && !isa<ConstantSDNode>(Y);
1221 }
1222 
1223 /// Check if sinking \p I's operands to I's basic block is profitable, because
1224 /// the operands can be folded into a target instruction, e.g.
1225 /// splats of scalars can fold into vector instructions.
1226 bool RISCVTargetLowering::shouldSinkOperands(
1227     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1228   using namespace llvm::PatternMatch;
1229 
1230   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1231     return false;
1232 
1233   auto IsSinker = [&](Instruction *I, int Operand) {
1234     switch (I->getOpcode()) {
1235     case Instruction::Add:
1236     case Instruction::Sub:
1237     case Instruction::Mul:
1238     case Instruction::And:
1239     case Instruction::Or:
1240     case Instruction::Xor:
1241     case Instruction::FAdd:
1242     case Instruction::FSub:
1243     case Instruction::FMul:
1244     case Instruction::FDiv:
1245     case Instruction::ICmp:
1246     case Instruction::FCmp:
1247       return true;
1248     case Instruction::Shl:
1249     case Instruction::LShr:
1250     case Instruction::AShr:
1251     case Instruction::UDiv:
1252     case Instruction::SDiv:
1253     case Instruction::URem:
1254     case Instruction::SRem:
1255       return Operand == 1;
1256     case Instruction::Call:
1257       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1258         switch (II->getIntrinsicID()) {
1259         case Intrinsic::fma:
1260           return Operand == 0 || Operand == 1;
1261         default:
1262           return false;
1263         }
1264       }
1265       return false;
1266     default:
1267       return false;
1268     }
1269   };
1270 
1271   for (auto OpIdx : enumerate(I->operands())) {
1272     if (!IsSinker(I, OpIdx.index()))
1273       continue;
1274 
1275     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1276     // Make sure we are not already sinking this operand
1277     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1278       continue;
1279 
1280     // We are looking for a splat that can be sunk.
1281     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1282                              m_Undef(), m_ZeroMask())))
1283       continue;
1284 
1285     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1286     // and vector registers
1287     for (Use &U : Op->uses()) {
1288       Instruction *Insn = cast<Instruction>(U.getUser());
1289       if (!IsSinker(Insn, U.getOperandNo()))
1290         return false;
1291     }
1292 
1293     Ops.push_back(&Op->getOperandUse(0));
1294     Ops.push_back(&OpIdx.value());
1295   }
1296   return true;
1297 }
1298 
1299 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1300                                        bool ForCodeSize) const {
1301   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1302   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1303     return false;
1304   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1305     return false;
1306   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1307     return false;
1308   if (Imm.isNegZero())
1309     return false;
1310   return Imm.isZero();
1311 }
1312 
1313 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1314   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1315          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1316          (VT == MVT::f64 && Subtarget.hasStdExtD());
1317 }
1318 
1319 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1320                                                       CallingConv::ID CC,
1321                                                       EVT VT) const {
1322   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1323   // We might still end up using a GPR but that will be decided based on ABI.
1324   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1325   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1326     return MVT::f32;
1327 
1328   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1329 }
1330 
1331 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1332                                                            CallingConv::ID CC,
1333                                                            EVT VT) const {
1334   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1335   // We might still end up using a GPR but that will be decided based on ABI.
1336   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1337   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1338     return 1;
1339 
1340   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1341 }
1342 
1343 // Changes the condition code and swaps operands if necessary, so the SetCC
1344 // operation matches one of the comparisons supported directly by branches
1345 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1346 // with 1/-1.
1347 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1348                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1349   // Convert X > -1 to X >= 0.
1350   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1351     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1352     CC = ISD::SETGE;
1353     return;
1354   }
1355   // Convert X < 1 to 0 >= X.
1356   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1357     RHS = LHS;
1358     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1359     CC = ISD::SETGE;
1360     return;
1361   }
1362 
1363   switch (CC) {
1364   default:
1365     break;
1366   case ISD::SETGT:
1367   case ISD::SETLE:
1368   case ISD::SETUGT:
1369   case ISD::SETULE:
1370     CC = ISD::getSetCCSwappedOperands(CC);
1371     std::swap(LHS, RHS);
1372     break;
1373   }
1374 }
1375 
1376 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1377   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1378   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1379   if (VT.getVectorElementType() == MVT::i1)
1380     KnownSize *= 8;
1381 
1382   switch (KnownSize) {
1383   default:
1384     llvm_unreachable("Invalid LMUL.");
1385   case 8:
1386     return RISCVII::VLMUL::LMUL_F8;
1387   case 16:
1388     return RISCVII::VLMUL::LMUL_F4;
1389   case 32:
1390     return RISCVII::VLMUL::LMUL_F2;
1391   case 64:
1392     return RISCVII::VLMUL::LMUL_1;
1393   case 128:
1394     return RISCVII::VLMUL::LMUL_2;
1395   case 256:
1396     return RISCVII::VLMUL::LMUL_4;
1397   case 512:
1398     return RISCVII::VLMUL::LMUL_8;
1399   }
1400 }
1401 
1402 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1403   switch (LMul) {
1404   default:
1405     llvm_unreachable("Invalid LMUL.");
1406   case RISCVII::VLMUL::LMUL_F8:
1407   case RISCVII::VLMUL::LMUL_F4:
1408   case RISCVII::VLMUL::LMUL_F2:
1409   case RISCVII::VLMUL::LMUL_1:
1410     return RISCV::VRRegClassID;
1411   case RISCVII::VLMUL::LMUL_2:
1412     return RISCV::VRM2RegClassID;
1413   case RISCVII::VLMUL::LMUL_4:
1414     return RISCV::VRM4RegClassID;
1415   case RISCVII::VLMUL::LMUL_8:
1416     return RISCV::VRM8RegClassID;
1417   }
1418 }
1419 
1420 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1421   RISCVII::VLMUL LMUL = getLMUL(VT);
1422   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1423       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1424       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1425       LMUL == RISCVII::VLMUL::LMUL_1) {
1426     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1427                   "Unexpected subreg numbering");
1428     return RISCV::sub_vrm1_0 + Index;
1429   }
1430   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1431     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1432                   "Unexpected subreg numbering");
1433     return RISCV::sub_vrm2_0 + Index;
1434   }
1435   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1436     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1437                   "Unexpected subreg numbering");
1438     return RISCV::sub_vrm4_0 + Index;
1439   }
1440   llvm_unreachable("Invalid vector type.");
1441 }
1442 
1443 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1444   if (VT.getVectorElementType() == MVT::i1)
1445     return RISCV::VRRegClassID;
1446   return getRegClassIDForLMUL(getLMUL(VT));
1447 }
1448 
1449 // Attempt to decompose a subvector insert/extract between VecVT and
1450 // SubVecVT via subregister indices. Returns the subregister index that
1451 // can perform the subvector insert/extract with the given element index, as
1452 // well as the index corresponding to any leftover subvectors that must be
1453 // further inserted/extracted within the register class for SubVecVT.
1454 std::pair<unsigned, unsigned>
1455 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1456     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1457     const RISCVRegisterInfo *TRI) {
1458   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1459                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1460                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1461                 "Register classes not ordered");
1462   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1463   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1464   // Try to compose a subregister index that takes us from the incoming
1465   // LMUL>1 register class down to the outgoing one. At each step we half
1466   // the LMUL:
1467   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1468   // Note that this is not guaranteed to find a subregister index, such as
1469   // when we are extracting from one VR type to another.
1470   unsigned SubRegIdx = RISCV::NoSubRegister;
1471   for (const unsigned RCID :
1472        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1473     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1474       VecVT = VecVT.getHalfNumVectorElementsVT();
1475       bool IsHi =
1476           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1477       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1478                                             getSubregIndexByMVT(VecVT, IsHi));
1479       if (IsHi)
1480         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1481     }
1482   return {SubRegIdx, InsertExtractIdx};
1483 }
1484 
1485 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1486 // stores for those types.
1487 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1488   return !Subtarget.useRVVForFixedLengthVectors() ||
1489          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1490 }
1491 
1492 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1493   if (ScalarTy->isPointerTy())
1494     return true;
1495 
1496   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1497       ScalarTy->isIntegerTy(32))
1498     return true;
1499 
1500   if (ScalarTy->isIntegerTy(64))
1501     return Subtarget.hasVInstructionsI64();
1502 
1503   if (ScalarTy->isHalfTy())
1504     return Subtarget.hasVInstructionsF16();
1505   if (ScalarTy->isFloatTy())
1506     return Subtarget.hasVInstructionsF32();
1507   if (ScalarTy->isDoubleTy())
1508     return Subtarget.hasVInstructionsF64();
1509 
1510   return false;
1511 }
1512 
1513 static bool useRVVForFixedLengthVectorVT(MVT VT,
1514                                          const RISCVSubtarget &Subtarget) {
1515   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1516   if (!Subtarget.useRVVForFixedLengthVectors())
1517     return false;
1518 
1519   // We only support a set of vector types with a consistent maximum fixed size
1520   // across all supported vector element types to avoid legalization issues.
1521   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1522   // fixed-length vector type we support is 1024 bytes.
1523   if (VT.getFixedSizeInBits() > 1024 * 8)
1524     return false;
1525 
1526   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1527 
1528   MVT EltVT = VT.getVectorElementType();
1529 
1530   // Don't use RVV for vectors we cannot scalarize if required.
1531   switch (EltVT.SimpleTy) {
1532   // i1 is supported but has different rules.
1533   default:
1534     return false;
1535   case MVT::i1:
1536     // Masks can only use a single register.
1537     if (VT.getVectorNumElements() > MinVLen)
1538       return false;
1539     MinVLen /= 8;
1540     break;
1541   case MVT::i8:
1542   case MVT::i16:
1543   case MVT::i32:
1544     break;
1545   case MVT::i64:
1546     if (!Subtarget.hasVInstructionsI64())
1547       return false;
1548     break;
1549   case MVT::f16:
1550     if (!Subtarget.hasVInstructionsF16())
1551       return false;
1552     break;
1553   case MVT::f32:
1554     if (!Subtarget.hasVInstructionsF32())
1555       return false;
1556     break;
1557   case MVT::f64:
1558     if (!Subtarget.hasVInstructionsF64())
1559       return false;
1560     break;
1561   }
1562 
1563   // Reject elements larger than ELEN.
1564   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1565     return false;
1566 
1567   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1568   // Don't use RVV for types that don't fit.
1569   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1570     return false;
1571 
1572   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1573   // the base fixed length RVV support in place.
1574   if (!VT.isPow2VectorType())
1575     return false;
1576 
1577   return true;
1578 }
1579 
1580 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1581   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1582 }
1583 
1584 // Return the largest legal scalable vector type that matches VT's element type.
1585 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1586                                             const RISCVSubtarget &Subtarget) {
1587   // This may be called before legal types are setup.
1588   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1589           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1590          "Expected legal fixed length vector!");
1591 
1592   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1593   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1594 
1595   MVT EltVT = VT.getVectorElementType();
1596   switch (EltVT.SimpleTy) {
1597   default:
1598     llvm_unreachable("unexpected element type for RVV container");
1599   case MVT::i1:
1600   case MVT::i8:
1601   case MVT::i16:
1602   case MVT::i32:
1603   case MVT::i64:
1604   case MVT::f16:
1605   case MVT::f32:
1606   case MVT::f64: {
1607     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1608     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1609     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1610     unsigned NumElts =
1611         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1612     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1613     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1614     return MVT::getScalableVectorVT(EltVT, NumElts);
1615   }
1616   }
1617 }
1618 
1619 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1620                                             const RISCVSubtarget &Subtarget) {
1621   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1622                                           Subtarget);
1623 }
1624 
1625 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1626   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1627 }
1628 
1629 // Grow V to consume an entire RVV register.
1630 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1631                                        const RISCVSubtarget &Subtarget) {
1632   assert(VT.isScalableVector() &&
1633          "Expected to convert into a scalable vector!");
1634   assert(V.getValueType().isFixedLengthVector() &&
1635          "Expected a fixed length vector operand!");
1636   SDLoc DL(V);
1637   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1638   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1639 }
1640 
1641 // Shrink V so it's just big enough to maintain a VT's worth of data.
1642 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1643                                          const RISCVSubtarget &Subtarget) {
1644   assert(VT.isFixedLengthVector() &&
1645          "Expected to convert into a fixed length vector!");
1646   assert(V.getValueType().isScalableVector() &&
1647          "Expected a scalable vector operand!");
1648   SDLoc DL(V);
1649   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1650   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1651 }
1652 
1653 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1654 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1655 // the vector type that it is contained in.
1656 static std::pair<SDValue, SDValue>
1657 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1658                 const RISCVSubtarget &Subtarget) {
1659   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1660   MVT XLenVT = Subtarget.getXLenVT();
1661   SDValue VL = VecVT.isFixedLengthVector()
1662                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1663                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1664   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1665   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1666   return {Mask, VL};
1667 }
1668 
1669 // As above but assuming the given type is a scalable vector type.
1670 static std::pair<SDValue, SDValue>
1671 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1672                         const RISCVSubtarget &Subtarget) {
1673   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1674   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1675 }
1676 
1677 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1678 // of either is (currently) supported. This can get us into an infinite loop
1679 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1680 // as a ..., etc.
1681 // Until either (or both) of these can reliably lower any node, reporting that
1682 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1683 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1684 // which is not desirable.
1685 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1686     EVT VT, unsigned DefinedValues) const {
1687   return false;
1688 }
1689 
1690 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1691   // Only splats are currently supported.
1692   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1693     return true;
1694 
1695   return false;
1696 }
1697 
1698 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1699                                   const RISCVSubtarget &Subtarget) {
1700   // RISCV FP-to-int conversions saturate to the destination register size, but
1701   // don't produce 0 for nan. We can use a conversion instruction and fix the
1702   // nan case with a compare and a select.
1703   SDValue Src = Op.getOperand(0);
1704 
1705   EVT DstVT = Op.getValueType();
1706   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1707 
1708   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1709   unsigned Opc;
1710   if (SatVT == DstVT)
1711     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1712   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1713     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1714   else
1715     return SDValue();
1716   // FIXME: Support other SatVTs by clamping before or after the conversion.
1717 
1718   SDLoc DL(Op);
1719   SDValue FpToInt = DAG.getNode(
1720       Opc, DL, DstVT, Src,
1721       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1722 
1723   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1724   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1725 }
1726 
1727 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1728 // and back. Taking care to avoid converting values that are nan or already
1729 // correct.
1730 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1731 // have FRM dependencies modeled yet.
1732 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1733   MVT VT = Op.getSimpleValueType();
1734   assert(VT.isVector() && "Unexpected type");
1735 
1736   SDLoc DL(Op);
1737 
1738   // Freeze the source since we are increasing the number of uses.
1739   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1740 
1741   // Truncate to integer and convert back to FP.
1742   MVT IntVT = VT.changeVectorElementTypeToInteger();
1743   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1744   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1745 
1746   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1747 
1748   if (Op.getOpcode() == ISD::FCEIL) {
1749     // If the truncated value is the greater than or equal to the original
1750     // value, we've computed the ceil. Otherwise, we went the wrong way and
1751     // need to increase by 1.
1752     // FIXME: This should use a masked operation. Handle here or in isel?
1753     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1754                                  DAG.getConstantFP(1.0, DL, VT));
1755     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1756     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1757   } else if (Op.getOpcode() == ISD::FFLOOR) {
1758     // If the truncated value is the less than or equal to the original value,
1759     // we've computed the floor. Otherwise, we went the wrong way and need to
1760     // decrease by 1.
1761     // FIXME: This should use a masked operation. Handle here or in isel?
1762     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1763                                  DAG.getConstantFP(1.0, DL, VT));
1764     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1765     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1766   }
1767 
1768   // Restore the original sign so that -0.0 is preserved.
1769   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1770 
1771   // Determine the largest integer that can be represented exactly. This and
1772   // values larger than it don't have any fractional bits so don't need to
1773   // be converted.
1774   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1775   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1776   APFloat MaxVal = APFloat(FltSem);
1777   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1778                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1779   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1780 
1781   // If abs(Src) was larger than MaxVal or nan, keep it.
1782   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1783   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1784   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1785 }
1786 
1787 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1788                                  const RISCVSubtarget &Subtarget) {
1789   MVT VT = Op.getSimpleValueType();
1790   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1791 
1792   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1793 
1794   SDLoc DL(Op);
1795   SDValue Mask, VL;
1796   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1797 
1798   unsigned Opc =
1799       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1800   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1801   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1802 }
1803 
1804 struct VIDSequence {
1805   int64_t StepNumerator;
1806   unsigned StepDenominator;
1807   int64_t Addend;
1808 };
1809 
1810 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1811 // to the (non-zero) step S and start value X. This can be then lowered as the
1812 // RVV sequence (VID * S) + X, for example.
1813 // The step S is represented as an integer numerator divided by a positive
1814 // denominator. Note that the implementation currently only identifies
1815 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1816 // cannot detect 2/3, for example.
1817 // Note that this method will also match potentially unappealing index
1818 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1819 // determine whether this is worth generating code for.
1820 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1821   unsigned NumElts = Op.getNumOperands();
1822   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1823   if (!Op.getValueType().isInteger())
1824     return None;
1825 
1826   Optional<unsigned> SeqStepDenom;
1827   Optional<int64_t> SeqStepNum, SeqAddend;
1828   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1829   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1830   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1831     // Assume undef elements match the sequence; we just have to be careful
1832     // when interpolating across them.
1833     if (Op.getOperand(Idx).isUndef())
1834       continue;
1835     // The BUILD_VECTOR must be all constants.
1836     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1837       return None;
1838 
1839     uint64_t Val = Op.getConstantOperandVal(Idx) &
1840                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1841 
1842     if (PrevElt) {
1843       // Calculate the step since the last non-undef element, and ensure
1844       // it's consistent across the entire sequence.
1845       unsigned IdxDiff = Idx - PrevElt->second;
1846       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1847 
1848       // A zero-value value difference means that we're somewhere in the middle
1849       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1850       // step change before evaluating the sequence.
1851       if (ValDiff != 0) {
1852         int64_t Remainder = ValDiff % IdxDiff;
1853         // Normalize the step if it's greater than 1.
1854         if (Remainder != ValDiff) {
1855           // The difference must cleanly divide the element span.
1856           if (Remainder != 0)
1857             return None;
1858           ValDiff /= IdxDiff;
1859           IdxDiff = 1;
1860         }
1861 
1862         if (!SeqStepNum)
1863           SeqStepNum = ValDiff;
1864         else if (ValDiff != SeqStepNum)
1865           return None;
1866 
1867         if (!SeqStepDenom)
1868           SeqStepDenom = IdxDiff;
1869         else if (IdxDiff != *SeqStepDenom)
1870           return None;
1871       }
1872     }
1873 
1874     // Record and/or check any addend.
1875     if (SeqStepNum && SeqStepDenom) {
1876       uint64_t ExpectedVal =
1877           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1878       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1879       if (!SeqAddend)
1880         SeqAddend = Addend;
1881       else if (SeqAddend != Addend)
1882         return None;
1883     }
1884 
1885     // Record this non-undef element for later.
1886     if (!PrevElt || PrevElt->first != Val)
1887       PrevElt = std::make_pair(Val, Idx);
1888   }
1889   // We need to have logged both a step and an addend for this to count as
1890   // a legal index sequence.
1891   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1892     return None;
1893 
1894   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1895 }
1896 
1897 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1898                                  const RISCVSubtarget &Subtarget) {
1899   MVT VT = Op.getSimpleValueType();
1900   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1901 
1902   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1903 
1904   SDLoc DL(Op);
1905   SDValue Mask, VL;
1906   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1907 
1908   MVT XLenVT = Subtarget.getXLenVT();
1909   unsigned NumElts = Op.getNumOperands();
1910 
1911   if (VT.getVectorElementType() == MVT::i1) {
1912     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1913       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1914       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1915     }
1916 
1917     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1918       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1919       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1920     }
1921 
1922     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1923     // scalar integer chunks whose bit-width depends on the number of mask
1924     // bits and XLEN.
1925     // First, determine the most appropriate scalar integer type to use. This
1926     // is at most XLenVT, but may be shrunk to a smaller vector element type
1927     // according to the size of the final vector - use i8 chunks rather than
1928     // XLenVT if we're producing a v8i1. This results in more consistent
1929     // codegen across RV32 and RV64.
1930     unsigned NumViaIntegerBits =
1931         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1932     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1933       // If we have to use more than one INSERT_VECTOR_ELT then this
1934       // optimization is likely to increase code size; avoid peforming it in
1935       // such a case. We can use a load from a constant pool in this case.
1936       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1937         return SDValue();
1938       // Now we can create our integer vector type. Note that it may be larger
1939       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1940       MVT IntegerViaVecVT =
1941           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1942                            divideCeil(NumElts, NumViaIntegerBits));
1943 
1944       uint64_t Bits = 0;
1945       unsigned BitPos = 0, IntegerEltIdx = 0;
1946       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1947 
1948       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1949         // Once we accumulate enough bits to fill our scalar type, insert into
1950         // our vector and clear our accumulated data.
1951         if (I != 0 && I % NumViaIntegerBits == 0) {
1952           if (NumViaIntegerBits <= 32)
1953             Bits = SignExtend64(Bits, 32);
1954           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1955           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1956                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1957           Bits = 0;
1958           BitPos = 0;
1959           IntegerEltIdx++;
1960         }
1961         SDValue V = Op.getOperand(I);
1962         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1963         Bits |= ((uint64_t)BitValue << BitPos);
1964       }
1965 
1966       // Insert the (remaining) scalar value into position in our integer
1967       // vector type.
1968       if (NumViaIntegerBits <= 32)
1969         Bits = SignExtend64(Bits, 32);
1970       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1971       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1972                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1973 
1974       if (NumElts < NumViaIntegerBits) {
1975         // If we're producing a smaller vector than our minimum legal integer
1976         // type, bitcast to the equivalent (known-legal) mask type, and extract
1977         // our final mask.
1978         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1979         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1980         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1981                           DAG.getConstant(0, DL, XLenVT));
1982       } else {
1983         // Else we must have produced an integer type with the same size as the
1984         // mask type; bitcast for the final result.
1985         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1986         Vec = DAG.getBitcast(VT, Vec);
1987       }
1988 
1989       return Vec;
1990     }
1991 
1992     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1993     // vector type, we have a legal equivalently-sized i8 type, so we can use
1994     // that.
1995     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1996     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1997 
1998     SDValue WideVec;
1999     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2000       // For a splat, perform a scalar truncate before creating the wider
2001       // vector.
2002       assert(Splat.getValueType() == XLenVT &&
2003              "Unexpected type for i1 splat value");
2004       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2005                           DAG.getConstant(1, DL, XLenVT));
2006       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2007     } else {
2008       SmallVector<SDValue, 8> Ops(Op->op_values());
2009       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2010       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2011       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2012     }
2013 
2014     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2015   }
2016 
2017   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2018     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2019                                         : RISCVISD::VMV_V_X_VL;
2020     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2021     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2022   }
2023 
2024   // Try and match index sequences, which we can lower to the vid instruction
2025   // with optional modifications. An all-undef vector is matched by
2026   // getSplatValue, above.
2027   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2028     int64_t StepNumerator = SimpleVID->StepNumerator;
2029     unsigned StepDenominator = SimpleVID->StepDenominator;
2030     int64_t Addend = SimpleVID->Addend;
2031 
2032     assert(StepNumerator != 0 && "Invalid step");
2033     bool Negate = false;
2034     int64_t SplatStepVal = StepNumerator;
2035     unsigned StepOpcode = ISD::MUL;
2036     if (StepNumerator != 1) {
2037       if (isPowerOf2_64(std::abs(StepNumerator))) {
2038         Negate = StepNumerator < 0;
2039         StepOpcode = ISD::SHL;
2040         SplatStepVal = Log2_64(std::abs(StepNumerator));
2041       }
2042     }
2043 
2044     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2045     // threshold since it's the immediate value many RVV instructions accept.
2046     // There is no vmul.vi instruction so ensure multiply constant can fit in
2047     // a single addi instruction.
2048     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2049          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2050         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2051       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2052       // Convert right out of the scalable type so we can use standard ISD
2053       // nodes for the rest of the computation. If we used scalable types with
2054       // these, we'd lose the fixed-length vector info and generate worse
2055       // vsetvli code.
2056       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2057       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2058           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2059         SDValue SplatStep = DAG.getSplatVector(
2060             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2061         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2062       }
2063       if (StepDenominator != 1) {
2064         SDValue SplatStep = DAG.getSplatVector(
2065             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2066         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2067       }
2068       if (Addend != 0 || Negate) {
2069         SDValue SplatAddend =
2070             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2071         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2072       }
2073       return VID;
2074     }
2075   }
2076 
2077   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2078   // when re-interpreted as a vector with a larger element type. For example,
2079   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2080   // could be instead splat as
2081   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2082   // TODO: This optimization could also work on non-constant splats, but it
2083   // would require bit-manipulation instructions to construct the splat value.
2084   SmallVector<SDValue> Sequence;
2085   unsigned EltBitSize = VT.getScalarSizeInBits();
2086   const auto *BV = cast<BuildVectorSDNode>(Op);
2087   if (VT.isInteger() && EltBitSize < 64 &&
2088       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2089       BV->getRepeatedSequence(Sequence) &&
2090       (Sequence.size() * EltBitSize) <= 64) {
2091     unsigned SeqLen = Sequence.size();
2092     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2093     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2094     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2095             ViaIntVT == MVT::i64) &&
2096            "Unexpected sequence type");
2097 
2098     unsigned EltIdx = 0;
2099     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2100     uint64_t SplatValue = 0;
2101     // Construct the amalgamated value which can be splatted as this larger
2102     // vector type.
2103     for (const auto &SeqV : Sequence) {
2104       if (!SeqV.isUndef())
2105         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2106                        << (EltIdx * EltBitSize));
2107       EltIdx++;
2108     }
2109 
2110     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2111     // achieve better constant materializion.
2112     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2113       SplatValue = SignExtend64(SplatValue, 32);
2114 
2115     // Since we can't introduce illegal i64 types at this stage, we can only
2116     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2117     // way we can use RVV instructions to splat.
2118     assert((ViaIntVT.bitsLE(XLenVT) ||
2119             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2120            "Unexpected bitcast sequence");
2121     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2122       SDValue ViaVL =
2123           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2124       MVT ViaContainerVT =
2125           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2126       SDValue Splat =
2127           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2128                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2129       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2130       return DAG.getBitcast(VT, Splat);
2131     }
2132   }
2133 
2134   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2135   // which constitute a large proportion of the elements. In such cases we can
2136   // splat a vector with the dominant element and make up the shortfall with
2137   // INSERT_VECTOR_ELTs.
2138   // Note that this includes vectors of 2 elements by association. The
2139   // upper-most element is the "dominant" one, allowing us to use a splat to
2140   // "insert" the upper element, and an insert of the lower element at position
2141   // 0, which improves codegen.
2142   SDValue DominantValue;
2143   unsigned MostCommonCount = 0;
2144   DenseMap<SDValue, unsigned> ValueCounts;
2145   unsigned NumUndefElts =
2146       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2147 
2148   // Track the number of scalar loads we know we'd be inserting, estimated as
2149   // any non-zero floating-point constant. Other kinds of element are either
2150   // already in registers or are materialized on demand. The threshold at which
2151   // a vector load is more desirable than several scalar materializion and
2152   // vector-insertion instructions is not known.
2153   unsigned NumScalarLoads = 0;
2154 
2155   for (SDValue V : Op->op_values()) {
2156     if (V.isUndef())
2157       continue;
2158 
2159     ValueCounts.insert(std::make_pair(V, 0));
2160     unsigned &Count = ValueCounts[V];
2161 
2162     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2163       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2164 
2165     // Is this value dominant? In case of a tie, prefer the highest element as
2166     // it's cheaper to insert near the beginning of a vector than it is at the
2167     // end.
2168     if (++Count >= MostCommonCount) {
2169       DominantValue = V;
2170       MostCommonCount = Count;
2171     }
2172   }
2173 
2174   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2175   unsigned NumDefElts = NumElts - NumUndefElts;
2176   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2177 
2178   // Don't perform this optimization when optimizing for size, since
2179   // materializing elements and inserting them tends to cause code bloat.
2180   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2181       ((MostCommonCount > DominantValueCountThreshold) ||
2182        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2183     // Start by splatting the most common element.
2184     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2185 
2186     DenseSet<SDValue> Processed{DominantValue};
2187     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2188     for (const auto &OpIdx : enumerate(Op->ops())) {
2189       const SDValue &V = OpIdx.value();
2190       if (V.isUndef() || !Processed.insert(V).second)
2191         continue;
2192       if (ValueCounts[V] == 1) {
2193         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2194                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2195       } else {
2196         // Blend in all instances of this value using a VSELECT, using a
2197         // mask where each bit signals whether that element is the one
2198         // we're after.
2199         SmallVector<SDValue> Ops;
2200         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2201           return DAG.getConstant(V == V1, DL, XLenVT);
2202         });
2203         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2204                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2205                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2206       }
2207     }
2208 
2209     return Vec;
2210   }
2211 
2212   return SDValue();
2213 }
2214 
2215 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2216                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2217   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2218     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2219     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2220     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2221     // node in order to try and match RVV vector/scalar instructions.
2222     if ((LoC >> 31) == HiC)
2223       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2224 
2225     // If vl is equal to VLMax and Hi constant is equal to Lo, we could use
2226     // vmv.v.x whose EEW = 32 to lower it.
2227     auto *Const = dyn_cast<ConstantSDNode>(VL);
2228     if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) {
2229       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2230       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2231       // access the subtarget here now.
2232       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL);
2233       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2234     }
2235   }
2236 
2237   // Fall back to a stack store and stride x0 vector load.
2238   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2239 }
2240 
2241 // Called by type legalization to handle splat of i64 on RV32.
2242 // FIXME: We can optimize this when the type has sign or zero bits in one
2243 // of the halves.
2244 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2245                                    SDValue VL, SelectionDAG &DAG) {
2246   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2247   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2248                            DAG.getConstant(0, DL, MVT::i32));
2249   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2250                            DAG.getConstant(1, DL, MVT::i32));
2251   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2252 }
2253 
2254 // This function lowers a splat of a scalar operand Splat with the vector
2255 // length VL. It ensures the final sequence is type legal, which is useful when
2256 // lowering a splat after type legalization.
2257 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2258                                 SelectionDAG &DAG,
2259                                 const RISCVSubtarget &Subtarget) {
2260   if (VT.isFloatingPoint()) {
2261     // If VL is 1, we could use vfmv.s.f.
2262     if (isOneConstant(VL))
2263       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2264                          Scalar, VL);
2265     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2266   }
2267 
2268   MVT XLenVT = Subtarget.getXLenVT();
2269 
2270   // Simplest case is that the operand needs to be promoted to XLenVT.
2271   if (Scalar.getValueType().bitsLE(XLenVT)) {
2272     // If the operand is a constant, sign extend to increase our chances
2273     // of being able to use a .vi instruction. ANY_EXTEND would become a
2274     // a zero extend and the simm5 check in isel would fail.
2275     // FIXME: Should we ignore the upper bits in isel instead?
2276     unsigned ExtOpc =
2277         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2278     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2279     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2280     // If VL is 1 and the scalar value won't benefit from immediate, we could
2281     // use vmv.s.x.
2282     if (isOneConstant(VL) &&
2283         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2284       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2285                          VL);
2286     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2287   }
2288 
2289   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2290          "Unexpected scalar for splat lowering!");
2291 
2292   if (isOneConstant(VL) && isNullConstant(Scalar))
2293     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2294                        DAG.getConstant(0, DL, XLenVT), VL);
2295 
2296   // Otherwise use the more complicated splatting algorithm.
2297   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2298 }
2299 
2300 // Is the mask a slidedown that shifts in undefs.
2301 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2302   int Size = Mask.size();
2303 
2304   // Elements shifted in should be undef.
2305   auto CheckUndefs = [&](int Shift) {
2306     for (int i = Size - Shift; i != Size; ++i)
2307       if (Mask[i] >= 0)
2308         return false;
2309     return true;
2310   };
2311 
2312   // Elements should be shifted or undef.
2313   auto MatchShift = [&](int Shift) {
2314     for (int i = 0; i != Size - Shift; ++i)
2315        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2316          return false;
2317     return true;
2318   };
2319 
2320   // Try all possible shifts.
2321   for (int Shift = 1; Shift != Size; ++Shift)
2322     if (CheckUndefs(Shift) && MatchShift(Shift))
2323       return Shift;
2324 
2325   // No match.
2326   return -1;
2327 }
2328 
2329 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2330                                    const RISCVSubtarget &Subtarget) {
2331   SDValue V1 = Op.getOperand(0);
2332   SDValue V2 = Op.getOperand(1);
2333   SDLoc DL(Op);
2334   MVT XLenVT = Subtarget.getXLenVT();
2335   MVT VT = Op.getSimpleValueType();
2336   unsigned NumElts = VT.getVectorNumElements();
2337   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2338 
2339   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2340 
2341   SDValue TrueMask, VL;
2342   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2343 
2344   if (SVN->isSplat()) {
2345     const int Lane = SVN->getSplatIndex();
2346     if (Lane >= 0) {
2347       MVT SVT = VT.getVectorElementType();
2348 
2349       // Turn splatted vector load into a strided load with an X0 stride.
2350       SDValue V = V1;
2351       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2352       // with undef.
2353       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2354       int Offset = Lane;
2355       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2356         int OpElements =
2357             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2358         V = V.getOperand(Offset / OpElements);
2359         Offset %= OpElements;
2360       }
2361 
2362       // We need to ensure the load isn't atomic or volatile.
2363       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2364         auto *Ld = cast<LoadSDNode>(V);
2365         Offset *= SVT.getStoreSize();
2366         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2367                                                    TypeSize::Fixed(Offset), DL);
2368 
2369         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2370         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2371           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2372           SDValue IntID =
2373               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2374           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
2375                            DAG.getRegister(RISCV::X0, XLenVT), VL};
2376           SDValue NewLoad = DAG.getMemIntrinsicNode(
2377               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2378               DAG.getMachineFunction().getMachineMemOperand(
2379                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2380           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2381           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2382         }
2383 
2384         // Otherwise use a scalar load and splat. This will give the best
2385         // opportunity to fold a splat into the operation. ISel can turn it into
2386         // the x0 strided load if we aren't able to fold away the select.
2387         if (SVT.isFloatingPoint())
2388           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2389                           Ld->getPointerInfo().getWithOffset(Offset),
2390                           Ld->getOriginalAlign(),
2391                           Ld->getMemOperand()->getFlags());
2392         else
2393           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2394                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2395                              Ld->getOriginalAlign(),
2396                              Ld->getMemOperand()->getFlags());
2397         DAG.makeEquivalentMemoryOrdering(Ld, V);
2398 
2399         unsigned Opc =
2400             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2401         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2402         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2403       }
2404 
2405       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2406       assert(Lane < (int)NumElts && "Unexpected lane!");
2407       SDValue Gather =
2408           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2409                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2410       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2411     }
2412   }
2413 
2414   // Try to match as a slidedown.
2415   int SlideAmt = matchShuffleAsSlideDown(SVN->getMask());
2416   if (SlideAmt >= 0) {
2417     // TODO: Should we reduce the VL to account for the upper undef elements?
2418     // Requires additional vsetvlis, but might be faster to execute.
2419     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2420     SDValue SlideDown =
2421         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2422                     DAG.getUNDEF(ContainerVT), V1,
2423                     DAG.getConstant(SlideAmt, DL, XLenVT),
2424                     TrueMask, VL);
2425     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2426   }
2427 
2428   // Detect shuffles which can be re-expressed as vector selects; these are
2429   // shuffles in which each element in the destination is taken from an element
2430   // at the corresponding index in either source vectors.
2431   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
2432     int MaskIndex = MaskIdx.value();
2433     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2434   });
2435 
2436   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2437 
2438   SmallVector<SDValue> MaskVals;
2439   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2440   // merged with a second vrgather.
2441   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2442 
2443   // By default we preserve the original operand order, and use a mask to
2444   // select LHS as true and RHS as false. However, since RVV vector selects may
2445   // feature splats but only on the LHS, we may choose to invert our mask and
2446   // instead select between RHS and LHS.
2447   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2448   bool InvertMask = IsSelect == SwapOps;
2449 
2450   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2451   // half.
2452   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2453 
2454   // Now construct the mask that will be used by the vselect or blended
2455   // vrgather operation. For vrgathers, construct the appropriate indices into
2456   // each vector.
2457   for (int MaskIndex : SVN->getMask()) {
2458     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2459     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2460     if (!IsSelect) {
2461       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2462       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2463                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2464                                      : DAG.getUNDEF(XLenVT));
2465       GatherIndicesRHS.push_back(
2466           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2467                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2468       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2469         ++LHSIndexCounts[MaskIndex];
2470       if (!IsLHSOrUndefIndex)
2471         ++RHSIndexCounts[MaskIndex - NumElts];
2472     }
2473   }
2474 
2475   if (SwapOps) {
2476     std::swap(V1, V2);
2477     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2478   }
2479 
2480   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2481   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2482   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2483 
2484   if (IsSelect)
2485     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2486 
2487   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2488     // On such a large vector we're unable to use i8 as the index type.
2489     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2490     // may involve vector splitting if we're already at LMUL=8, or our
2491     // user-supplied maximum fixed-length LMUL.
2492     return SDValue();
2493   }
2494 
2495   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2496   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2497   MVT IndexVT = VT.changeTypeToInteger();
2498   // Since we can't introduce illegal index types at this stage, use i16 and
2499   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2500   // than XLenVT.
2501   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2502     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2503     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2504   }
2505 
2506   MVT IndexContainerVT =
2507       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2508 
2509   SDValue Gather;
2510   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2511   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2512   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2513     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2514   } else {
2515     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2516     // If only one index is used, we can use a "splat" vrgather.
2517     // TODO: We can splat the most-common index and fix-up any stragglers, if
2518     // that's beneficial.
2519     if (LHSIndexCounts.size() == 1) {
2520       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2521       Gather =
2522           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2523                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2524     } else {
2525       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2526       LHSIndices =
2527           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2528 
2529       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2530                            TrueMask, VL);
2531     }
2532   }
2533 
2534   // If a second vector operand is used by this shuffle, blend it in with an
2535   // additional vrgather.
2536   if (!V2.isUndef()) {
2537     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2538     // If only one index is used, we can use a "splat" vrgather.
2539     // TODO: We can splat the most-common index and fix-up any stragglers, if
2540     // that's beneficial.
2541     if (RHSIndexCounts.size() == 1) {
2542       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2543       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2544                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2545     } else {
2546       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2547       RHSIndices =
2548           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2549       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2550                        VL);
2551     }
2552 
2553     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2554     SelectMask =
2555         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2556 
2557     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2558                          Gather, VL);
2559   }
2560 
2561   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2562 }
2563 
2564 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2565                                      SDLoc DL, SelectionDAG &DAG,
2566                                      const RISCVSubtarget &Subtarget) {
2567   if (VT.isScalableVector())
2568     return DAG.getFPExtendOrRound(Op, DL, VT);
2569   assert(VT.isFixedLengthVector() &&
2570          "Unexpected value type for RVV FP extend/round lowering");
2571   SDValue Mask, VL;
2572   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2573   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2574                         ? RISCVISD::FP_EXTEND_VL
2575                         : RISCVISD::FP_ROUND_VL;
2576   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2577 }
2578 
2579 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2580 // the exponent.
2581 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2582   MVT VT = Op.getSimpleValueType();
2583   unsigned EltSize = VT.getScalarSizeInBits();
2584   SDValue Src = Op.getOperand(0);
2585   SDLoc DL(Op);
2586 
2587   // We need a FP type that can represent the value.
2588   // TODO: Use f16 for i8 when possible?
2589   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2590   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2591 
2592   // Legal types should have been checked in the RISCVTargetLowering
2593   // constructor.
2594   // TODO: Splitting may make sense in some cases.
2595   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2596          "Expected legal float type!");
2597 
2598   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2599   // The trailing zero count is equal to log2 of this single bit value.
2600   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2601     SDValue Neg =
2602         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2603     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2604   }
2605 
2606   // We have a legal FP type, convert to it.
2607   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2608   // Bitcast to integer and shift the exponent to the LSB.
2609   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2610   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2611   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2612   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2613                               DAG.getConstant(ShiftAmt, DL, IntVT));
2614   // Truncate back to original type to allow vnsrl.
2615   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2616   // The exponent contains log2 of the value in biased form.
2617   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2618 
2619   // For trailing zeros, we just need to subtract the bias.
2620   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2621     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2622                        DAG.getConstant(ExponentBias, DL, VT));
2623 
2624   // For leading zeros, we need to remove the bias and convert from log2 to
2625   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2626   unsigned Adjust = ExponentBias + (EltSize - 1);
2627   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2628 }
2629 
2630 // While RVV has alignment restrictions, we should always be able to load as a
2631 // legal equivalently-sized byte-typed vector instead. This method is
2632 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2633 // the load is already correctly-aligned, it returns SDValue().
2634 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2635                                                     SelectionDAG &DAG) const {
2636   auto *Load = cast<LoadSDNode>(Op);
2637   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2638 
2639   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2640                                      Load->getMemoryVT(),
2641                                      *Load->getMemOperand()))
2642     return SDValue();
2643 
2644   SDLoc DL(Op);
2645   MVT VT = Op.getSimpleValueType();
2646   unsigned EltSizeBits = VT.getScalarSizeInBits();
2647   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2648          "Unexpected unaligned RVV load type");
2649   MVT NewVT =
2650       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2651   assert(NewVT.isValid() &&
2652          "Expecting equally-sized RVV vector types to be legal");
2653   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2654                           Load->getPointerInfo(), Load->getOriginalAlign(),
2655                           Load->getMemOperand()->getFlags());
2656   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2657 }
2658 
2659 // While RVV has alignment restrictions, we should always be able to store as a
2660 // legal equivalently-sized byte-typed vector instead. This method is
2661 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2662 // returns SDValue() if the store is already correctly aligned.
2663 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2664                                                      SelectionDAG &DAG) const {
2665   auto *Store = cast<StoreSDNode>(Op);
2666   assert(Store && Store->getValue().getValueType().isVector() &&
2667          "Expected vector store");
2668 
2669   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2670                                      Store->getMemoryVT(),
2671                                      *Store->getMemOperand()))
2672     return SDValue();
2673 
2674   SDLoc DL(Op);
2675   SDValue StoredVal = Store->getValue();
2676   MVT VT = StoredVal.getSimpleValueType();
2677   unsigned EltSizeBits = VT.getScalarSizeInBits();
2678   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2679          "Unexpected unaligned RVV store type");
2680   MVT NewVT =
2681       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2682   assert(NewVT.isValid() &&
2683          "Expecting equally-sized RVV vector types to be legal");
2684   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2685   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2686                       Store->getPointerInfo(), Store->getOriginalAlign(),
2687                       Store->getMemOperand()->getFlags());
2688 }
2689 
2690 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2691                                             SelectionDAG &DAG) const {
2692   switch (Op.getOpcode()) {
2693   default:
2694     report_fatal_error("unimplemented operand");
2695   case ISD::GlobalAddress:
2696     return lowerGlobalAddress(Op, DAG);
2697   case ISD::BlockAddress:
2698     return lowerBlockAddress(Op, DAG);
2699   case ISD::ConstantPool:
2700     return lowerConstantPool(Op, DAG);
2701   case ISD::JumpTable:
2702     return lowerJumpTable(Op, DAG);
2703   case ISD::GlobalTLSAddress:
2704     return lowerGlobalTLSAddress(Op, DAG);
2705   case ISD::SELECT:
2706     return lowerSELECT(Op, DAG);
2707   case ISD::BRCOND:
2708     return lowerBRCOND(Op, DAG);
2709   case ISD::VASTART:
2710     return lowerVASTART(Op, DAG);
2711   case ISD::FRAMEADDR:
2712     return lowerFRAMEADDR(Op, DAG);
2713   case ISD::RETURNADDR:
2714     return lowerRETURNADDR(Op, DAG);
2715   case ISD::SHL_PARTS:
2716     return lowerShiftLeftParts(Op, DAG);
2717   case ISD::SRA_PARTS:
2718     return lowerShiftRightParts(Op, DAG, true);
2719   case ISD::SRL_PARTS:
2720     return lowerShiftRightParts(Op, DAG, false);
2721   case ISD::BITCAST: {
2722     SDLoc DL(Op);
2723     EVT VT = Op.getValueType();
2724     SDValue Op0 = Op.getOperand(0);
2725     EVT Op0VT = Op0.getValueType();
2726     MVT XLenVT = Subtarget.getXLenVT();
2727     if (VT.isFixedLengthVector()) {
2728       // We can handle fixed length vector bitcasts with a simple replacement
2729       // in isel.
2730       if (Op0VT.isFixedLengthVector())
2731         return Op;
2732       // When bitcasting from scalar to fixed-length vector, insert the scalar
2733       // into a one-element vector of the result type, and perform a vector
2734       // bitcast.
2735       if (!Op0VT.isVector()) {
2736         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2737         if (!isTypeLegal(BVT))
2738           return SDValue();
2739         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2740                                               DAG.getUNDEF(BVT), Op0,
2741                                               DAG.getConstant(0, DL, XLenVT)));
2742       }
2743       return SDValue();
2744     }
2745     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2746     // thus: bitcast the vector to a one-element vector type whose element type
2747     // is the same as the result type, and extract the first element.
2748     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2749       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2750       if (!isTypeLegal(BVT))
2751         return SDValue();
2752       SDValue BVec = DAG.getBitcast(BVT, Op0);
2753       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2754                          DAG.getConstant(0, DL, XLenVT));
2755     }
2756     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2757       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2758       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2759       return FPConv;
2760     }
2761     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2762         Subtarget.hasStdExtF()) {
2763       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2764       SDValue FPConv =
2765           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2766       return FPConv;
2767     }
2768     return SDValue();
2769   }
2770   case ISD::INTRINSIC_WO_CHAIN:
2771     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2772   case ISD::INTRINSIC_W_CHAIN:
2773     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2774   case ISD::INTRINSIC_VOID:
2775     return LowerINTRINSIC_VOID(Op, DAG);
2776   case ISD::BSWAP:
2777   case ISD::BITREVERSE: {
2778     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2779     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2780     MVT VT = Op.getSimpleValueType();
2781     SDLoc DL(Op);
2782     // Start with the maximum immediate value which is the bitwidth - 1.
2783     unsigned Imm = VT.getSizeInBits() - 1;
2784     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2785     if (Op.getOpcode() == ISD::BSWAP)
2786       Imm &= ~0x7U;
2787     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2788                        DAG.getConstant(Imm, DL, VT));
2789   }
2790   case ISD::FSHL:
2791   case ISD::FSHR: {
2792     MVT VT = Op.getSimpleValueType();
2793     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2794     SDLoc DL(Op);
2795     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2796       return Op;
2797     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2798     // use log(XLen) bits. Mask the shift amount accordingly.
2799     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2800     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2801                                 DAG.getConstant(ShAmtWidth, DL, VT));
2802     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2803     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2804   }
2805   case ISD::TRUNCATE: {
2806     SDLoc DL(Op);
2807     MVT VT = Op.getSimpleValueType();
2808     // Only custom-lower vector truncates
2809     if (!VT.isVector())
2810       return Op;
2811 
2812     // Truncates to mask types are handled differently
2813     if (VT.getVectorElementType() == MVT::i1)
2814       return lowerVectorMaskTrunc(Op, DAG);
2815 
2816     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2817     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2818     // truncate by one power of two at a time.
2819     MVT DstEltVT = VT.getVectorElementType();
2820 
2821     SDValue Src = Op.getOperand(0);
2822     MVT SrcVT = Src.getSimpleValueType();
2823     MVT SrcEltVT = SrcVT.getVectorElementType();
2824 
2825     assert(DstEltVT.bitsLT(SrcEltVT) &&
2826            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2827            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2828            "Unexpected vector truncate lowering");
2829 
2830     MVT ContainerVT = SrcVT;
2831     if (SrcVT.isFixedLengthVector()) {
2832       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2833       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2834     }
2835 
2836     SDValue Result = Src;
2837     SDValue Mask, VL;
2838     std::tie(Mask, VL) =
2839         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2840     LLVMContext &Context = *DAG.getContext();
2841     const ElementCount Count = ContainerVT.getVectorElementCount();
2842     do {
2843       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2844       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2845       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2846                            Mask, VL);
2847     } while (SrcEltVT != DstEltVT);
2848 
2849     if (SrcVT.isFixedLengthVector())
2850       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2851 
2852     return Result;
2853   }
2854   case ISD::ANY_EXTEND:
2855   case ISD::ZERO_EXTEND:
2856     if (Op.getOperand(0).getValueType().isVector() &&
2857         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2858       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2859     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2860   case ISD::SIGN_EXTEND:
2861     if (Op.getOperand(0).getValueType().isVector() &&
2862         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2863       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2864     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2865   case ISD::SPLAT_VECTOR_PARTS:
2866     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2867   case ISD::INSERT_VECTOR_ELT:
2868     return lowerINSERT_VECTOR_ELT(Op, DAG);
2869   case ISD::EXTRACT_VECTOR_ELT:
2870     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2871   case ISD::VSCALE: {
2872     MVT VT = Op.getSimpleValueType();
2873     SDLoc DL(Op);
2874     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2875     // We define our scalable vector types for lmul=1 to use a 64 bit known
2876     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2877     // vscale as VLENB / 8.
2878     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
2879     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2880       // We assume VLENB is a multiple of 8. We manually choose the best shift
2881       // here because SimplifyDemandedBits isn't always able to simplify it.
2882       uint64_t Val = Op.getConstantOperandVal(0);
2883       if (isPowerOf2_64(Val)) {
2884         uint64_t Log2 = Log2_64(Val);
2885         if (Log2 < 3)
2886           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2887                              DAG.getConstant(3 - Log2, DL, VT));
2888         if (Log2 > 3)
2889           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2890                              DAG.getConstant(Log2 - 3, DL, VT));
2891         return VLENB;
2892       }
2893       // If the multiplier is a multiple of 8, scale it down to avoid needing
2894       // to shift the VLENB value.
2895       if ((Val % 8) == 0)
2896         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2897                            DAG.getConstant(Val / 8, DL, VT));
2898     }
2899 
2900     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2901                                  DAG.getConstant(3, DL, VT));
2902     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2903   }
2904   case ISD::FPOWI: {
2905     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
2906     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
2907     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
2908         Op.getOperand(1).getValueType() == MVT::i32) {
2909       SDLoc DL(Op);
2910       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
2911       SDValue Powi =
2912           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
2913       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
2914                          DAG.getIntPtrConstant(0, DL));
2915     }
2916     return SDValue();
2917   }
2918   case ISD::FP_EXTEND: {
2919     // RVV can only do fp_extend to types double the size as the source. We
2920     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2921     // via f32.
2922     SDLoc DL(Op);
2923     MVT VT = Op.getSimpleValueType();
2924     SDValue Src = Op.getOperand(0);
2925     MVT SrcVT = Src.getSimpleValueType();
2926 
2927     // Prepare any fixed-length vector operands.
2928     MVT ContainerVT = VT;
2929     if (SrcVT.isFixedLengthVector()) {
2930       ContainerVT = getContainerForFixedLengthVector(VT);
2931       MVT SrcContainerVT =
2932           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2933       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2934     }
2935 
2936     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2937         SrcVT.getVectorElementType() != MVT::f16) {
2938       // For scalable vectors, we only need to close the gap between
2939       // vXf16->vXf64.
2940       if (!VT.isFixedLengthVector())
2941         return Op;
2942       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2943       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2944       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2945     }
2946 
2947     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2948     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2949     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2950         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2951 
2952     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2953                                            DL, DAG, Subtarget);
2954     if (VT.isFixedLengthVector())
2955       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2956     return Extend;
2957   }
2958   case ISD::FP_ROUND: {
2959     // RVV can only do fp_round to types half the size as the source. We
2960     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2961     // conversion instruction.
2962     SDLoc DL(Op);
2963     MVT VT = Op.getSimpleValueType();
2964     SDValue Src = Op.getOperand(0);
2965     MVT SrcVT = Src.getSimpleValueType();
2966 
2967     // Prepare any fixed-length vector operands.
2968     MVT ContainerVT = VT;
2969     if (VT.isFixedLengthVector()) {
2970       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2971       ContainerVT =
2972           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2973       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2974     }
2975 
2976     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2977         SrcVT.getVectorElementType() != MVT::f64) {
2978       // For scalable vectors, we only need to close the gap between
2979       // vXf64<->vXf16.
2980       if (!VT.isFixedLengthVector())
2981         return Op;
2982       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2983       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2984       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2985     }
2986 
2987     SDValue Mask, VL;
2988     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2989 
2990     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2991     SDValue IntermediateRound =
2992         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2993     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2994                                           DL, DAG, Subtarget);
2995 
2996     if (VT.isFixedLengthVector())
2997       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2998     return Round;
2999   }
3000   case ISD::FP_TO_SINT:
3001   case ISD::FP_TO_UINT:
3002   case ISD::SINT_TO_FP:
3003   case ISD::UINT_TO_FP: {
3004     // RVV can only do fp<->int conversions to types half/double the size as
3005     // the source. We custom-lower any conversions that do two hops into
3006     // sequences.
3007     MVT VT = Op.getSimpleValueType();
3008     if (!VT.isVector())
3009       return Op;
3010     SDLoc DL(Op);
3011     SDValue Src = Op.getOperand(0);
3012     MVT EltVT = VT.getVectorElementType();
3013     MVT SrcVT = Src.getSimpleValueType();
3014     MVT SrcEltVT = SrcVT.getVectorElementType();
3015     unsigned EltSize = EltVT.getSizeInBits();
3016     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3017     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3018            "Unexpected vector element types");
3019 
3020     bool IsInt2FP = SrcEltVT.isInteger();
3021     // Widening conversions
3022     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3023       if (IsInt2FP) {
3024         // Do a regular integer sign/zero extension then convert to float.
3025         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3026                                       VT.getVectorElementCount());
3027         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3028                                  ? ISD::ZERO_EXTEND
3029                                  : ISD::SIGN_EXTEND;
3030         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3031         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3032       }
3033       // FP2Int
3034       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3035       // Do one doubling fp_extend then complete the operation by converting
3036       // to int.
3037       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3038       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3039       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3040     }
3041 
3042     // Narrowing conversions
3043     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3044       if (IsInt2FP) {
3045         // One narrowing int_to_fp, then an fp_round.
3046         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3047         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3048         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3049         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3050       }
3051       // FP2Int
3052       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3053       // representable by the integer, the result is poison.
3054       MVT IVecVT =
3055           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3056                            VT.getVectorElementCount());
3057       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3058       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3059     }
3060 
3061     // Scalable vectors can exit here. Patterns will handle equally-sized
3062     // conversions halving/doubling ones.
3063     if (!VT.isFixedLengthVector())
3064       return Op;
3065 
3066     // For fixed-length vectors we lower to a custom "VL" node.
3067     unsigned RVVOpc = 0;
3068     switch (Op.getOpcode()) {
3069     default:
3070       llvm_unreachable("Impossible opcode");
3071     case ISD::FP_TO_SINT:
3072       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3073       break;
3074     case ISD::FP_TO_UINT:
3075       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3076       break;
3077     case ISD::SINT_TO_FP:
3078       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3079       break;
3080     case ISD::UINT_TO_FP:
3081       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3082       break;
3083     }
3084 
3085     MVT ContainerVT, SrcContainerVT;
3086     // Derive the reference container type from the larger vector type.
3087     if (SrcEltSize > EltSize) {
3088       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3089       ContainerVT =
3090           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3091     } else {
3092       ContainerVT = getContainerForFixedLengthVector(VT);
3093       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3094     }
3095 
3096     SDValue Mask, VL;
3097     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3098 
3099     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3100     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3101     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3102   }
3103   case ISD::FP_TO_SINT_SAT:
3104   case ISD::FP_TO_UINT_SAT:
3105     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3106   case ISD::FTRUNC:
3107   case ISD::FCEIL:
3108   case ISD::FFLOOR:
3109     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3110   case ISD::VECREDUCE_ADD:
3111   case ISD::VECREDUCE_UMAX:
3112   case ISD::VECREDUCE_SMAX:
3113   case ISD::VECREDUCE_UMIN:
3114   case ISD::VECREDUCE_SMIN:
3115     return lowerVECREDUCE(Op, DAG);
3116   case ISD::VECREDUCE_AND:
3117   case ISD::VECREDUCE_OR:
3118   case ISD::VECREDUCE_XOR:
3119     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3120       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3121     return lowerVECREDUCE(Op, DAG);
3122   case ISD::VECREDUCE_FADD:
3123   case ISD::VECREDUCE_SEQ_FADD:
3124   case ISD::VECREDUCE_FMIN:
3125   case ISD::VECREDUCE_FMAX:
3126     return lowerFPVECREDUCE(Op, DAG);
3127   case ISD::VP_REDUCE_ADD:
3128   case ISD::VP_REDUCE_UMAX:
3129   case ISD::VP_REDUCE_SMAX:
3130   case ISD::VP_REDUCE_UMIN:
3131   case ISD::VP_REDUCE_SMIN:
3132   case ISD::VP_REDUCE_FADD:
3133   case ISD::VP_REDUCE_SEQ_FADD:
3134   case ISD::VP_REDUCE_FMIN:
3135   case ISD::VP_REDUCE_FMAX:
3136     return lowerVPREDUCE(Op, DAG);
3137   case ISD::VP_REDUCE_AND:
3138   case ISD::VP_REDUCE_OR:
3139   case ISD::VP_REDUCE_XOR:
3140     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3141       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3142     return lowerVPREDUCE(Op, DAG);
3143   case ISD::INSERT_SUBVECTOR:
3144     return lowerINSERT_SUBVECTOR(Op, DAG);
3145   case ISD::EXTRACT_SUBVECTOR:
3146     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3147   case ISD::STEP_VECTOR:
3148     return lowerSTEP_VECTOR(Op, DAG);
3149   case ISD::VECTOR_REVERSE:
3150     return lowerVECTOR_REVERSE(Op, DAG);
3151   case ISD::BUILD_VECTOR:
3152     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3153   case ISD::SPLAT_VECTOR:
3154     if (Op.getValueType().getVectorElementType() == MVT::i1)
3155       return lowerVectorMaskSplat(Op, DAG);
3156     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3157   case ISD::VECTOR_SHUFFLE:
3158     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3159   case ISD::CONCAT_VECTORS: {
3160     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3161     // better than going through the stack, as the default expansion does.
3162     SDLoc DL(Op);
3163     MVT VT = Op.getSimpleValueType();
3164     unsigned NumOpElts =
3165         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3166     SDValue Vec = DAG.getUNDEF(VT);
3167     for (const auto &OpIdx : enumerate(Op->ops()))
3168       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
3169                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3170     return Vec;
3171   }
3172   case ISD::LOAD:
3173     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3174       return V;
3175     if (Op.getValueType().isFixedLengthVector())
3176       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3177     return Op;
3178   case ISD::STORE:
3179     if (auto V = expandUnalignedRVVStore(Op, DAG))
3180       return V;
3181     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3182       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3183     return Op;
3184   case ISD::MLOAD:
3185   case ISD::VP_LOAD:
3186     return lowerMaskedLoad(Op, DAG);
3187   case ISD::MSTORE:
3188   case ISD::VP_STORE:
3189     return lowerMaskedStore(Op, DAG);
3190   case ISD::SETCC:
3191     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3192   case ISD::ADD:
3193     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3194   case ISD::SUB:
3195     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3196   case ISD::MUL:
3197     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3198   case ISD::MULHS:
3199     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3200   case ISD::MULHU:
3201     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3202   case ISD::AND:
3203     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3204                                               RISCVISD::AND_VL);
3205   case ISD::OR:
3206     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3207                                               RISCVISD::OR_VL);
3208   case ISD::XOR:
3209     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3210                                               RISCVISD::XOR_VL);
3211   case ISD::SDIV:
3212     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3213   case ISD::SREM:
3214     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3215   case ISD::UDIV:
3216     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3217   case ISD::UREM:
3218     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3219   case ISD::SHL:
3220   case ISD::SRA:
3221   case ISD::SRL:
3222     if (Op.getSimpleValueType().isFixedLengthVector())
3223       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3224     // This can be called for an i32 shift amount that needs to be promoted.
3225     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3226            "Unexpected custom legalisation");
3227     return SDValue();
3228   case ISD::SADDSAT:
3229     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3230   case ISD::UADDSAT:
3231     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3232   case ISD::SSUBSAT:
3233     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3234   case ISD::USUBSAT:
3235     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3236   case ISD::FADD:
3237     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3238   case ISD::FSUB:
3239     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3240   case ISD::FMUL:
3241     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3242   case ISD::FDIV:
3243     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3244   case ISD::FNEG:
3245     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3246   case ISD::FABS:
3247     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3248   case ISD::FSQRT:
3249     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3250   case ISD::FMA:
3251     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3252   case ISD::SMIN:
3253     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3254   case ISD::SMAX:
3255     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3256   case ISD::UMIN:
3257     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3258   case ISD::UMAX:
3259     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3260   case ISD::FMINNUM:
3261     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3262   case ISD::FMAXNUM:
3263     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3264   case ISD::ABS:
3265     return lowerABS(Op, DAG);
3266   case ISD::CTLZ_ZERO_UNDEF:
3267   case ISD::CTTZ_ZERO_UNDEF:
3268     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3269   case ISD::VSELECT:
3270     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3271   case ISD::FCOPYSIGN:
3272     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3273   case ISD::MGATHER:
3274   case ISD::VP_GATHER:
3275     return lowerMaskedGather(Op, DAG);
3276   case ISD::MSCATTER:
3277   case ISD::VP_SCATTER:
3278     return lowerMaskedScatter(Op, DAG);
3279   case ISD::FLT_ROUNDS_:
3280     return lowerGET_ROUNDING(Op, DAG);
3281   case ISD::SET_ROUNDING:
3282     return lowerSET_ROUNDING(Op, DAG);
3283   case ISD::VP_SELECT:
3284     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3285   case ISD::VP_ADD:
3286     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3287   case ISD::VP_SUB:
3288     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3289   case ISD::VP_MUL:
3290     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3291   case ISD::VP_SDIV:
3292     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3293   case ISD::VP_UDIV:
3294     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3295   case ISD::VP_SREM:
3296     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3297   case ISD::VP_UREM:
3298     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3299   case ISD::VP_AND:
3300     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3301   case ISD::VP_OR:
3302     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3303   case ISD::VP_XOR:
3304     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3305   case ISD::VP_ASHR:
3306     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3307   case ISD::VP_LSHR:
3308     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3309   case ISD::VP_SHL:
3310     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3311   case ISD::VP_FADD:
3312     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3313   case ISD::VP_FSUB:
3314     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3315   case ISD::VP_FMUL:
3316     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3317   case ISD::VP_FDIV:
3318     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3319   }
3320 }
3321 
3322 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3323                              SelectionDAG &DAG, unsigned Flags) {
3324   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3325 }
3326 
3327 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3328                              SelectionDAG &DAG, unsigned Flags) {
3329   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3330                                    Flags);
3331 }
3332 
3333 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3334                              SelectionDAG &DAG, unsigned Flags) {
3335   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3336                                    N->getOffset(), Flags);
3337 }
3338 
3339 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3340                              SelectionDAG &DAG, unsigned Flags) {
3341   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3342 }
3343 
3344 template <class NodeTy>
3345 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3346                                      bool IsLocal) const {
3347   SDLoc DL(N);
3348   EVT Ty = getPointerTy(DAG.getDataLayout());
3349 
3350   if (isPositionIndependent()) {
3351     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3352     if (IsLocal)
3353       // Use PC-relative addressing to access the symbol. This generates the
3354       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3355       // %pcrel_lo(auipc)).
3356       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3357 
3358     // Use PC-relative addressing to access the GOT for this symbol, then load
3359     // the address from the GOT. This generates the pattern (PseudoLA sym),
3360     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3361     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3362   }
3363 
3364   switch (getTargetMachine().getCodeModel()) {
3365   default:
3366     report_fatal_error("Unsupported code model for lowering");
3367   case CodeModel::Small: {
3368     // Generate a sequence for accessing addresses within the first 2 GiB of
3369     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3370     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3371     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3372     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3373     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3374   }
3375   case CodeModel::Medium: {
3376     // Generate a sequence for accessing addresses within any 2GiB range within
3377     // the address space. This generates the pattern (PseudoLLA sym), which
3378     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3379     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3380     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3381   }
3382   }
3383 }
3384 
3385 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3386                                                 SelectionDAG &DAG) const {
3387   SDLoc DL(Op);
3388   EVT Ty = Op.getValueType();
3389   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3390   int64_t Offset = N->getOffset();
3391   MVT XLenVT = Subtarget.getXLenVT();
3392 
3393   const GlobalValue *GV = N->getGlobal();
3394   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3395   SDValue Addr = getAddr(N, DAG, IsLocal);
3396 
3397   // In order to maximise the opportunity for common subexpression elimination,
3398   // emit a separate ADD node for the global address offset instead of folding
3399   // it in the global address node. Later peephole optimisations may choose to
3400   // fold it back in when profitable.
3401   if (Offset != 0)
3402     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3403                        DAG.getConstant(Offset, DL, XLenVT));
3404   return Addr;
3405 }
3406 
3407 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3408                                                SelectionDAG &DAG) const {
3409   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3410 
3411   return getAddr(N, DAG);
3412 }
3413 
3414 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3415                                                SelectionDAG &DAG) const {
3416   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3417 
3418   return getAddr(N, DAG);
3419 }
3420 
3421 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3422                                             SelectionDAG &DAG) const {
3423   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3424 
3425   return getAddr(N, DAG);
3426 }
3427 
3428 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3429                                               SelectionDAG &DAG,
3430                                               bool UseGOT) const {
3431   SDLoc DL(N);
3432   EVT Ty = getPointerTy(DAG.getDataLayout());
3433   const GlobalValue *GV = N->getGlobal();
3434   MVT XLenVT = Subtarget.getXLenVT();
3435 
3436   if (UseGOT) {
3437     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3438     // load the address from the GOT and add the thread pointer. This generates
3439     // the pattern (PseudoLA_TLS_IE sym), which expands to
3440     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3441     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3442     SDValue Load =
3443         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3444 
3445     // Add the thread pointer.
3446     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3447     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3448   }
3449 
3450   // Generate a sequence for accessing the address relative to the thread
3451   // pointer, with the appropriate adjustment for the thread pointer offset.
3452   // This generates the pattern
3453   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3454   SDValue AddrHi =
3455       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3456   SDValue AddrAdd =
3457       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3458   SDValue AddrLo =
3459       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3460 
3461   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3462   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3463   SDValue MNAdd = SDValue(
3464       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3465       0);
3466   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3467 }
3468 
3469 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3470                                                SelectionDAG &DAG) const {
3471   SDLoc DL(N);
3472   EVT Ty = getPointerTy(DAG.getDataLayout());
3473   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3474   const GlobalValue *GV = N->getGlobal();
3475 
3476   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3477   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3478   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3479   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3480   SDValue Load =
3481       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3482 
3483   // Prepare argument list to generate call.
3484   ArgListTy Args;
3485   ArgListEntry Entry;
3486   Entry.Node = Load;
3487   Entry.Ty = CallTy;
3488   Args.push_back(Entry);
3489 
3490   // Setup call to __tls_get_addr.
3491   TargetLowering::CallLoweringInfo CLI(DAG);
3492   CLI.setDebugLoc(DL)
3493       .setChain(DAG.getEntryNode())
3494       .setLibCallee(CallingConv::C, CallTy,
3495                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3496                     std::move(Args));
3497 
3498   return LowerCallTo(CLI).first;
3499 }
3500 
3501 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3502                                                    SelectionDAG &DAG) const {
3503   SDLoc DL(Op);
3504   EVT Ty = Op.getValueType();
3505   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3506   int64_t Offset = N->getOffset();
3507   MVT XLenVT = Subtarget.getXLenVT();
3508 
3509   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3510 
3511   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3512       CallingConv::GHC)
3513     report_fatal_error("In GHC calling convention TLS is not supported");
3514 
3515   SDValue Addr;
3516   switch (Model) {
3517   case TLSModel::LocalExec:
3518     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3519     break;
3520   case TLSModel::InitialExec:
3521     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3522     break;
3523   case TLSModel::LocalDynamic:
3524   case TLSModel::GeneralDynamic:
3525     Addr = getDynamicTLSAddr(N, DAG);
3526     break;
3527   }
3528 
3529   // In order to maximise the opportunity for common subexpression elimination,
3530   // emit a separate ADD node for the global address offset instead of folding
3531   // it in the global address node. Later peephole optimisations may choose to
3532   // fold it back in when profitable.
3533   if (Offset != 0)
3534     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3535                        DAG.getConstant(Offset, DL, XLenVT));
3536   return Addr;
3537 }
3538 
3539 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3540   SDValue CondV = Op.getOperand(0);
3541   SDValue TrueV = Op.getOperand(1);
3542   SDValue FalseV = Op.getOperand(2);
3543   SDLoc DL(Op);
3544   MVT VT = Op.getSimpleValueType();
3545   MVT XLenVT = Subtarget.getXLenVT();
3546 
3547   // Lower vector SELECTs to VSELECTs by splatting the condition.
3548   if (VT.isVector()) {
3549     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3550     SDValue CondSplat = VT.isScalableVector()
3551                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3552                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3553     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3554   }
3555 
3556   // If the result type is XLenVT and CondV is the output of a SETCC node
3557   // which also operated on XLenVT inputs, then merge the SETCC node into the
3558   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3559   // compare+branch instructions. i.e.:
3560   // (select (setcc lhs, rhs, cc), truev, falsev)
3561   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3562   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3563       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3564     SDValue LHS = CondV.getOperand(0);
3565     SDValue RHS = CondV.getOperand(1);
3566     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3567     ISD::CondCode CCVal = CC->get();
3568 
3569     // Special case for a select of 2 constants that have a diffence of 1.
3570     // Normally this is done by DAGCombine, but if the select is introduced by
3571     // type legalization or op legalization, we miss it. Restricting to SETLT
3572     // case for now because that is what signed saturating add/sub need.
3573     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3574     // but we would probably want to swap the true/false values if the condition
3575     // is SETGE/SETLE to avoid an XORI.
3576     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3577         CCVal == ISD::SETLT) {
3578       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3579       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3580       if (TrueVal - 1 == FalseVal)
3581         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3582       if (TrueVal + 1 == FalseVal)
3583         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3584     }
3585 
3586     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3587 
3588     SDValue TargetCC = DAG.getCondCode(CCVal);
3589     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3590     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3591   }
3592 
3593   // Otherwise:
3594   // (select condv, truev, falsev)
3595   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3596   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3597   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3598 
3599   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3600 
3601   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3602 }
3603 
3604 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3605   SDValue CondV = Op.getOperand(1);
3606   SDLoc DL(Op);
3607   MVT XLenVT = Subtarget.getXLenVT();
3608 
3609   if (CondV.getOpcode() == ISD::SETCC &&
3610       CondV.getOperand(0).getValueType() == XLenVT) {
3611     SDValue LHS = CondV.getOperand(0);
3612     SDValue RHS = CondV.getOperand(1);
3613     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3614 
3615     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3616 
3617     SDValue TargetCC = DAG.getCondCode(CCVal);
3618     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3619                        LHS, RHS, TargetCC, Op.getOperand(2));
3620   }
3621 
3622   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3623                      CondV, DAG.getConstant(0, DL, XLenVT),
3624                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3625 }
3626 
3627 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3628   MachineFunction &MF = DAG.getMachineFunction();
3629   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3630 
3631   SDLoc DL(Op);
3632   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3633                                  getPointerTy(MF.getDataLayout()));
3634 
3635   // vastart just stores the address of the VarArgsFrameIndex slot into the
3636   // memory location argument.
3637   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3638   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3639                       MachinePointerInfo(SV));
3640 }
3641 
3642 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3643                                             SelectionDAG &DAG) const {
3644   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3645   MachineFunction &MF = DAG.getMachineFunction();
3646   MachineFrameInfo &MFI = MF.getFrameInfo();
3647   MFI.setFrameAddressIsTaken(true);
3648   Register FrameReg = RI.getFrameRegister(MF);
3649   int XLenInBytes = Subtarget.getXLen() / 8;
3650 
3651   EVT VT = Op.getValueType();
3652   SDLoc DL(Op);
3653   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3654   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3655   while (Depth--) {
3656     int Offset = -(XLenInBytes * 2);
3657     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3658                               DAG.getIntPtrConstant(Offset, DL));
3659     FrameAddr =
3660         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3661   }
3662   return FrameAddr;
3663 }
3664 
3665 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3666                                              SelectionDAG &DAG) const {
3667   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3668   MachineFunction &MF = DAG.getMachineFunction();
3669   MachineFrameInfo &MFI = MF.getFrameInfo();
3670   MFI.setReturnAddressIsTaken(true);
3671   MVT XLenVT = Subtarget.getXLenVT();
3672   int XLenInBytes = Subtarget.getXLen() / 8;
3673 
3674   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3675     return SDValue();
3676 
3677   EVT VT = Op.getValueType();
3678   SDLoc DL(Op);
3679   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3680   if (Depth) {
3681     int Off = -XLenInBytes;
3682     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3683     SDValue Offset = DAG.getConstant(Off, DL, VT);
3684     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3685                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3686                        MachinePointerInfo());
3687   }
3688 
3689   // Return the value of the return address register, marking it an implicit
3690   // live-in.
3691   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3692   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3693 }
3694 
3695 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3696                                                  SelectionDAG &DAG) const {
3697   SDLoc DL(Op);
3698   SDValue Lo = Op.getOperand(0);
3699   SDValue Hi = Op.getOperand(1);
3700   SDValue Shamt = Op.getOperand(2);
3701   EVT VT = Lo.getValueType();
3702 
3703   // if Shamt-XLEN < 0: // Shamt < XLEN
3704   //   Lo = Lo << Shamt
3705   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3706   // else:
3707   //   Lo = 0
3708   //   Hi = Lo << (Shamt-XLEN)
3709 
3710   SDValue Zero = DAG.getConstant(0, DL, VT);
3711   SDValue One = DAG.getConstant(1, DL, VT);
3712   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3713   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3714   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3715   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3716 
3717   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3718   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3719   SDValue ShiftRightLo =
3720       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3721   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3722   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3723   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3724 
3725   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3726 
3727   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3728   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3729 
3730   SDValue Parts[2] = {Lo, Hi};
3731   return DAG.getMergeValues(Parts, DL);
3732 }
3733 
3734 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3735                                                   bool IsSRA) const {
3736   SDLoc DL(Op);
3737   SDValue Lo = Op.getOperand(0);
3738   SDValue Hi = Op.getOperand(1);
3739   SDValue Shamt = Op.getOperand(2);
3740   EVT VT = Lo.getValueType();
3741 
3742   // SRA expansion:
3743   //   if Shamt-XLEN < 0: // Shamt < XLEN
3744   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3745   //     Hi = Hi >>s Shamt
3746   //   else:
3747   //     Lo = Hi >>s (Shamt-XLEN);
3748   //     Hi = Hi >>s (XLEN-1)
3749   //
3750   // SRL expansion:
3751   //   if Shamt-XLEN < 0: // Shamt < XLEN
3752   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3753   //     Hi = Hi >>u Shamt
3754   //   else:
3755   //     Lo = Hi >>u (Shamt-XLEN);
3756   //     Hi = 0;
3757 
3758   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3759 
3760   SDValue Zero = DAG.getConstant(0, DL, VT);
3761   SDValue One = DAG.getConstant(1, DL, VT);
3762   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3763   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3764   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3765   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3766 
3767   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3768   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3769   SDValue ShiftLeftHi =
3770       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3771   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3772   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3773   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3774   SDValue HiFalse =
3775       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3776 
3777   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3778 
3779   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3780   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3781 
3782   SDValue Parts[2] = {Lo, Hi};
3783   return DAG.getMergeValues(Parts, DL);
3784 }
3785 
3786 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3787 // legal equivalently-sized i8 type, so we can use that as a go-between.
3788 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3789                                                   SelectionDAG &DAG) const {
3790   SDLoc DL(Op);
3791   MVT VT = Op.getSimpleValueType();
3792   SDValue SplatVal = Op.getOperand(0);
3793   // All-zeros or all-ones splats are handled specially.
3794   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3795     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3796     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3797   }
3798   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3799     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3800     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3801   }
3802   MVT XLenVT = Subtarget.getXLenVT();
3803   assert(SplatVal.getValueType() == XLenVT &&
3804          "Unexpected type for i1 splat value");
3805   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3806   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3807                          DAG.getConstant(1, DL, XLenVT));
3808   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3809   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3810   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3811 }
3812 
3813 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3814 // illegal (currently only vXi64 RV32).
3815 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3816 // them to SPLAT_VECTOR_I64
3817 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3818                                                      SelectionDAG &DAG) const {
3819   SDLoc DL(Op);
3820   MVT VecVT = Op.getSimpleValueType();
3821   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3822          "Unexpected SPLAT_VECTOR_PARTS lowering");
3823 
3824   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3825   SDValue Lo = Op.getOperand(0);
3826   SDValue Hi = Op.getOperand(1);
3827 
3828   if (VecVT.isFixedLengthVector()) {
3829     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3830     SDLoc DL(Op);
3831     SDValue Mask, VL;
3832     std::tie(Mask, VL) =
3833         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3834 
3835     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3836     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3837   }
3838 
3839   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3840     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3841     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3842     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3843     // node in order to try and match RVV vector/scalar instructions.
3844     if ((LoC >> 31) == HiC)
3845       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3846   }
3847 
3848   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3849   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3850       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3851       Hi.getConstantOperandVal(1) == 31)
3852     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3853 
3854   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3855   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3856                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
3857 }
3858 
3859 // Custom-lower extensions from mask vectors by using a vselect either with 1
3860 // for zero/any-extension or -1 for sign-extension:
3861 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3862 // Note that any-extension is lowered identically to zero-extension.
3863 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3864                                                 int64_t ExtTrueVal) const {
3865   SDLoc DL(Op);
3866   MVT VecVT = Op.getSimpleValueType();
3867   SDValue Src = Op.getOperand(0);
3868   // Only custom-lower extensions from mask types
3869   assert(Src.getValueType().isVector() &&
3870          Src.getValueType().getVectorElementType() == MVT::i1);
3871 
3872   MVT XLenVT = Subtarget.getXLenVT();
3873   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3874   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3875 
3876   if (VecVT.isScalableVector()) {
3877     // Be careful not to introduce illegal scalar types at this stage, and be
3878     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3879     // illegal and must be expanded. Since we know that the constants are
3880     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3881     bool IsRV32E64 =
3882         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3883 
3884     if (!IsRV32E64) {
3885       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3886       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3887     } else {
3888       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3889       SplatTrueVal =
3890           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3891     }
3892 
3893     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3894   }
3895 
3896   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3897   MVT I1ContainerVT =
3898       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3899 
3900   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3901 
3902   SDValue Mask, VL;
3903   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3904 
3905   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3906   SplatTrueVal =
3907       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3908   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3909                                SplatTrueVal, SplatZero, VL);
3910 
3911   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3912 }
3913 
3914 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3915     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3916   MVT ExtVT = Op.getSimpleValueType();
3917   // Only custom-lower extensions from fixed-length vector types.
3918   if (!ExtVT.isFixedLengthVector())
3919     return Op;
3920   MVT VT = Op.getOperand(0).getSimpleValueType();
3921   // Grab the canonical container type for the extended type. Infer the smaller
3922   // type from that to ensure the same number of vector elements, as we know
3923   // the LMUL will be sufficient to hold the smaller type.
3924   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3925   // Get the extended container type manually to ensure the same number of
3926   // vector elements between source and dest.
3927   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3928                                      ContainerExtVT.getVectorElementCount());
3929 
3930   SDValue Op1 =
3931       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3932 
3933   SDLoc DL(Op);
3934   SDValue Mask, VL;
3935   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3936 
3937   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3938 
3939   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3940 }
3941 
3942 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3943 // setcc operation:
3944 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3945 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3946                                                   SelectionDAG &DAG) const {
3947   SDLoc DL(Op);
3948   EVT MaskVT = Op.getValueType();
3949   // Only expect to custom-lower truncations to mask types
3950   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3951          "Unexpected type for vector mask lowering");
3952   SDValue Src = Op.getOperand(0);
3953   MVT VecVT = Src.getSimpleValueType();
3954 
3955   // If this is a fixed vector, we need to convert it to a scalable vector.
3956   MVT ContainerVT = VecVT;
3957   if (VecVT.isFixedLengthVector()) {
3958     ContainerVT = getContainerForFixedLengthVector(VecVT);
3959     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3960   }
3961 
3962   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3963   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3964 
3965   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3966   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3967 
3968   if (VecVT.isScalableVector()) {
3969     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3970     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3971   }
3972 
3973   SDValue Mask, VL;
3974   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3975 
3976   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3977   SDValue Trunc =
3978       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3979   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3980                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3981   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3982 }
3983 
3984 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3985 // first position of a vector, and that vector is slid up to the insert index.
3986 // By limiting the active vector length to index+1 and merging with the
3987 // original vector (with an undisturbed tail policy for elements >= VL), we
3988 // achieve the desired result of leaving all elements untouched except the one
3989 // at VL-1, which is replaced with the desired value.
3990 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3991                                                     SelectionDAG &DAG) const {
3992   SDLoc DL(Op);
3993   MVT VecVT = Op.getSimpleValueType();
3994   SDValue Vec = Op.getOperand(0);
3995   SDValue Val = Op.getOperand(1);
3996   SDValue Idx = Op.getOperand(2);
3997 
3998   if (VecVT.getVectorElementType() == MVT::i1) {
3999     // FIXME: For now we just promote to an i8 vector and insert into that,
4000     // but this is probably not optimal.
4001     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4002     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4003     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4004     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4005   }
4006 
4007   MVT ContainerVT = VecVT;
4008   // If the operand is a fixed-length vector, convert to a scalable one.
4009   if (VecVT.isFixedLengthVector()) {
4010     ContainerVT = getContainerForFixedLengthVector(VecVT);
4011     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4012   }
4013 
4014   MVT XLenVT = Subtarget.getXLenVT();
4015 
4016   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4017   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4018   // Even i64-element vectors on RV32 can be lowered without scalar
4019   // legalization if the most-significant 32 bits of the value are not affected
4020   // by the sign-extension of the lower 32 bits.
4021   // TODO: We could also catch sign extensions of a 32-bit value.
4022   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4023     const auto *CVal = cast<ConstantSDNode>(Val);
4024     if (isInt<32>(CVal->getSExtValue())) {
4025       IsLegalInsert = true;
4026       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4027     }
4028   }
4029 
4030   SDValue Mask, VL;
4031   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4032 
4033   SDValue ValInVec;
4034 
4035   if (IsLegalInsert) {
4036     unsigned Opc =
4037         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4038     if (isNullConstant(Idx)) {
4039       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4040       if (!VecVT.isFixedLengthVector())
4041         return Vec;
4042       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4043     }
4044     ValInVec =
4045         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4046   } else {
4047     // On RV32, i64-element vectors must be specially handled to place the
4048     // value at element 0, by using two vslide1up instructions in sequence on
4049     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4050     // this.
4051     SDValue One = DAG.getConstant(1, DL, XLenVT);
4052     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4053     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4054     MVT I32ContainerVT =
4055         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4056     SDValue I32Mask =
4057         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4058     // Limit the active VL to two.
4059     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4060     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4061     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4062     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4063                            InsertI64VL);
4064     // First slide in the hi value, then the lo in underneath it.
4065     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4066                            ValHi, I32Mask, InsertI64VL);
4067     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4068                            ValLo, I32Mask, InsertI64VL);
4069     // Bitcast back to the right container type.
4070     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4071   }
4072 
4073   // Now that the value is in a vector, slide it into position.
4074   SDValue InsertVL =
4075       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4076   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4077                                 ValInVec, Idx, Mask, InsertVL);
4078   if (!VecVT.isFixedLengthVector())
4079     return Slideup;
4080   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4081 }
4082 
4083 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4084 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4085 // types this is done using VMV_X_S to allow us to glean information about the
4086 // sign bits of the result.
4087 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4088                                                      SelectionDAG &DAG) const {
4089   SDLoc DL(Op);
4090   SDValue Idx = Op.getOperand(1);
4091   SDValue Vec = Op.getOperand(0);
4092   EVT EltVT = Op.getValueType();
4093   MVT VecVT = Vec.getSimpleValueType();
4094   MVT XLenVT = Subtarget.getXLenVT();
4095 
4096   if (VecVT.getVectorElementType() == MVT::i1) {
4097     // FIXME: For now we just promote to an i8 vector and extract from that,
4098     // but this is probably not optimal.
4099     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4100     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4101     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4102   }
4103 
4104   // If this is a fixed vector, we need to convert it to a scalable vector.
4105   MVT ContainerVT = VecVT;
4106   if (VecVT.isFixedLengthVector()) {
4107     ContainerVT = getContainerForFixedLengthVector(VecVT);
4108     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4109   }
4110 
4111   // If the index is 0, the vector is already in the right position.
4112   if (!isNullConstant(Idx)) {
4113     // Use a VL of 1 to avoid processing more elements than we need.
4114     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4115     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4116     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4117     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4118                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4119   }
4120 
4121   if (!EltVT.isInteger()) {
4122     // Floating-point extracts are handled in TableGen.
4123     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4124                        DAG.getConstant(0, DL, XLenVT));
4125   }
4126 
4127   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4128   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4129 }
4130 
4131 // Some RVV intrinsics may claim that they want an integer operand to be
4132 // promoted or expanded.
4133 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4134                                           const RISCVSubtarget &Subtarget) {
4135   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4136           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4137          "Unexpected opcode");
4138 
4139   if (!Subtarget.hasVInstructions())
4140     return SDValue();
4141 
4142   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4143   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4144   SDLoc DL(Op);
4145 
4146   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4147       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4148   if (!II || !II->SplatOperand)
4149     return SDValue();
4150 
4151   unsigned SplatOp = II->SplatOperand + HasChain;
4152   assert(SplatOp < Op.getNumOperands());
4153 
4154   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4155   SDValue &ScalarOp = Operands[SplatOp];
4156   MVT OpVT = ScalarOp.getSimpleValueType();
4157   MVT XLenVT = Subtarget.getXLenVT();
4158 
4159   // If this isn't a scalar, or its type is XLenVT we're done.
4160   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4161     return SDValue();
4162 
4163   // Simplest case is that the operand needs to be promoted to XLenVT.
4164   if (OpVT.bitsLT(XLenVT)) {
4165     // If the operand is a constant, sign extend to increase our chances
4166     // of being able to use a .vi instruction. ANY_EXTEND would become a
4167     // a zero extend and the simm5 check in isel would fail.
4168     // FIXME: Should we ignore the upper bits in isel instead?
4169     unsigned ExtOpc =
4170         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4171     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4172     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4173   }
4174 
4175   // Use the previous operand to get the vXi64 VT. The result might be a mask
4176   // VT for compares. Using the previous operand assumes that the previous
4177   // operand will never have a smaller element size than a scalar operand and
4178   // that a widening operation never uses SEW=64.
4179   // NOTE: If this fails the below assert, we can probably just find the
4180   // element count from any operand or result and use it to construct the VT.
4181   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
4182   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4183 
4184   // The more complex case is when the scalar is larger than XLenVT.
4185   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4186          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4187 
4188   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4189   // on the instruction to sign-extend since SEW>XLEN.
4190   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4191     if (isInt<32>(CVal->getSExtValue())) {
4192       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4193       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4194     }
4195   }
4196 
4197   // We need to convert the scalar to a splat vector.
4198   // FIXME: Can we implicitly truncate the scalar if it is known to
4199   // be sign extended?
4200   // VL should be the last operand.
4201   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
4202   assert(VL.getValueType() == XLenVT);
4203   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4204   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4205 }
4206 
4207 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4208                                                      SelectionDAG &DAG) const {
4209   unsigned IntNo = Op.getConstantOperandVal(0);
4210   SDLoc DL(Op);
4211   MVT XLenVT = Subtarget.getXLenVT();
4212 
4213   switch (IntNo) {
4214   default:
4215     break; // Don't custom lower most intrinsics.
4216   case Intrinsic::thread_pointer: {
4217     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4218     return DAG.getRegister(RISCV::X4, PtrVT);
4219   }
4220   case Intrinsic::riscv_orc_b:
4221     // Lower to the GORCI encoding for orc.b.
4222     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
4223                        DAG.getConstant(7, DL, XLenVT));
4224   case Intrinsic::riscv_grev:
4225   case Intrinsic::riscv_gorc: {
4226     unsigned Opc =
4227         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4228     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4229   }
4230   case Intrinsic::riscv_shfl:
4231   case Intrinsic::riscv_unshfl: {
4232     unsigned Opc =
4233         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4234     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4235   }
4236   case Intrinsic::riscv_bcompress:
4237   case Intrinsic::riscv_bdecompress: {
4238     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4239                                                        : RISCVISD::BDECOMPRESS;
4240     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4241   }
4242   case Intrinsic::riscv_bfp:
4243     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4244                        Op.getOperand(2));
4245   case Intrinsic::riscv_vmv_x_s:
4246     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4247     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4248                        Op.getOperand(1));
4249   case Intrinsic::riscv_vmv_v_x:
4250     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4251                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4252   case Intrinsic::riscv_vfmv_v_f:
4253     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4254                        Op.getOperand(1), Op.getOperand(2));
4255   case Intrinsic::riscv_vmv_s_x: {
4256     SDValue Scalar = Op.getOperand(2);
4257 
4258     if (Scalar.getValueType().bitsLE(XLenVT)) {
4259       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4260       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4261                          Op.getOperand(1), Scalar, Op.getOperand(3));
4262     }
4263 
4264     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4265 
4266     // This is an i64 value that lives in two scalar registers. We have to
4267     // insert this in a convoluted way. First we build vXi64 splat containing
4268     // the/ two values that we assemble using some bit math. Next we'll use
4269     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4270     // to merge element 0 from our splat into the source vector.
4271     // FIXME: This is probably not the best way to do this, but it is
4272     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4273     // point.
4274     //   sw lo, (a0)
4275     //   sw hi, 4(a0)
4276     //   vlse vX, (a0)
4277     //
4278     //   vid.v      vVid
4279     //   vmseq.vx   mMask, vVid, 0
4280     //   vmerge.vvm vDest, vSrc, vVal, mMask
4281     MVT VT = Op.getSimpleValueType();
4282     SDValue Vec = Op.getOperand(1);
4283     SDValue VL = Op.getOperand(3);
4284 
4285     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4286     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4287                                       DAG.getConstant(0, DL, MVT::i32), VL);
4288 
4289     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4290     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4291     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4292     SDValue SelectCond =
4293         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4294                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4295     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4296                        Vec, VL);
4297   }
4298   case Intrinsic::riscv_vslide1up:
4299   case Intrinsic::riscv_vslide1down:
4300   case Intrinsic::riscv_vslide1up_mask:
4301   case Intrinsic::riscv_vslide1down_mask: {
4302     // We need to special case these when the scalar is larger than XLen.
4303     unsigned NumOps = Op.getNumOperands();
4304     bool IsMasked = NumOps == 7;
4305     unsigned OpOffset = IsMasked ? 1 : 0;
4306     SDValue Scalar = Op.getOperand(2 + OpOffset);
4307     if (Scalar.getValueType().bitsLE(XLenVT))
4308       break;
4309 
4310     // Splatting a sign extended constant is fine.
4311     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4312       if (isInt<32>(CVal->getSExtValue()))
4313         break;
4314 
4315     MVT VT = Op.getSimpleValueType();
4316     assert(VT.getVectorElementType() == MVT::i64 &&
4317            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4318 
4319     // Convert the vector source to the equivalent nxvXi32 vector.
4320     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4321     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4322 
4323     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4324                                    DAG.getConstant(0, DL, XLenVT));
4325     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4326                                    DAG.getConstant(1, DL, XLenVT));
4327 
4328     // Double the VL since we halved SEW.
4329     SDValue VL = Op.getOperand(NumOps - (1 + OpOffset));
4330     SDValue I32VL =
4331         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4332 
4333     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4334     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4335 
4336     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4337     // instructions.
4338     if (IntNo == Intrinsic::riscv_vslide1up ||
4339         IntNo == Intrinsic::riscv_vslide1up_mask) {
4340       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4341                         I32Mask, I32VL);
4342       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4343                         I32Mask, I32VL);
4344     } else {
4345       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4346                         I32Mask, I32VL);
4347       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4348                         I32Mask, I32VL);
4349     }
4350 
4351     // Convert back to nxvXi64.
4352     Vec = DAG.getBitcast(VT, Vec);
4353 
4354     if (!IsMasked)
4355       return Vec;
4356 
4357     // Apply mask after the operation.
4358     SDValue Mask = Op.getOperand(NumOps - 3);
4359     SDValue MaskedOff = Op.getOperand(1);
4360     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4361   }
4362   }
4363 
4364   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4365 }
4366 
4367 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4368                                                     SelectionDAG &DAG) const {
4369   unsigned IntNo = Op.getConstantOperandVal(1);
4370   switch (IntNo) {
4371   default:
4372     break;
4373   case Intrinsic::riscv_masked_strided_load: {
4374     SDLoc DL(Op);
4375     MVT XLenVT = Subtarget.getXLenVT();
4376 
4377     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4378     // the selection of the masked intrinsics doesn't do this for us.
4379     SDValue Mask = Op.getOperand(5);
4380     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4381 
4382     MVT VT = Op->getSimpleValueType(0);
4383     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4384 
4385     SDValue PassThru = Op.getOperand(2);
4386     if (!IsUnmasked) {
4387       MVT MaskVT =
4388           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4389       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4390       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4391     }
4392 
4393     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4394 
4395     SDValue IntID = DAG.getTargetConstant(
4396         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4397         XLenVT);
4398 
4399     auto *Load = cast<MemIntrinsicSDNode>(Op);
4400     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4401     if (!IsUnmasked)
4402       Ops.push_back(PassThru);
4403     Ops.push_back(Op.getOperand(3)); // Ptr
4404     Ops.push_back(Op.getOperand(4)); // Stride
4405     if (!IsUnmasked)
4406       Ops.push_back(Mask);
4407     Ops.push_back(VL);
4408     if (!IsUnmasked) {
4409       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4410       Ops.push_back(Policy);
4411     }
4412 
4413     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4414     SDValue Result =
4415         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4416                                 Load->getMemoryVT(), Load->getMemOperand());
4417     SDValue Chain = Result.getValue(1);
4418     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4419     return DAG.getMergeValues({Result, Chain}, DL);
4420   }
4421   }
4422 
4423   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4424 }
4425 
4426 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4427                                                  SelectionDAG &DAG) const {
4428   unsigned IntNo = Op.getConstantOperandVal(1);
4429   switch (IntNo) {
4430   default:
4431     break;
4432   case Intrinsic::riscv_masked_strided_store: {
4433     SDLoc DL(Op);
4434     MVT XLenVT = Subtarget.getXLenVT();
4435 
4436     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4437     // the selection of the masked intrinsics doesn't do this for us.
4438     SDValue Mask = Op.getOperand(5);
4439     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4440 
4441     SDValue Val = Op.getOperand(2);
4442     MVT VT = Val.getSimpleValueType();
4443     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4444 
4445     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4446     if (!IsUnmasked) {
4447       MVT MaskVT =
4448           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4449       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4450     }
4451 
4452     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4453 
4454     SDValue IntID = DAG.getTargetConstant(
4455         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4456         XLenVT);
4457 
4458     auto *Store = cast<MemIntrinsicSDNode>(Op);
4459     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4460     Ops.push_back(Val);
4461     Ops.push_back(Op.getOperand(3)); // Ptr
4462     Ops.push_back(Op.getOperand(4)); // Stride
4463     if (!IsUnmasked)
4464       Ops.push_back(Mask);
4465     Ops.push_back(VL);
4466 
4467     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4468                                    Ops, Store->getMemoryVT(),
4469                                    Store->getMemOperand());
4470   }
4471   }
4472 
4473   return SDValue();
4474 }
4475 
4476 static MVT getLMUL1VT(MVT VT) {
4477   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4478          "Unexpected vector MVT");
4479   return MVT::getScalableVectorVT(
4480       VT.getVectorElementType(),
4481       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4482 }
4483 
4484 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4485   switch (ISDOpcode) {
4486   default:
4487     llvm_unreachable("Unhandled reduction");
4488   case ISD::VECREDUCE_ADD:
4489     return RISCVISD::VECREDUCE_ADD_VL;
4490   case ISD::VECREDUCE_UMAX:
4491     return RISCVISD::VECREDUCE_UMAX_VL;
4492   case ISD::VECREDUCE_SMAX:
4493     return RISCVISD::VECREDUCE_SMAX_VL;
4494   case ISD::VECREDUCE_UMIN:
4495     return RISCVISD::VECREDUCE_UMIN_VL;
4496   case ISD::VECREDUCE_SMIN:
4497     return RISCVISD::VECREDUCE_SMIN_VL;
4498   case ISD::VECREDUCE_AND:
4499     return RISCVISD::VECREDUCE_AND_VL;
4500   case ISD::VECREDUCE_OR:
4501     return RISCVISD::VECREDUCE_OR_VL;
4502   case ISD::VECREDUCE_XOR:
4503     return RISCVISD::VECREDUCE_XOR_VL;
4504   }
4505 }
4506 
4507 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4508                                                          SelectionDAG &DAG,
4509                                                          bool IsVP) const {
4510   SDLoc DL(Op);
4511   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4512   MVT VecVT = Vec.getSimpleValueType();
4513   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4514           Op.getOpcode() == ISD::VECREDUCE_OR ||
4515           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4516           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4517           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4518           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4519          "Unexpected reduction lowering");
4520 
4521   MVT XLenVT = Subtarget.getXLenVT();
4522   assert(Op.getValueType() == XLenVT &&
4523          "Expected reduction output to be legalized to XLenVT");
4524 
4525   MVT ContainerVT = VecVT;
4526   if (VecVT.isFixedLengthVector()) {
4527     ContainerVT = getContainerForFixedLengthVector(VecVT);
4528     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4529   }
4530 
4531   SDValue Mask, VL;
4532   if (IsVP) {
4533     Mask = Op.getOperand(2);
4534     VL = Op.getOperand(3);
4535   } else {
4536     std::tie(Mask, VL) =
4537         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4538   }
4539 
4540   unsigned BaseOpc;
4541   ISD::CondCode CC;
4542   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4543 
4544   switch (Op.getOpcode()) {
4545   default:
4546     llvm_unreachable("Unhandled reduction");
4547   case ISD::VECREDUCE_AND:
4548   case ISD::VP_REDUCE_AND: {
4549     // vcpop ~x == 0
4550     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4551     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4552     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4553     CC = ISD::SETEQ;
4554     BaseOpc = ISD::AND;
4555     break;
4556   }
4557   case ISD::VECREDUCE_OR:
4558   case ISD::VP_REDUCE_OR:
4559     // vcpop x != 0
4560     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4561     CC = ISD::SETNE;
4562     BaseOpc = ISD::OR;
4563     break;
4564   case ISD::VECREDUCE_XOR:
4565   case ISD::VP_REDUCE_XOR: {
4566     // ((vcpop x) & 1) != 0
4567     SDValue One = DAG.getConstant(1, DL, XLenVT);
4568     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4569     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4570     CC = ISD::SETNE;
4571     BaseOpc = ISD::XOR;
4572     break;
4573   }
4574   }
4575 
4576   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4577 
4578   if (!IsVP)
4579     return SetCC;
4580 
4581   // Now include the start value in the operation.
4582   // Note that we must return the start value when no elements are operated
4583   // upon. The vcpop instructions we've emitted in each case above will return
4584   // 0 for an inactive vector, and so we've already received the neutral value:
4585   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4586   // can simply include the start value.
4587   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4588 }
4589 
4590 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4591                                             SelectionDAG &DAG) const {
4592   SDLoc DL(Op);
4593   SDValue Vec = Op.getOperand(0);
4594   EVT VecEVT = Vec.getValueType();
4595 
4596   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4597 
4598   // Due to ordering in legalize types we may have a vector type that needs to
4599   // be split. Do that manually so we can get down to a legal type.
4600   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4601          TargetLowering::TypeSplitVector) {
4602     SDValue Lo, Hi;
4603     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4604     VecEVT = Lo.getValueType();
4605     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4606   }
4607 
4608   // TODO: The type may need to be widened rather than split. Or widened before
4609   // it can be split.
4610   if (!isTypeLegal(VecEVT))
4611     return SDValue();
4612 
4613   MVT VecVT = VecEVT.getSimpleVT();
4614   MVT VecEltVT = VecVT.getVectorElementType();
4615   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4616 
4617   MVT ContainerVT = VecVT;
4618   if (VecVT.isFixedLengthVector()) {
4619     ContainerVT = getContainerForFixedLengthVector(VecVT);
4620     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4621   }
4622 
4623   MVT M1VT = getLMUL1VT(ContainerVT);
4624   MVT XLenVT = Subtarget.getXLenVT();
4625 
4626   SDValue Mask, VL;
4627   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4628 
4629   SDValue NeutralElem =
4630       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4631   SDValue IdentitySplat = lowerScalarSplat(
4632       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4633   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4634                                   IdentitySplat, Mask, VL);
4635   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4636                              DAG.getConstant(0, DL, XLenVT));
4637   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4638 }
4639 
4640 // Given a reduction op, this function returns the matching reduction opcode,
4641 // the vector SDValue and the scalar SDValue required to lower this to a
4642 // RISCVISD node.
4643 static std::tuple<unsigned, SDValue, SDValue>
4644 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4645   SDLoc DL(Op);
4646   auto Flags = Op->getFlags();
4647   unsigned Opcode = Op.getOpcode();
4648   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4649   switch (Opcode) {
4650   default:
4651     llvm_unreachable("Unhandled reduction");
4652   case ISD::VECREDUCE_FADD: {
4653     // Use positive zero if we can. It is cheaper to materialize.
4654     SDValue Zero =
4655         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4656     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4657   }
4658   case ISD::VECREDUCE_SEQ_FADD:
4659     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4660                            Op.getOperand(0));
4661   case ISD::VECREDUCE_FMIN:
4662     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4663                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4664   case ISD::VECREDUCE_FMAX:
4665     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4666                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4667   }
4668 }
4669 
4670 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4671                                               SelectionDAG &DAG) const {
4672   SDLoc DL(Op);
4673   MVT VecEltVT = Op.getSimpleValueType();
4674 
4675   unsigned RVVOpcode;
4676   SDValue VectorVal, ScalarVal;
4677   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4678       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4679   MVT VecVT = VectorVal.getSimpleValueType();
4680 
4681   MVT ContainerVT = VecVT;
4682   if (VecVT.isFixedLengthVector()) {
4683     ContainerVT = getContainerForFixedLengthVector(VecVT);
4684     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4685   }
4686 
4687   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4688   MVT XLenVT = Subtarget.getXLenVT();
4689 
4690   SDValue Mask, VL;
4691   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4692 
4693   SDValue ScalarSplat = lowerScalarSplat(
4694       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4695   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4696                                   VectorVal, ScalarSplat, Mask, VL);
4697   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4698                      DAG.getConstant(0, DL, XLenVT));
4699 }
4700 
4701 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4702   switch (ISDOpcode) {
4703   default:
4704     llvm_unreachable("Unhandled reduction");
4705   case ISD::VP_REDUCE_ADD:
4706     return RISCVISD::VECREDUCE_ADD_VL;
4707   case ISD::VP_REDUCE_UMAX:
4708     return RISCVISD::VECREDUCE_UMAX_VL;
4709   case ISD::VP_REDUCE_SMAX:
4710     return RISCVISD::VECREDUCE_SMAX_VL;
4711   case ISD::VP_REDUCE_UMIN:
4712     return RISCVISD::VECREDUCE_UMIN_VL;
4713   case ISD::VP_REDUCE_SMIN:
4714     return RISCVISD::VECREDUCE_SMIN_VL;
4715   case ISD::VP_REDUCE_AND:
4716     return RISCVISD::VECREDUCE_AND_VL;
4717   case ISD::VP_REDUCE_OR:
4718     return RISCVISD::VECREDUCE_OR_VL;
4719   case ISD::VP_REDUCE_XOR:
4720     return RISCVISD::VECREDUCE_XOR_VL;
4721   case ISD::VP_REDUCE_FADD:
4722     return RISCVISD::VECREDUCE_FADD_VL;
4723   case ISD::VP_REDUCE_SEQ_FADD:
4724     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4725   case ISD::VP_REDUCE_FMAX:
4726     return RISCVISD::VECREDUCE_FMAX_VL;
4727   case ISD::VP_REDUCE_FMIN:
4728     return RISCVISD::VECREDUCE_FMIN_VL;
4729   }
4730 }
4731 
4732 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
4733                                            SelectionDAG &DAG) const {
4734   SDLoc DL(Op);
4735   SDValue Vec = Op.getOperand(1);
4736   EVT VecEVT = Vec.getValueType();
4737 
4738   // TODO: The type may need to be widened rather than split. Or widened before
4739   // it can be split.
4740   if (!isTypeLegal(VecEVT))
4741     return SDValue();
4742 
4743   MVT VecVT = VecEVT.getSimpleVT();
4744   MVT VecEltVT = VecVT.getVectorElementType();
4745   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
4746 
4747   MVT ContainerVT = VecVT;
4748   if (VecVT.isFixedLengthVector()) {
4749     ContainerVT = getContainerForFixedLengthVector(VecVT);
4750     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4751   }
4752 
4753   SDValue VL = Op.getOperand(3);
4754   SDValue Mask = Op.getOperand(2);
4755 
4756   MVT M1VT = getLMUL1VT(ContainerVT);
4757   MVT XLenVT = Subtarget.getXLenVT();
4758   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
4759 
4760   SDValue StartSplat =
4761       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
4762                        DL, DAG, Subtarget);
4763   SDValue Reduction =
4764       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
4765   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
4766                              DAG.getConstant(0, DL, XLenVT));
4767   if (!VecVT.isInteger())
4768     return Elt0;
4769   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4770 }
4771 
4772 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4773                                                    SelectionDAG &DAG) const {
4774   SDValue Vec = Op.getOperand(0);
4775   SDValue SubVec = Op.getOperand(1);
4776   MVT VecVT = Vec.getSimpleValueType();
4777   MVT SubVecVT = SubVec.getSimpleValueType();
4778 
4779   SDLoc DL(Op);
4780   MVT XLenVT = Subtarget.getXLenVT();
4781   unsigned OrigIdx = Op.getConstantOperandVal(2);
4782   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4783 
4784   // We don't have the ability to slide mask vectors up indexed by their i1
4785   // elements; the smallest we can do is i8. Often we are able to bitcast to
4786   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4787   // into a scalable one, we might not necessarily have enough scalable
4788   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4789   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4790       (OrigIdx != 0 || !Vec.isUndef())) {
4791     if (VecVT.getVectorMinNumElements() >= 8 &&
4792         SubVecVT.getVectorMinNumElements() >= 8) {
4793       assert(OrigIdx % 8 == 0 && "Invalid index");
4794       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4795              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4796              "Unexpected mask vector lowering");
4797       OrigIdx /= 8;
4798       SubVecVT =
4799           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4800                            SubVecVT.isScalableVector());
4801       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4802                                VecVT.isScalableVector());
4803       Vec = DAG.getBitcast(VecVT, Vec);
4804       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4805     } else {
4806       // We can't slide this mask vector up indexed by its i1 elements.
4807       // This poses a problem when we wish to insert a scalable vector which
4808       // can't be re-expressed as a larger type. Just choose the slow path and
4809       // extend to a larger type, then truncate back down.
4810       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4811       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4812       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4813       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4814       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4815                         Op.getOperand(2));
4816       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4817       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4818     }
4819   }
4820 
4821   // If the subvector vector is a fixed-length type, we cannot use subregister
4822   // manipulation to simplify the codegen; we don't know which register of a
4823   // LMUL group contains the specific subvector as we only know the minimum
4824   // register size. Therefore we must slide the vector group up the full
4825   // amount.
4826   if (SubVecVT.isFixedLengthVector()) {
4827     if (OrigIdx == 0 && Vec.isUndef())
4828       return Op;
4829     MVT ContainerVT = VecVT;
4830     if (VecVT.isFixedLengthVector()) {
4831       ContainerVT = getContainerForFixedLengthVector(VecVT);
4832       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4833     }
4834     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4835                          DAG.getUNDEF(ContainerVT), SubVec,
4836                          DAG.getConstant(0, DL, XLenVT));
4837     SDValue Mask =
4838         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4839     // Set the vector length to only the number of elements we care about. Note
4840     // that for slideup this includes the offset.
4841     SDValue VL =
4842         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4843     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4844     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4845                                   SubVec, SlideupAmt, Mask, VL);
4846     if (VecVT.isFixedLengthVector())
4847       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4848     return DAG.getBitcast(Op.getValueType(), Slideup);
4849   }
4850 
4851   unsigned SubRegIdx, RemIdx;
4852   std::tie(SubRegIdx, RemIdx) =
4853       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4854           VecVT, SubVecVT, OrigIdx, TRI);
4855 
4856   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4857   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4858                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4859                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4860 
4861   // 1. If the Idx has been completely eliminated and this subvector's size is
4862   // a vector register or a multiple thereof, or the surrounding elements are
4863   // undef, then this is a subvector insert which naturally aligns to a vector
4864   // register. These can easily be handled using subregister manipulation.
4865   // 2. If the subvector is smaller than a vector register, then the insertion
4866   // must preserve the undisturbed elements of the register. We do this by
4867   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4868   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4869   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4870   // LMUL=1 type back into the larger vector (resolving to another subregister
4871   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4872   // to avoid allocating a large register group to hold our subvector.
4873   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4874     return Op;
4875 
4876   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4877   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4878   // (in our case undisturbed). This means we can set up a subvector insertion
4879   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4880   // size of the subvector.
4881   MVT InterSubVT = VecVT;
4882   SDValue AlignedExtract = Vec;
4883   unsigned AlignedIdx = OrigIdx - RemIdx;
4884   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4885     InterSubVT = getLMUL1VT(VecVT);
4886     // Extract a subvector equal to the nearest full vector register type. This
4887     // should resolve to a EXTRACT_SUBREG instruction.
4888     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4889                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4890   }
4891 
4892   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4893   // For scalable vectors this must be further multiplied by vscale.
4894   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4895 
4896   SDValue Mask, VL;
4897   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4898 
4899   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4900   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4901   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4902   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4903 
4904   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4905                        DAG.getUNDEF(InterSubVT), SubVec,
4906                        DAG.getConstant(0, DL, XLenVT));
4907 
4908   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4909                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4910 
4911   // If required, insert this subvector back into the correct vector register.
4912   // This should resolve to an INSERT_SUBREG instruction.
4913   if (VecVT.bitsGT(InterSubVT))
4914     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4915                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4916 
4917   // We might have bitcast from a mask type: cast back to the original type if
4918   // required.
4919   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4920 }
4921 
4922 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4923                                                     SelectionDAG &DAG) const {
4924   SDValue Vec = Op.getOperand(0);
4925   MVT SubVecVT = Op.getSimpleValueType();
4926   MVT VecVT = Vec.getSimpleValueType();
4927 
4928   SDLoc DL(Op);
4929   MVT XLenVT = Subtarget.getXLenVT();
4930   unsigned OrigIdx = Op.getConstantOperandVal(1);
4931   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4932 
4933   // We don't have the ability to slide mask vectors down indexed by their i1
4934   // elements; the smallest we can do is i8. Often we are able to bitcast to
4935   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4936   // from a scalable one, we might not necessarily have enough scalable
4937   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4938   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4939     if (VecVT.getVectorMinNumElements() >= 8 &&
4940         SubVecVT.getVectorMinNumElements() >= 8) {
4941       assert(OrigIdx % 8 == 0 && "Invalid index");
4942       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4943              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4944              "Unexpected mask vector lowering");
4945       OrigIdx /= 8;
4946       SubVecVT =
4947           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4948                            SubVecVT.isScalableVector());
4949       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4950                                VecVT.isScalableVector());
4951       Vec = DAG.getBitcast(VecVT, Vec);
4952     } else {
4953       // We can't slide this mask vector down, indexed by its i1 elements.
4954       // This poses a problem when we wish to extract a scalable vector which
4955       // can't be re-expressed as a larger type. Just choose the slow path and
4956       // extend to a larger type, then truncate back down.
4957       // TODO: We could probably improve this when extracting certain fixed
4958       // from fixed, where we can extract as i8 and shift the correct element
4959       // right to reach the desired subvector?
4960       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4961       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4962       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4963       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4964                         Op.getOperand(1));
4965       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4966       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4967     }
4968   }
4969 
4970   // If the subvector vector is a fixed-length type, we cannot use subregister
4971   // manipulation to simplify the codegen; we don't know which register of a
4972   // LMUL group contains the specific subvector as we only know the minimum
4973   // register size. Therefore we must slide the vector group down the full
4974   // amount.
4975   if (SubVecVT.isFixedLengthVector()) {
4976     // With an index of 0 this is a cast-like subvector, which can be performed
4977     // with subregister operations.
4978     if (OrigIdx == 0)
4979       return Op;
4980     MVT ContainerVT = VecVT;
4981     if (VecVT.isFixedLengthVector()) {
4982       ContainerVT = getContainerForFixedLengthVector(VecVT);
4983       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4984     }
4985     SDValue Mask =
4986         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4987     // Set the vector length to only the number of elements we care about. This
4988     // avoids sliding down elements we're going to discard straight away.
4989     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4990     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4991     SDValue Slidedown =
4992         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4993                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4994     // Now we can use a cast-like subvector extract to get the result.
4995     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4996                             DAG.getConstant(0, DL, XLenVT));
4997     return DAG.getBitcast(Op.getValueType(), Slidedown);
4998   }
4999 
5000   unsigned SubRegIdx, RemIdx;
5001   std::tie(SubRegIdx, RemIdx) =
5002       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5003           VecVT, SubVecVT, OrigIdx, TRI);
5004 
5005   // If the Idx has been completely eliminated then this is a subvector extract
5006   // which naturally aligns to a vector register. These can easily be handled
5007   // using subregister manipulation.
5008   if (RemIdx == 0)
5009     return Op;
5010 
5011   // Else we must shift our vector register directly to extract the subvector.
5012   // Do this using VSLIDEDOWN.
5013 
5014   // If the vector type is an LMUL-group type, extract a subvector equal to the
5015   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5016   // instruction.
5017   MVT InterSubVT = VecVT;
5018   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5019     InterSubVT = getLMUL1VT(VecVT);
5020     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5021                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5022   }
5023 
5024   // Slide this vector register down by the desired number of elements in order
5025   // to place the desired subvector starting at element 0.
5026   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5027   // For scalable vectors this must be further multiplied by vscale.
5028   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5029 
5030   SDValue Mask, VL;
5031   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5032   SDValue Slidedown =
5033       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5034                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5035 
5036   // Now the vector is in the right position, extract our final subvector. This
5037   // should resolve to a COPY.
5038   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5039                           DAG.getConstant(0, DL, XLenVT));
5040 
5041   // We might have bitcast from a mask type: cast back to the original type if
5042   // required.
5043   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5044 }
5045 
5046 // Lower step_vector to the vid instruction. Any non-identity step value must
5047 // be accounted for my manual expansion.
5048 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5049                                               SelectionDAG &DAG) const {
5050   SDLoc DL(Op);
5051   MVT VT = Op.getSimpleValueType();
5052   MVT XLenVT = Subtarget.getXLenVT();
5053   SDValue Mask, VL;
5054   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5055   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5056   uint64_t StepValImm = Op.getConstantOperandVal(0);
5057   if (StepValImm != 1) {
5058     if (isPowerOf2_64(StepValImm)) {
5059       SDValue StepVal =
5060           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5061                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5062       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5063     } else {
5064       SDValue StepVal = lowerScalarSplat(
5065           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5066           DL, DAG, Subtarget);
5067       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5068     }
5069   }
5070   return StepVec;
5071 }
5072 
5073 // Implement vector_reverse using vrgather.vv with indices determined by
5074 // subtracting the id of each element from (VLMAX-1). This will convert
5075 // the indices like so:
5076 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5077 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5078 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5079                                                  SelectionDAG &DAG) const {
5080   SDLoc DL(Op);
5081   MVT VecVT = Op.getSimpleValueType();
5082   unsigned EltSize = VecVT.getScalarSizeInBits();
5083   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5084 
5085   unsigned MaxVLMAX = 0;
5086   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5087   if (VectorBitsMax != 0)
5088     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5089 
5090   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5091   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5092 
5093   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5094   // to use vrgatherei16.vv.
5095   // TODO: It's also possible to use vrgatherei16.vv for other types to
5096   // decrease register width for the index calculation.
5097   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5098     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5099     // Reverse each half, then reassemble them in reverse order.
5100     // NOTE: It's also possible that after splitting that VLMAX no longer
5101     // requires vrgatherei16.vv.
5102     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5103       SDValue Lo, Hi;
5104       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5105       EVT LoVT, HiVT;
5106       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5107       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5108       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5109       // Reassemble the low and high pieces reversed.
5110       // FIXME: This is a CONCAT_VECTORS.
5111       SDValue Res =
5112           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5113                       DAG.getIntPtrConstant(0, DL));
5114       return DAG.getNode(
5115           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5116           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5117     }
5118 
5119     // Just promote the int type to i16 which will double the LMUL.
5120     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5121     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5122   }
5123 
5124   MVT XLenVT = Subtarget.getXLenVT();
5125   SDValue Mask, VL;
5126   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5127 
5128   // Calculate VLMAX-1 for the desired SEW.
5129   unsigned MinElts = VecVT.getVectorMinNumElements();
5130   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5131                               DAG.getConstant(MinElts, DL, XLenVT));
5132   SDValue VLMinus1 =
5133       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5134 
5135   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5136   bool IsRV32E64 =
5137       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5138   SDValue SplatVL;
5139   if (!IsRV32E64)
5140     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5141   else
5142     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5143 
5144   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5145   SDValue Indices =
5146       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5147 
5148   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5149 }
5150 
5151 SDValue
5152 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5153                                                      SelectionDAG &DAG) const {
5154   SDLoc DL(Op);
5155   auto *Load = cast<LoadSDNode>(Op);
5156 
5157   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5158                                         Load->getMemoryVT(),
5159                                         *Load->getMemOperand()) &&
5160          "Expecting a correctly-aligned load");
5161 
5162   MVT VT = Op.getSimpleValueType();
5163   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5164 
5165   SDValue VL =
5166       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5167 
5168   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5169   SDValue NewLoad = DAG.getMemIntrinsicNode(
5170       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5171       Load->getMemoryVT(), Load->getMemOperand());
5172 
5173   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5174   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5175 }
5176 
5177 SDValue
5178 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5179                                                       SelectionDAG &DAG) const {
5180   SDLoc DL(Op);
5181   auto *Store = cast<StoreSDNode>(Op);
5182 
5183   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5184                                         Store->getMemoryVT(),
5185                                         *Store->getMemOperand()) &&
5186          "Expecting a correctly-aligned store");
5187 
5188   SDValue StoreVal = Store->getValue();
5189   MVT VT = StoreVal.getSimpleValueType();
5190 
5191   // If the size less than a byte, we need to pad with zeros to make a byte.
5192   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5193     VT = MVT::v8i1;
5194     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5195                            DAG.getConstant(0, DL, VT), StoreVal,
5196                            DAG.getIntPtrConstant(0, DL));
5197   }
5198 
5199   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5200 
5201   SDValue VL =
5202       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5203 
5204   SDValue NewValue =
5205       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5206   return DAG.getMemIntrinsicNode(
5207       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5208       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5209       Store->getMemoryVT(), Store->getMemOperand());
5210 }
5211 
5212 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5213                                              SelectionDAG &DAG) const {
5214   SDLoc DL(Op);
5215   MVT VT = Op.getSimpleValueType();
5216 
5217   const auto *MemSD = cast<MemSDNode>(Op);
5218   EVT MemVT = MemSD->getMemoryVT();
5219   MachineMemOperand *MMO = MemSD->getMemOperand();
5220   SDValue Chain = MemSD->getChain();
5221   SDValue BasePtr = MemSD->getBasePtr();
5222 
5223   SDValue Mask, PassThru, VL;
5224   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5225     Mask = VPLoad->getMask();
5226     PassThru = DAG.getUNDEF(VT);
5227     VL = VPLoad->getVectorLength();
5228   } else {
5229     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5230     Mask = MLoad->getMask();
5231     PassThru = MLoad->getPassThru();
5232   }
5233 
5234   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5235 
5236   MVT XLenVT = Subtarget.getXLenVT();
5237 
5238   MVT ContainerVT = VT;
5239   if (VT.isFixedLengthVector()) {
5240     ContainerVT = getContainerForFixedLengthVector(VT);
5241     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5242     if (!IsUnmasked) {
5243       MVT MaskVT =
5244           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5245       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5246     }
5247   }
5248 
5249   if (!VL)
5250     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5251 
5252   unsigned IntID =
5253       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5254   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5255   if (!IsUnmasked)
5256     Ops.push_back(PassThru);
5257   Ops.push_back(BasePtr);
5258   if (!IsUnmasked)
5259     Ops.push_back(Mask);
5260   Ops.push_back(VL);
5261   if (!IsUnmasked)
5262     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5263 
5264   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5265 
5266   SDValue Result =
5267       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5268   Chain = Result.getValue(1);
5269 
5270   if (VT.isFixedLengthVector())
5271     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5272 
5273   return DAG.getMergeValues({Result, Chain}, DL);
5274 }
5275 
5276 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5277                                               SelectionDAG &DAG) const {
5278   SDLoc DL(Op);
5279 
5280   const auto *MemSD = cast<MemSDNode>(Op);
5281   EVT MemVT = MemSD->getMemoryVT();
5282   MachineMemOperand *MMO = MemSD->getMemOperand();
5283   SDValue Chain = MemSD->getChain();
5284   SDValue BasePtr = MemSD->getBasePtr();
5285   SDValue Val, Mask, VL;
5286 
5287   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5288     Val = VPStore->getValue();
5289     Mask = VPStore->getMask();
5290     VL = VPStore->getVectorLength();
5291   } else {
5292     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5293     Val = MStore->getValue();
5294     Mask = MStore->getMask();
5295   }
5296 
5297   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5298 
5299   MVT VT = Val.getSimpleValueType();
5300   MVT XLenVT = Subtarget.getXLenVT();
5301 
5302   MVT ContainerVT = VT;
5303   if (VT.isFixedLengthVector()) {
5304     ContainerVT = getContainerForFixedLengthVector(VT);
5305 
5306     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5307     if (!IsUnmasked) {
5308       MVT MaskVT =
5309           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5310       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5311     }
5312   }
5313 
5314   if (!VL)
5315     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5316 
5317   unsigned IntID =
5318       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5319   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5320   Ops.push_back(Val);
5321   Ops.push_back(BasePtr);
5322   if (!IsUnmasked)
5323     Ops.push_back(Mask);
5324   Ops.push_back(VL);
5325 
5326   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5327                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5328 }
5329 
5330 SDValue
5331 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5332                                                       SelectionDAG &DAG) const {
5333   MVT InVT = Op.getOperand(0).getSimpleValueType();
5334   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5335 
5336   MVT VT = Op.getSimpleValueType();
5337 
5338   SDValue Op1 =
5339       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5340   SDValue Op2 =
5341       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5342 
5343   SDLoc DL(Op);
5344   SDValue VL =
5345       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5346 
5347   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5348   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5349 
5350   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5351                             Op.getOperand(2), Mask, VL);
5352 
5353   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5354 }
5355 
5356 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5357     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5358   MVT VT = Op.getSimpleValueType();
5359 
5360   if (VT.getVectorElementType() == MVT::i1)
5361     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5362 
5363   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5364 }
5365 
5366 SDValue
5367 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5368                                                       SelectionDAG &DAG) const {
5369   unsigned Opc;
5370   switch (Op.getOpcode()) {
5371   default: llvm_unreachable("Unexpected opcode!");
5372   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5373   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5374   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5375   }
5376 
5377   return lowerToScalableOp(Op, DAG, Opc);
5378 }
5379 
5380 // Lower vector ABS to smax(X, sub(0, X)).
5381 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5382   SDLoc DL(Op);
5383   MVT VT = Op.getSimpleValueType();
5384   SDValue X = Op.getOperand(0);
5385 
5386   assert(VT.isFixedLengthVector() && "Unexpected type");
5387 
5388   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5389   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5390 
5391   SDValue Mask, VL;
5392   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5393 
5394   SDValue SplatZero =
5395       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5396                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5397   SDValue NegX =
5398       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5399   SDValue Max =
5400       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5401 
5402   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5403 }
5404 
5405 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5406     SDValue Op, SelectionDAG &DAG) const {
5407   SDLoc DL(Op);
5408   MVT VT = Op.getSimpleValueType();
5409   SDValue Mag = Op.getOperand(0);
5410   SDValue Sign = Op.getOperand(1);
5411   assert(Mag.getValueType() == Sign.getValueType() &&
5412          "Can only handle COPYSIGN with matching types.");
5413 
5414   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5415   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5416   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5417 
5418   SDValue Mask, VL;
5419   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5420 
5421   SDValue CopySign =
5422       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5423 
5424   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5425 }
5426 
5427 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5428     SDValue Op, SelectionDAG &DAG) const {
5429   MVT VT = Op.getSimpleValueType();
5430   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5431 
5432   MVT I1ContainerVT =
5433       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5434 
5435   SDValue CC =
5436       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5437   SDValue Op1 =
5438       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5439   SDValue Op2 =
5440       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5441 
5442   SDLoc DL(Op);
5443   SDValue Mask, VL;
5444   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5445 
5446   SDValue Select =
5447       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5448 
5449   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5450 }
5451 
5452 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5453                                                unsigned NewOpc,
5454                                                bool HasMask) const {
5455   MVT VT = Op.getSimpleValueType();
5456   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5457 
5458   // Create list of operands by converting existing ones to scalable types.
5459   SmallVector<SDValue, 6> Ops;
5460   for (const SDValue &V : Op->op_values()) {
5461     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5462 
5463     // Pass through non-vector operands.
5464     if (!V.getValueType().isVector()) {
5465       Ops.push_back(V);
5466       continue;
5467     }
5468 
5469     // "cast" fixed length vector to a scalable vector.
5470     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5471            "Only fixed length vectors are supported!");
5472     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5473   }
5474 
5475   SDLoc DL(Op);
5476   SDValue Mask, VL;
5477   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5478   if (HasMask)
5479     Ops.push_back(Mask);
5480   Ops.push_back(VL);
5481 
5482   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5483   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5484 }
5485 
5486 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5487 // * Operands of each node are assumed to be in the same order.
5488 // * The EVL operand is promoted from i32 to i64 on RV64.
5489 // * Fixed-length vectors are converted to their scalable-vector container
5490 //   types.
5491 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5492                                        unsigned RISCVISDOpc) const {
5493   SDLoc DL(Op);
5494   MVT VT = Op.getSimpleValueType();
5495   SmallVector<SDValue, 4> Ops;
5496 
5497   for (const auto &OpIdx : enumerate(Op->ops())) {
5498     SDValue V = OpIdx.value();
5499     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5500     // Pass through operands which aren't fixed-length vectors.
5501     if (!V.getValueType().isFixedLengthVector()) {
5502       Ops.push_back(V);
5503       continue;
5504     }
5505     // "cast" fixed length vector to a scalable vector.
5506     MVT OpVT = V.getSimpleValueType();
5507     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5508     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5509            "Only fixed length vectors are supported!");
5510     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5511   }
5512 
5513   if (!VT.isFixedLengthVector())
5514     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5515 
5516   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5517 
5518   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5519 
5520   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5521 }
5522 
5523 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5524                                             unsigned MaskOpc,
5525                                             unsigned VecOpc) const {
5526   MVT VT = Op.getSimpleValueType();
5527   if (VT.getVectorElementType() != MVT::i1)
5528     return lowerVPOp(Op, DAG, VecOpc);
5529 
5530   // It is safe to drop mask parameter as masked-off elements are undef.
5531   SDValue Op1 = Op->getOperand(0);
5532   SDValue Op2 = Op->getOperand(1);
5533   SDValue VL = Op->getOperand(3);
5534 
5535   MVT ContainerVT = VT;
5536   const bool IsFixed = VT.isFixedLengthVector();
5537   if (IsFixed) {
5538     ContainerVT = getContainerForFixedLengthVector(VT);
5539     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5540     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5541   }
5542 
5543   SDLoc DL(Op);
5544   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5545   if (!IsFixed)
5546     return Val;
5547   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5548 }
5549 
5550 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5551 // matched to a RVV indexed load. The RVV indexed load instructions only
5552 // support the "unsigned unscaled" addressing mode; indices are implicitly
5553 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5554 // signed or scaled indexing is extended to the XLEN value type and scaled
5555 // accordingly.
5556 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5557                                                SelectionDAG &DAG) const {
5558   SDLoc DL(Op);
5559   MVT VT = Op.getSimpleValueType();
5560 
5561   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5562   EVT MemVT = MemSD->getMemoryVT();
5563   MachineMemOperand *MMO = MemSD->getMemOperand();
5564   SDValue Chain = MemSD->getChain();
5565   SDValue BasePtr = MemSD->getBasePtr();
5566 
5567   ISD::LoadExtType LoadExtType;
5568   SDValue Index, Mask, PassThru, VL;
5569 
5570   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5571     Index = VPGN->getIndex();
5572     Mask = VPGN->getMask();
5573     PassThru = DAG.getUNDEF(VT);
5574     VL = VPGN->getVectorLength();
5575     // VP doesn't support extending loads.
5576     LoadExtType = ISD::NON_EXTLOAD;
5577   } else {
5578     // Else it must be a MGATHER.
5579     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5580     Index = MGN->getIndex();
5581     Mask = MGN->getMask();
5582     PassThru = MGN->getPassThru();
5583     LoadExtType = MGN->getExtensionType();
5584   }
5585 
5586   MVT IndexVT = Index.getSimpleValueType();
5587   MVT XLenVT = Subtarget.getXLenVT();
5588 
5589   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5590          "Unexpected VTs!");
5591   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5592   // Targets have to explicitly opt-in for extending vector loads.
5593   assert(LoadExtType == ISD::NON_EXTLOAD &&
5594          "Unexpected extending MGATHER/VP_GATHER");
5595   (void)LoadExtType;
5596 
5597   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5598   // the selection of the masked intrinsics doesn't do this for us.
5599   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5600 
5601   MVT ContainerVT = VT;
5602   if (VT.isFixedLengthVector()) {
5603     // We need to use the larger of the result and index type to determine the
5604     // scalable type to use so we don't increase LMUL for any operand/result.
5605     if (VT.bitsGE(IndexVT)) {
5606       ContainerVT = getContainerForFixedLengthVector(VT);
5607       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5608                                  ContainerVT.getVectorElementCount());
5609     } else {
5610       IndexVT = getContainerForFixedLengthVector(IndexVT);
5611       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5612                                      IndexVT.getVectorElementCount());
5613     }
5614 
5615     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5616 
5617     if (!IsUnmasked) {
5618       MVT MaskVT =
5619           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5620       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5621       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5622     }
5623   }
5624 
5625   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5626       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5627       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5628   }
5629 
5630   if (!VL)
5631     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5632 
5633   unsigned IntID =
5634       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5635   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5636   if (!IsUnmasked)
5637     Ops.push_back(PassThru);
5638   Ops.push_back(BasePtr);
5639   Ops.push_back(Index);
5640   if (!IsUnmasked)
5641     Ops.push_back(Mask);
5642   Ops.push_back(VL);
5643   if (!IsUnmasked)
5644     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5645 
5646   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5647   SDValue Result =
5648       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5649   Chain = Result.getValue(1);
5650 
5651   if (VT.isFixedLengthVector())
5652     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5653 
5654   return DAG.getMergeValues({Result, Chain}, DL);
5655 }
5656 
5657 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5658 // matched to a RVV indexed store. The RVV indexed store instructions only
5659 // support the "unsigned unscaled" addressing mode; indices are implicitly
5660 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5661 // signed or scaled indexing is extended to the XLEN value type and scaled
5662 // accordingly.
5663 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5664                                                 SelectionDAG &DAG) const {
5665   SDLoc DL(Op);
5666   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5667   EVT MemVT = MemSD->getMemoryVT();
5668   MachineMemOperand *MMO = MemSD->getMemOperand();
5669   SDValue Chain = MemSD->getChain();
5670   SDValue BasePtr = MemSD->getBasePtr();
5671 
5672   bool IsTruncatingStore = false;
5673   SDValue Index, Mask, Val, VL;
5674 
5675   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5676     Index = VPSN->getIndex();
5677     Mask = VPSN->getMask();
5678     Val = VPSN->getValue();
5679     VL = VPSN->getVectorLength();
5680     // VP doesn't support truncating stores.
5681     IsTruncatingStore = false;
5682   } else {
5683     // Else it must be a MSCATTER.
5684     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5685     Index = MSN->getIndex();
5686     Mask = MSN->getMask();
5687     Val = MSN->getValue();
5688     IsTruncatingStore = MSN->isTruncatingStore();
5689   }
5690 
5691   MVT VT = Val.getSimpleValueType();
5692   MVT IndexVT = Index.getSimpleValueType();
5693   MVT XLenVT = Subtarget.getXLenVT();
5694 
5695   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5696          "Unexpected VTs!");
5697   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5698   // Targets have to explicitly opt-in for extending vector loads and
5699   // truncating vector stores.
5700   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5701   (void)IsTruncatingStore;
5702 
5703   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5704   // the selection of the masked intrinsics doesn't do this for us.
5705   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5706 
5707   MVT ContainerVT = VT;
5708   if (VT.isFixedLengthVector()) {
5709     // We need to use the larger of the value and index type to determine the
5710     // scalable type to use so we don't increase LMUL for any operand/result.
5711     if (VT.bitsGE(IndexVT)) {
5712       ContainerVT = getContainerForFixedLengthVector(VT);
5713       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5714                                  ContainerVT.getVectorElementCount());
5715     } else {
5716       IndexVT = getContainerForFixedLengthVector(IndexVT);
5717       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5718                                      IndexVT.getVectorElementCount());
5719     }
5720 
5721     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5722     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5723 
5724     if (!IsUnmasked) {
5725       MVT MaskVT =
5726           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5727       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5728     }
5729   }
5730 
5731   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5732       IndexVT = IndexVT.changeVectorElementType(XLenVT);
5733       Index = DAG.getNode(ISD::TRUNCATE, DL, IndexVT, Index);
5734   }
5735 
5736   if (!VL)
5737     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5738 
5739   unsigned IntID =
5740       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
5741   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5742   Ops.push_back(Val);
5743   Ops.push_back(BasePtr);
5744   Ops.push_back(Index);
5745   if (!IsUnmasked)
5746     Ops.push_back(Mask);
5747   Ops.push_back(VL);
5748 
5749   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5750                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5751 }
5752 
5753 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
5754                                                SelectionDAG &DAG) const {
5755   const MVT XLenVT = Subtarget.getXLenVT();
5756   SDLoc DL(Op);
5757   SDValue Chain = Op->getOperand(0);
5758   SDValue SysRegNo = DAG.getTargetConstant(
5759       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5760   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
5761   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
5762 
5763   // Encoding used for rounding mode in RISCV differs from that used in
5764   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
5765   // table, which consists of a sequence of 4-bit fields, each representing
5766   // corresponding FLT_ROUNDS mode.
5767   static const int Table =
5768       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
5769       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
5770       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
5771       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
5772       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
5773 
5774   SDValue Shift =
5775       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
5776   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5777                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5778   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5779                                DAG.getConstant(7, DL, XLenVT));
5780 
5781   return DAG.getMergeValues({Masked, Chain}, DL);
5782 }
5783 
5784 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
5785                                                SelectionDAG &DAG) const {
5786   const MVT XLenVT = Subtarget.getXLenVT();
5787   SDLoc DL(Op);
5788   SDValue Chain = Op->getOperand(0);
5789   SDValue RMValue = Op->getOperand(1);
5790   SDValue SysRegNo = DAG.getTargetConstant(
5791       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
5792 
5793   // Encoding used for rounding mode in RISCV differs from that used in
5794   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
5795   // a table, which consists of a sequence of 4-bit fields, each representing
5796   // corresponding RISCV mode.
5797   static const unsigned Table =
5798       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
5799       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
5800       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
5801       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
5802       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
5803 
5804   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
5805                               DAG.getConstant(2, DL, XLenVT));
5806   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
5807                                 DAG.getConstant(Table, DL, XLenVT), Shift);
5808   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
5809                         DAG.getConstant(0x7, DL, XLenVT));
5810   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
5811                      RMValue);
5812 }
5813 
5814 // Returns the opcode of the target-specific SDNode that implements the 32-bit
5815 // form of the given Opcode.
5816 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
5817   switch (Opcode) {
5818   default:
5819     llvm_unreachable("Unexpected opcode");
5820   case ISD::SHL:
5821     return RISCVISD::SLLW;
5822   case ISD::SRA:
5823     return RISCVISD::SRAW;
5824   case ISD::SRL:
5825     return RISCVISD::SRLW;
5826   case ISD::SDIV:
5827     return RISCVISD::DIVW;
5828   case ISD::UDIV:
5829     return RISCVISD::DIVUW;
5830   case ISD::UREM:
5831     return RISCVISD::REMUW;
5832   case ISD::ROTL:
5833     return RISCVISD::ROLW;
5834   case ISD::ROTR:
5835     return RISCVISD::RORW;
5836   case RISCVISD::GREV:
5837     return RISCVISD::GREVW;
5838   case RISCVISD::GORC:
5839     return RISCVISD::GORCW;
5840   }
5841 }
5842 
5843 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
5844 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
5845 // otherwise be promoted to i64, making it difficult to select the
5846 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
5847 // type i8/i16/i32 is lost.
5848 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
5849                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
5850   SDLoc DL(N);
5851   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5852   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
5853   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
5854   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5855   // ReplaceNodeResults requires we maintain the same type for the return value.
5856   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
5857 }
5858 
5859 // Converts the given 32-bit operation to a i64 operation with signed extension
5860 // semantic to reduce the signed extension instructions.
5861 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
5862   SDLoc DL(N);
5863   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5864   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5865   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
5866   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5867                                DAG.getValueType(MVT::i32));
5868   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
5869 }
5870 
5871 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
5872                                              SmallVectorImpl<SDValue> &Results,
5873                                              SelectionDAG &DAG) const {
5874   SDLoc DL(N);
5875   switch (N->getOpcode()) {
5876   default:
5877     llvm_unreachable("Don't know how to custom type legalize this operation!");
5878   case ISD::STRICT_FP_TO_SINT:
5879   case ISD::STRICT_FP_TO_UINT:
5880   case ISD::FP_TO_SINT:
5881   case ISD::FP_TO_UINT: {
5882     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5883            "Unexpected custom legalisation");
5884     bool IsStrict = N->isStrictFPOpcode();
5885     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
5886                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
5887     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
5888     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
5889         TargetLowering::TypeSoftenFloat) {
5890       if (!isTypeLegal(Op0.getValueType()))
5891         return;
5892       if (IsStrict) {
5893         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
5894                                 : RISCVISD::STRICT_FCVT_WU_RV64;
5895         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
5896         SDValue Res = DAG.getNode(
5897             Opc, DL, VTs, N->getOperand(0), Op0,
5898             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
5899         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5900         Results.push_back(Res.getValue(1));
5901         return;
5902       }
5903       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
5904       SDValue Res =
5905           DAG.getNode(Opc, DL, MVT::i64, Op0,
5906                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
5907       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5908       return;
5909     }
5910     // If the FP type needs to be softened, emit a library call using the 'si'
5911     // version. If we left it to default legalization we'd end up with 'di'. If
5912     // the FP type doesn't need to be softened just let generic type
5913     // legalization promote the result type.
5914     RTLIB::Libcall LC;
5915     if (IsSigned)
5916       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
5917     else
5918       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5919     MakeLibCallOptions CallOptions;
5920     EVT OpVT = Op0.getValueType();
5921     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5922     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5923     SDValue Result;
5924     std::tie(Result, Chain) =
5925         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5926     Results.push_back(Result);
5927     if (IsStrict)
5928       Results.push_back(Chain);
5929     break;
5930   }
5931   case ISD::READCYCLECOUNTER: {
5932     assert(!Subtarget.is64Bit() &&
5933            "READCYCLECOUNTER only has custom type legalization on riscv32");
5934 
5935     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5936     SDValue RCW =
5937         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5938 
5939     Results.push_back(
5940         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5941     Results.push_back(RCW.getValue(2));
5942     break;
5943   }
5944   case ISD::MUL: {
5945     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5946     unsigned XLen = Subtarget.getXLen();
5947     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5948     if (Size > XLen) {
5949       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5950       SDValue LHS = N->getOperand(0);
5951       SDValue RHS = N->getOperand(1);
5952       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5953 
5954       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5955       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5956       // We need exactly one side to be unsigned.
5957       if (LHSIsU == RHSIsU)
5958         return;
5959 
5960       auto MakeMULPair = [&](SDValue S, SDValue U) {
5961         MVT XLenVT = Subtarget.getXLenVT();
5962         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5963         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5964         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5965         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5966         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5967       };
5968 
5969       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5970       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5971 
5972       // The other operand should be signed, but still prefer MULH when
5973       // possible.
5974       if (RHSIsU && LHSIsS && !RHSIsS)
5975         Results.push_back(MakeMULPair(LHS, RHS));
5976       else if (LHSIsU && RHSIsS && !LHSIsS)
5977         Results.push_back(MakeMULPair(RHS, LHS));
5978 
5979       return;
5980     }
5981     LLVM_FALLTHROUGH;
5982   }
5983   case ISD::ADD:
5984   case ISD::SUB:
5985     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5986            "Unexpected custom legalisation");
5987     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5988     break;
5989   case ISD::SHL:
5990   case ISD::SRA:
5991   case ISD::SRL:
5992     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5993            "Unexpected custom legalisation");
5994     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5995       Results.push_back(customLegalizeToWOp(N, DAG));
5996       break;
5997     }
5998 
5999     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6000     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6001     // shift amount.
6002     if (N->getOpcode() == ISD::SHL) {
6003       SDLoc DL(N);
6004       SDValue NewOp0 =
6005           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6006       SDValue NewOp1 =
6007           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6008       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6009       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6010                                    DAG.getValueType(MVT::i32));
6011       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6012     }
6013 
6014     break;
6015   case ISD::ROTL:
6016   case ISD::ROTR:
6017     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6018            "Unexpected custom legalisation");
6019     Results.push_back(customLegalizeToWOp(N, DAG));
6020     break;
6021   case ISD::CTTZ:
6022   case ISD::CTTZ_ZERO_UNDEF:
6023   case ISD::CTLZ:
6024   case ISD::CTLZ_ZERO_UNDEF: {
6025     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6026            "Unexpected custom legalisation");
6027 
6028     SDValue NewOp0 =
6029         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6030     bool IsCTZ =
6031         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6032     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6033     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6034     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6035     return;
6036   }
6037   case ISD::SDIV:
6038   case ISD::UDIV:
6039   case ISD::UREM: {
6040     MVT VT = N->getSimpleValueType(0);
6041     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6042            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6043            "Unexpected custom legalisation");
6044     // Don't promote division/remainder by constant since we should expand those
6045     // to multiply by magic constant.
6046     // FIXME: What if the expansion is disabled for minsize.
6047     if (N->getOperand(1).getOpcode() == ISD::Constant)
6048       return;
6049 
6050     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6051     // the upper 32 bits. For other types we need to sign or zero extend
6052     // based on the opcode.
6053     unsigned ExtOpc = ISD::ANY_EXTEND;
6054     if (VT != MVT::i32)
6055       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6056                                            : ISD::ZERO_EXTEND;
6057 
6058     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6059     break;
6060   }
6061   case ISD::UADDO:
6062   case ISD::USUBO: {
6063     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6064            "Unexpected custom legalisation");
6065     bool IsAdd = N->getOpcode() == ISD::UADDO;
6066     // Create an ADDW or SUBW.
6067     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6068     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6069     SDValue Res =
6070         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6071     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6072                       DAG.getValueType(MVT::i32));
6073 
6074     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6075     // Since the inputs are sign extended from i32, this is equivalent to
6076     // comparing the lower 32 bits.
6077     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6078     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6079                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6080 
6081     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6082     Results.push_back(Overflow);
6083     return;
6084   }
6085   case ISD::UADDSAT:
6086   case ISD::USUBSAT: {
6087     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6088            "Unexpected custom legalisation");
6089     if (Subtarget.hasStdExtZbb()) {
6090       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6091       // sign extend allows overflow of the lower 32 bits to be detected on
6092       // the promoted size.
6093       SDValue LHS =
6094           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6095       SDValue RHS =
6096           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6097       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6098       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6099       return;
6100     }
6101 
6102     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6103     // promotion for UADDO/USUBO.
6104     Results.push_back(expandAddSubSat(N, DAG));
6105     return;
6106   }
6107   case ISD::BITCAST: {
6108     EVT VT = N->getValueType(0);
6109     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6110     SDValue Op0 = N->getOperand(0);
6111     EVT Op0VT = Op0.getValueType();
6112     MVT XLenVT = Subtarget.getXLenVT();
6113     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6114       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6115       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6116     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6117                Subtarget.hasStdExtF()) {
6118       SDValue FPConv =
6119           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6120       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6121     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6122                isTypeLegal(Op0VT)) {
6123       // Custom-legalize bitcasts from fixed-length vector types to illegal
6124       // scalar types in order to improve codegen. Bitcast the vector to a
6125       // one-element vector type whose element type is the same as the result
6126       // type, and extract the first element.
6127       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6128       if (isTypeLegal(BVT)) {
6129         SDValue BVec = DAG.getBitcast(BVT, Op0);
6130         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6131                                       DAG.getConstant(0, DL, XLenVT)));
6132       }
6133     }
6134     break;
6135   }
6136   case RISCVISD::GREV:
6137   case RISCVISD::GORC: {
6138     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6139            "Unexpected custom legalisation");
6140     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6141     // This is similar to customLegalizeToWOp, except that we pass the second
6142     // operand (a TargetConstant) straight through: it is already of type
6143     // XLenVT.
6144     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6145     SDValue NewOp0 =
6146         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6147     SDValue NewOp1 =
6148         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6149     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6150     // ReplaceNodeResults requires we maintain the same type for the return
6151     // value.
6152     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6153     break;
6154   }
6155   case RISCVISD::SHFL: {
6156     // There is no SHFLIW instruction, but we can just promote the operation.
6157     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6158            "Unexpected custom legalisation");
6159     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6160     SDValue NewOp0 =
6161         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6162     SDValue NewOp1 =
6163         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6164     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6165     // ReplaceNodeResults requires we maintain the same type for the return
6166     // value.
6167     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6168     break;
6169   }
6170   case ISD::BSWAP:
6171   case ISD::BITREVERSE: {
6172     MVT VT = N->getSimpleValueType(0);
6173     MVT XLenVT = Subtarget.getXLenVT();
6174     assert((VT == MVT::i8 || VT == MVT::i16 ||
6175             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6176            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6177     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6178     unsigned Imm = VT.getSizeInBits() - 1;
6179     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6180     if (N->getOpcode() == ISD::BSWAP)
6181       Imm &= ~0x7U;
6182     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6183     SDValue GREVI =
6184         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6185     // ReplaceNodeResults requires we maintain the same type for the return
6186     // value.
6187     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6188     break;
6189   }
6190   case ISD::FSHL:
6191   case ISD::FSHR: {
6192     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6193            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6194     SDValue NewOp0 =
6195         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6196     SDValue NewOp1 =
6197         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6198     SDValue NewOp2 =
6199         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6200     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6201     // Mask the shift amount to 5 bits.
6202     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6203                          DAG.getConstant(0x1f, DL, MVT::i64));
6204     unsigned Opc =
6205         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
6206     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
6207     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6208     break;
6209   }
6210   case ISD::EXTRACT_VECTOR_ELT: {
6211     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6212     // type is illegal (currently only vXi64 RV32).
6213     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6214     // transferred to the destination register. We issue two of these from the
6215     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6216     // first element.
6217     SDValue Vec = N->getOperand(0);
6218     SDValue Idx = N->getOperand(1);
6219 
6220     // The vector type hasn't been legalized yet so we can't issue target
6221     // specific nodes if it needs legalization.
6222     // FIXME: We would manually legalize if it's important.
6223     if (!isTypeLegal(Vec.getValueType()))
6224       return;
6225 
6226     MVT VecVT = Vec.getSimpleValueType();
6227 
6228     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6229            VecVT.getVectorElementType() == MVT::i64 &&
6230            "Unexpected EXTRACT_VECTOR_ELT legalization");
6231 
6232     // If this is a fixed vector, we need to convert it to a scalable vector.
6233     MVT ContainerVT = VecVT;
6234     if (VecVT.isFixedLengthVector()) {
6235       ContainerVT = getContainerForFixedLengthVector(VecVT);
6236       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6237     }
6238 
6239     MVT XLenVT = Subtarget.getXLenVT();
6240 
6241     // Use a VL of 1 to avoid processing more elements than we need.
6242     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6243     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6244     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6245 
6246     // Unless the index is known to be 0, we must slide the vector down to get
6247     // the desired element into index 0.
6248     if (!isNullConstant(Idx)) {
6249       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6250                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6251     }
6252 
6253     // Extract the lower XLEN bits of the correct vector element.
6254     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6255 
6256     // To extract the upper XLEN bits of the vector element, shift the first
6257     // element right by 32 bits and re-extract the lower XLEN bits.
6258     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6259                                      DAG.getConstant(32, DL, XLenVT), VL);
6260     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6261                                  ThirtyTwoV, Mask, VL);
6262 
6263     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6264 
6265     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6266     break;
6267   }
6268   case ISD::INTRINSIC_WO_CHAIN: {
6269     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6270     switch (IntNo) {
6271     default:
6272       llvm_unreachable(
6273           "Don't know how to custom type legalize this intrinsic!");
6274     case Intrinsic::riscv_orc_b: {
6275       // Lower to the GORCI encoding for orc.b with the operand extended.
6276       SDValue NewOp =
6277           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6278       // If Zbp is enabled, use GORCIW which will sign extend the result.
6279       unsigned Opc =
6280           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6281       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6282                                 DAG.getConstant(7, DL, MVT::i64));
6283       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6284       return;
6285     }
6286     case Intrinsic::riscv_grev:
6287     case Intrinsic::riscv_gorc: {
6288       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6289              "Unexpected custom legalisation");
6290       SDValue NewOp1 =
6291           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6292       SDValue NewOp2 =
6293           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6294       unsigned Opc =
6295           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
6296       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6297       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6298       break;
6299     }
6300     case Intrinsic::riscv_shfl:
6301     case Intrinsic::riscv_unshfl: {
6302       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6303              "Unexpected custom legalisation");
6304       SDValue NewOp1 =
6305           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6306       SDValue NewOp2 =
6307           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6308       unsigned Opc =
6309           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6310       if (isa<ConstantSDNode>(N->getOperand(2))) {
6311         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6312                              DAG.getConstant(0xf, DL, MVT::i64));
6313         Opc =
6314             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6315       }
6316       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6317       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6318       break;
6319     }
6320     case Intrinsic::riscv_bcompress:
6321     case Intrinsic::riscv_bdecompress: {
6322       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6323              "Unexpected custom legalisation");
6324       SDValue NewOp1 =
6325           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6326       SDValue NewOp2 =
6327           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6328       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
6329                          ? RISCVISD::BCOMPRESSW
6330                          : RISCVISD::BDECOMPRESSW;
6331       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6332       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6333       break;
6334     }
6335     case Intrinsic::riscv_bfp: {
6336       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6337              "Unexpected custom legalisation");
6338       SDValue NewOp1 =
6339           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6340       SDValue NewOp2 =
6341           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6342       SDValue Res = DAG.getNode(RISCVISD::BFPW, DL, MVT::i64, NewOp1, NewOp2);
6343       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6344       break;
6345     }
6346     case Intrinsic::riscv_vmv_x_s: {
6347       EVT VT = N->getValueType(0);
6348       MVT XLenVT = Subtarget.getXLenVT();
6349       if (VT.bitsLT(XLenVT)) {
6350         // Simple case just extract using vmv.x.s and truncate.
6351         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6352                                       Subtarget.getXLenVT(), N->getOperand(1));
6353         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6354         return;
6355       }
6356 
6357       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6358              "Unexpected custom legalization");
6359 
6360       // We need to do the move in two steps.
6361       SDValue Vec = N->getOperand(1);
6362       MVT VecVT = Vec.getSimpleValueType();
6363 
6364       // First extract the lower XLEN bits of the element.
6365       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6366 
6367       // To extract the upper XLEN bits of the vector element, shift the first
6368       // element right by 32 bits and re-extract the lower XLEN bits.
6369       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6370       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6371       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6372       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6373                                        DAG.getConstant(32, DL, XLenVT), VL);
6374       SDValue LShr32 =
6375           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6376       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6377 
6378       Results.push_back(
6379           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6380       break;
6381     }
6382     }
6383     break;
6384   }
6385   case ISD::VECREDUCE_ADD:
6386   case ISD::VECREDUCE_AND:
6387   case ISD::VECREDUCE_OR:
6388   case ISD::VECREDUCE_XOR:
6389   case ISD::VECREDUCE_SMAX:
6390   case ISD::VECREDUCE_UMAX:
6391   case ISD::VECREDUCE_SMIN:
6392   case ISD::VECREDUCE_UMIN:
6393     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6394       Results.push_back(V);
6395     break;
6396   case ISD::VP_REDUCE_ADD:
6397   case ISD::VP_REDUCE_AND:
6398   case ISD::VP_REDUCE_OR:
6399   case ISD::VP_REDUCE_XOR:
6400   case ISD::VP_REDUCE_SMAX:
6401   case ISD::VP_REDUCE_UMAX:
6402   case ISD::VP_REDUCE_SMIN:
6403   case ISD::VP_REDUCE_UMIN:
6404     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6405       Results.push_back(V);
6406     break;
6407   case ISD::FLT_ROUNDS_: {
6408     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6409     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6410     Results.push_back(Res.getValue(0));
6411     Results.push_back(Res.getValue(1));
6412     break;
6413   }
6414   }
6415 }
6416 
6417 // A structure to hold one of the bit-manipulation patterns below. Together, a
6418 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6419 //   (or (and (shl x, 1), 0xAAAAAAAA),
6420 //       (and (srl x, 1), 0x55555555))
6421 struct RISCVBitmanipPat {
6422   SDValue Op;
6423   unsigned ShAmt;
6424   bool IsSHL;
6425 
6426   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6427     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6428   }
6429 };
6430 
6431 // Matches patterns of the form
6432 //   (and (shl x, C2), (C1 << C2))
6433 //   (and (srl x, C2), C1)
6434 //   (shl (and x, C1), C2)
6435 //   (srl (and x, (C1 << C2)), C2)
6436 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6437 // The expected masks for each shift amount are specified in BitmanipMasks where
6438 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6439 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6440 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6441 // XLen is 64.
6442 static Optional<RISCVBitmanipPat>
6443 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6444   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6445          "Unexpected number of masks");
6446   Optional<uint64_t> Mask;
6447   // Optionally consume a mask around the shift operation.
6448   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6449     Mask = Op.getConstantOperandVal(1);
6450     Op = Op.getOperand(0);
6451   }
6452   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6453     return None;
6454   bool IsSHL = Op.getOpcode() == ISD::SHL;
6455 
6456   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6457     return None;
6458   uint64_t ShAmt = Op.getConstantOperandVal(1);
6459 
6460   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6461   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6462     return None;
6463   // If we don't have enough masks for 64 bit, then we must be trying to
6464   // match SHFL so we're only allowed to shift 1/4 of the width.
6465   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6466     return None;
6467 
6468   SDValue Src = Op.getOperand(0);
6469 
6470   // The expected mask is shifted left when the AND is found around SHL
6471   // patterns.
6472   //   ((x >> 1) & 0x55555555)
6473   //   ((x << 1) & 0xAAAAAAAA)
6474   bool SHLExpMask = IsSHL;
6475 
6476   if (!Mask) {
6477     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6478     // the mask is all ones: consume that now.
6479     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6480       Mask = Src.getConstantOperandVal(1);
6481       Src = Src.getOperand(0);
6482       // The expected mask is now in fact shifted left for SRL, so reverse the
6483       // decision.
6484       //   ((x & 0xAAAAAAAA) >> 1)
6485       //   ((x & 0x55555555) << 1)
6486       SHLExpMask = !SHLExpMask;
6487     } else {
6488       // Use a default shifted mask of all-ones if there's no AND, truncated
6489       // down to the expected width. This simplifies the logic later on.
6490       Mask = maskTrailingOnes<uint64_t>(Width);
6491       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6492     }
6493   }
6494 
6495   unsigned MaskIdx = Log2_32(ShAmt);
6496   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6497 
6498   if (SHLExpMask)
6499     ExpMask <<= ShAmt;
6500 
6501   if (Mask != ExpMask)
6502     return None;
6503 
6504   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6505 }
6506 
6507 // Matches any of the following bit-manipulation patterns:
6508 //   (and (shl x, 1), (0x55555555 << 1))
6509 //   (and (srl x, 1), 0x55555555)
6510 //   (shl (and x, 0x55555555), 1)
6511 //   (srl (and x, (0x55555555 << 1)), 1)
6512 // where the shift amount and mask may vary thus:
6513 //   [1]  = 0x55555555 / 0xAAAAAAAA
6514 //   [2]  = 0x33333333 / 0xCCCCCCCC
6515 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6516 //   [8]  = 0x00FF00FF / 0xFF00FF00
6517 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6518 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6519 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6520   // These are the unshifted masks which we use to match bit-manipulation
6521   // patterns. They may be shifted left in certain circumstances.
6522   static const uint64_t BitmanipMasks[] = {
6523       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6524       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6525 
6526   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6527 }
6528 
6529 // Match the following pattern as a GREVI(W) operation
6530 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6531 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6532                                const RISCVSubtarget &Subtarget) {
6533   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6534   EVT VT = Op.getValueType();
6535 
6536   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6537     auto LHS = matchGREVIPat(Op.getOperand(0));
6538     auto RHS = matchGREVIPat(Op.getOperand(1));
6539     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6540       SDLoc DL(Op);
6541       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6542                          DAG.getConstant(LHS->ShAmt, DL, VT));
6543     }
6544   }
6545   return SDValue();
6546 }
6547 
6548 // Matches any the following pattern as a GORCI(W) operation
6549 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6550 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6551 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6552 // Note that with the variant of 3.,
6553 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6554 // the inner pattern will first be matched as GREVI and then the outer
6555 // pattern will be matched to GORC via the first rule above.
6556 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6557 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6558                                const RISCVSubtarget &Subtarget) {
6559   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6560   EVT VT = Op.getValueType();
6561 
6562   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6563     SDLoc DL(Op);
6564     SDValue Op0 = Op.getOperand(0);
6565     SDValue Op1 = Op.getOperand(1);
6566 
6567     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6568       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6569           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6570           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6571         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6572       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6573       if ((Reverse.getOpcode() == ISD::ROTL ||
6574            Reverse.getOpcode() == ISD::ROTR) &&
6575           Reverse.getOperand(0) == X &&
6576           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6577         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6578         if (RotAmt == (VT.getSizeInBits() / 2))
6579           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6580                              DAG.getConstant(RotAmt, DL, VT));
6581       }
6582       return SDValue();
6583     };
6584 
6585     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6586     if (SDValue V = MatchOROfReverse(Op0, Op1))
6587       return V;
6588     if (SDValue V = MatchOROfReverse(Op1, Op0))
6589       return V;
6590 
6591     // OR is commutable so canonicalize its OR operand to the left
6592     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6593       std::swap(Op0, Op1);
6594     if (Op0.getOpcode() != ISD::OR)
6595       return SDValue();
6596     SDValue OrOp0 = Op0.getOperand(0);
6597     SDValue OrOp1 = Op0.getOperand(1);
6598     auto LHS = matchGREVIPat(OrOp0);
6599     // OR is commutable so swap the operands and try again: x might have been
6600     // on the left
6601     if (!LHS) {
6602       std::swap(OrOp0, OrOp1);
6603       LHS = matchGREVIPat(OrOp0);
6604     }
6605     auto RHS = matchGREVIPat(Op1);
6606     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6607       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6608                          DAG.getConstant(LHS->ShAmt, DL, VT));
6609     }
6610   }
6611   return SDValue();
6612 }
6613 
6614 // Matches any of the following bit-manipulation patterns:
6615 //   (and (shl x, 1), (0x22222222 << 1))
6616 //   (and (srl x, 1), 0x22222222)
6617 //   (shl (and x, 0x22222222), 1)
6618 //   (srl (and x, (0x22222222 << 1)), 1)
6619 // where the shift amount and mask may vary thus:
6620 //   [1]  = 0x22222222 / 0x44444444
6621 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6622 //   [4]  = 0x00F000F0 / 0x0F000F00
6623 //   [8]  = 0x0000FF00 / 0x00FF0000
6624 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6625 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6626   // These are the unshifted masks which we use to match bit-manipulation
6627   // patterns. They may be shifted left in certain circumstances.
6628   static const uint64_t BitmanipMasks[] = {
6629       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6630       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6631 
6632   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6633 }
6634 
6635 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6636 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6637                                const RISCVSubtarget &Subtarget) {
6638   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6639   EVT VT = Op.getValueType();
6640 
6641   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6642     return SDValue();
6643 
6644   SDValue Op0 = Op.getOperand(0);
6645   SDValue Op1 = Op.getOperand(1);
6646 
6647   // Or is commutable so canonicalize the second OR to the LHS.
6648   if (Op0.getOpcode() != ISD::OR)
6649     std::swap(Op0, Op1);
6650   if (Op0.getOpcode() != ISD::OR)
6651     return SDValue();
6652 
6653   // We found an inner OR, so our operands are the operands of the inner OR
6654   // and the other operand of the outer OR.
6655   SDValue A = Op0.getOperand(0);
6656   SDValue B = Op0.getOperand(1);
6657   SDValue C = Op1;
6658 
6659   auto Match1 = matchSHFLPat(A);
6660   auto Match2 = matchSHFLPat(B);
6661 
6662   // If neither matched, we failed.
6663   if (!Match1 && !Match2)
6664     return SDValue();
6665 
6666   // We had at least one match. if one failed, try the remaining C operand.
6667   if (!Match1) {
6668     std::swap(A, C);
6669     Match1 = matchSHFLPat(A);
6670     if (!Match1)
6671       return SDValue();
6672   } else if (!Match2) {
6673     std::swap(B, C);
6674     Match2 = matchSHFLPat(B);
6675     if (!Match2)
6676       return SDValue();
6677   }
6678   assert(Match1 && Match2);
6679 
6680   // Make sure our matches pair up.
6681   if (!Match1->formsPairWith(*Match2))
6682     return SDValue();
6683 
6684   // All the remains is to make sure C is an AND with the same input, that masks
6685   // out the bits that are being shuffled.
6686   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
6687       C.getOperand(0) != Match1->Op)
6688     return SDValue();
6689 
6690   uint64_t Mask = C.getConstantOperandVal(1);
6691 
6692   static const uint64_t BitmanipMasks[] = {
6693       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
6694       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
6695   };
6696 
6697   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6698   unsigned MaskIdx = Log2_32(Match1->ShAmt);
6699   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6700 
6701   if (Mask != ExpMask)
6702     return SDValue();
6703 
6704   SDLoc DL(Op);
6705   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
6706                      DAG.getConstant(Match1->ShAmt, DL, VT));
6707 }
6708 
6709 // Optimize (add (shl x, c0), (shl y, c1)) ->
6710 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
6711 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
6712                                   const RISCVSubtarget &Subtarget) {
6713   // Perform this optimization only in the zba extension.
6714   if (!Subtarget.hasStdExtZba())
6715     return SDValue();
6716 
6717   // Skip for vector types and larger types.
6718   EVT VT = N->getValueType(0);
6719   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6720     return SDValue();
6721 
6722   // The two operand nodes must be SHL and have no other use.
6723   SDValue N0 = N->getOperand(0);
6724   SDValue N1 = N->getOperand(1);
6725   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
6726       !N0->hasOneUse() || !N1->hasOneUse())
6727     return SDValue();
6728 
6729   // Check c0 and c1.
6730   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6731   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
6732   if (!N0C || !N1C)
6733     return SDValue();
6734   int64_t C0 = N0C->getSExtValue();
6735   int64_t C1 = N1C->getSExtValue();
6736   if (C0 <= 0 || C1 <= 0)
6737     return SDValue();
6738 
6739   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
6740   int64_t Bits = std::min(C0, C1);
6741   int64_t Diff = std::abs(C0 - C1);
6742   if (Diff != 1 && Diff != 2 && Diff != 3)
6743     return SDValue();
6744 
6745   // Build nodes.
6746   SDLoc DL(N);
6747   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
6748   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
6749   SDValue NA0 =
6750       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
6751   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
6752   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
6753 }
6754 
6755 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
6756 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
6757 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
6758 // not undo itself, but they are redundant.
6759 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
6760   SDValue Src = N->getOperand(0);
6761 
6762   if (Src.getOpcode() != N->getOpcode())
6763     return SDValue();
6764 
6765   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
6766       !isa<ConstantSDNode>(Src.getOperand(1)))
6767     return SDValue();
6768 
6769   unsigned ShAmt1 = N->getConstantOperandVal(1);
6770   unsigned ShAmt2 = Src.getConstantOperandVal(1);
6771   Src = Src.getOperand(0);
6772 
6773   unsigned CombinedShAmt;
6774   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
6775     CombinedShAmt = ShAmt1 | ShAmt2;
6776   else
6777     CombinedShAmt = ShAmt1 ^ ShAmt2;
6778 
6779   if (CombinedShAmt == 0)
6780     return Src;
6781 
6782   SDLoc DL(N);
6783   return DAG.getNode(
6784       N->getOpcode(), DL, N->getValueType(0), Src,
6785       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
6786 }
6787 
6788 // Combine a constant select operand into its use:
6789 //
6790 // (and (select cond, -1, c), x)
6791 //   -> (select cond, x, (and x, c))  [AllOnes=1]
6792 // (or  (select cond, 0, c), x)
6793 //   -> (select cond, x, (or x, c))  [AllOnes=0]
6794 // (xor (select cond, 0, c), x)
6795 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
6796 // (add (select cond, 0, c), x)
6797 //   -> (select cond, x, (add x, c))  [AllOnes=0]
6798 // (sub x, (select cond, 0, c))
6799 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
6800 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6801                                    SelectionDAG &DAG, bool AllOnes) {
6802   EVT VT = N->getValueType(0);
6803 
6804   // Skip vectors.
6805   if (VT.isVector())
6806     return SDValue();
6807 
6808   if ((Slct.getOpcode() != ISD::SELECT &&
6809        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
6810       !Slct.hasOneUse())
6811     return SDValue();
6812 
6813   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
6814     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
6815   };
6816 
6817   bool SwapSelectOps;
6818   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
6819   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
6820   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
6821   SDValue NonConstantVal;
6822   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
6823     SwapSelectOps = false;
6824     NonConstantVal = FalseVal;
6825   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
6826     SwapSelectOps = true;
6827     NonConstantVal = TrueVal;
6828   } else
6829     return SDValue();
6830 
6831   // Slct is now know to be the desired identity constant when CC is true.
6832   TrueVal = OtherOp;
6833   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
6834   // Unless SwapSelectOps says the condition should be false.
6835   if (SwapSelectOps)
6836     std::swap(TrueVal, FalseVal);
6837 
6838   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
6839     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
6840                        {Slct.getOperand(0), Slct.getOperand(1),
6841                         Slct.getOperand(2), TrueVal, FalseVal});
6842 
6843   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
6844                      {Slct.getOperand(0), TrueVal, FalseVal});
6845 }
6846 
6847 // Attempt combineSelectAndUse on each operand of a commutative operator N.
6848 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
6849                                               bool AllOnes) {
6850   SDValue N0 = N->getOperand(0);
6851   SDValue N1 = N->getOperand(1);
6852   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
6853     return Result;
6854   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
6855     return Result;
6856   return SDValue();
6857 }
6858 
6859 // Transform (add (mul x, c0), c1) ->
6860 //           (add (mul (add x, c1/c0), c0), c1%c0).
6861 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
6862 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
6863 // to an infinite loop in DAGCombine if transformed.
6864 // Or transform (add (mul x, c0), c1) ->
6865 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
6866 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
6867 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
6868 // lead to an infinite loop in DAGCombine if transformed.
6869 // Or transform (add (mul x, c0), c1) ->
6870 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
6871 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
6872 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
6873 // lead to an infinite loop in DAGCombine if transformed.
6874 // Or transform (add (mul x, c0), c1) ->
6875 //              (mul (add x, c1/c0), c0).
6876 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
6877 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
6878                                      const RISCVSubtarget &Subtarget) {
6879   // Skip for vector types and larger types.
6880   EVT VT = N->getValueType(0);
6881   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
6882     return SDValue();
6883   // The first operand node must be a MUL and has no other use.
6884   SDValue N0 = N->getOperand(0);
6885   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
6886     return SDValue();
6887   // Check if c0 and c1 match above conditions.
6888   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6889   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6890   if (!N0C || !N1C)
6891     return SDValue();
6892   int64_t C0 = N0C->getSExtValue();
6893   int64_t C1 = N1C->getSExtValue();
6894   int64_t CA, CB;
6895   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
6896     return SDValue();
6897   // Search for proper CA (non-zero) and CB that both are simm12.
6898   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
6899       !isInt<12>(C0 * (C1 / C0))) {
6900     CA = C1 / C0;
6901     CB = C1 % C0;
6902   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
6903              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
6904     CA = C1 / C0 + 1;
6905     CB = C1 % C0 - C0;
6906   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
6907              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
6908     CA = C1 / C0 - 1;
6909     CB = C1 % C0 + C0;
6910   } else
6911     return SDValue();
6912   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
6913   SDLoc DL(N);
6914   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
6915                              DAG.getConstant(CA, DL, VT));
6916   SDValue New1 =
6917       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
6918   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
6919 }
6920 
6921 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
6922                                  const RISCVSubtarget &Subtarget) {
6923   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
6924     return V;
6925   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
6926     return V;
6927   // fold (add (select lhs, rhs, cc, 0, y), x) ->
6928   //      (select lhs, rhs, cc, x, (add x, y))
6929   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6930 }
6931 
6932 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
6933   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
6934   //      (select lhs, rhs, cc, x, (sub x, y))
6935   SDValue N0 = N->getOperand(0);
6936   SDValue N1 = N->getOperand(1);
6937   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
6938 }
6939 
6940 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
6941   // fold (and (select lhs, rhs, cc, -1, y), x) ->
6942   //      (select lhs, rhs, cc, x, (and x, y))
6943   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
6944 }
6945 
6946 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
6947                                 const RISCVSubtarget &Subtarget) {
6948   if (Subtarget.hasStdExtZbp()) {
6949     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
6950       return GREV;
6951     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
6952       return GORC;
6953     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
6954       return SHFL;
6955   }
6956 
6957   // fold (or (select cond, 0, y), x) ->
6958   //      (select cond, x, (or x, y))
6959   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6960 }
6961 
6962 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
6963   // fold (xor (select cond, 0, y), x) ->
6964   //      (select cond, x, (xor x, y))
6965   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
6966 }
6967 
6968 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
6969 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
6970 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
6971 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
6972 // ADDW/SUBW/MULW.
6973 static SDValue performANY_EXTENDCombine(SDNode *N,
6974                                         TargetLowering::DAGCombinerInfo &DCI,
6975                                         const RISCVSubtarget &Subtarget) {
6976   if (!Subtarget.is64Bit())
6977     return SDValue();
6978 
6979   SelectionDAG &DAG = DCI.DAG;
6980 
6981   SDValue Src = N->getOperand(0);
6982   EVT VT = N->getValueType(0);
6983   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
6984     return SDValue();
6985 
6986   // The opcode must be one that can implicitly sign_extend.
6987   // FIXME: Additional opcodes.
6988   switch (Src.getOpcode()) {
6989   default:
6990     return SDValue();
6991   case ISD::MUL:
6992     if (!Subtarget.hasStdExtM())
6993       return SDValue();
6994     LLVM_FALLTHROUGH;
6995   case ISD::ADD:
6996   case ISD::SUB:
6997     break;
6998   }
6999 
7000   // Only handle cases where the result is used by a CopyToReg. That likely
7001   // means the value is a liveout of the basic block. This helps prevent
7002   // infinite combine loops like PR51206.
7003   if (none_of(N->uses(),
7004               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7005     return SDValue();
7006 
7007   SmallVector<SDNode *, 4> SetCCs;
7008   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7009                             UE = Src.getNode()->use_end();
7010        UI != UE; ++UI) {
7011     SDNode *User = *UI;
7012     if (User == N)
7013       continue;
7014     if (UI.getUse().getResNo() != Src.getResNo())
7015       continue;
7016     // All i32 setccs are legalized by sign extending operands.
7017     if (User->getOpcode() == ISD::SETCC) {
7018       SetCCs.push_back(User);
7019       continue;
7020     }
7021     // We don't know if we can extend this user.
7022     break;
7023   }
7024 
7025   // If we don't have any SetCCs, this isn't worthwhile.
7026   if (SetCCs.empty())
7027     return SDValue();
7028 
7029   SDLoc DL(N);
7030   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7031   DCI.CombineTo(N, SExt);
7032 
7033   // Promote all the setccs.
7034   for (SDNode *SetCC : SetCCs) {
7035     SmallVector<SDValue, 4> Ops;
7036 
7037     for (unsigned j = 0; j != 2; ++j) {
7038       SDValue SOp = SetCC->getOperand(j);
7039       if (SOp == Src)
7040         Ops.push_back(SExt);
7041       else
7042         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7043     }
7044 
7045     Ops.push_back(SetCC->getOperand(2));
7046     DCI.CombineTo(SetCC,
7047                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7048   }
7049   return SDValue(N, 0);
7050 }
7051 
7052 // Try to form VWMUL or VWMULU.
7053 // FIXME: Support VWMULSU.
7054 static SDValue combineMUL_VLToVWMUL(SDNode *N, SDValue Op0, SDValue Op1,
7055                                     SelectionDAG &DAG) {
7056   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7057   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7058   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7059   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7060     return SDValue();
7061 
7062   SDValue Mask = N->getOperand(2);
7063   SDValue VL = N->getOperand(3);
7064 
7065   // Make sure the mask and VL match.
7066   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7067     return SDValue();
7068 
7069   MVT VT = N->getSimpleValueType(0);
7070 
7071   // Determine the narrow size for a widening multiply.
7072   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7073   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7074                                   VT.getVectorElementCount());
7075 
7076   SDLoc DL(N);
7077 
7078   // See if the other operand is the same opcode.
7079   if (Op0.getOpcode() == Op1.getOpcode()) {
7080     if (!Op1.hasOneUse())
7081       return SDValue();
7082 
7083     // Make sure the mask and VL match.
7084     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7085       return SDValue();
7086 
7087     Op1 = Op1.getOperand(0);
7088   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7089     // The operand is a splat of a scalar.
7090 
7091     // The VL must be the same.
7092     if (Op1.getOperand(1) != VL)
7093       return SDValue();
7094 
7095     // Get the scalar value.
7096     Op1 = Op1.getOperand(0);
7097 
7098     // See if have enough sign bits or zero bits in the scalar to use a
7099     // widening multiply by splatting to smaller element size.
7100     unsigned EltBits = VT.getScalarSizeInBits();
7101     unsigned ScalarBits = Op1.getValueSizeInBits();
7102     // Make sure we're getting all element bits from the scalar register.
7103     // FIXME: Support implicit sign extension of vmv.v.x?
7104     if (ScalarBits < EltBits)
7105       return SDValue();
7106 
7107     if (IsSignExt) {
7108       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7109         return SDValue();
7110     } else {
7111       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7112       if (!DAG.MaskedValueIsZero(Op1, Mask))
7113         return SDValue();
7114     }
7115 
7116     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7117   } else
7118     return SDValue();
7119 
7120   Op0 = Op0.getOperand(0);
7121 
7122   // Re-introduce narrower extends if needed.
7123   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7124   if (Op0.getValueType() != NarrowVT)
7125     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7126   if (Op1.getValueType() != NarrowVT)
7127     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7128 
7129   unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7130   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7131 }
7132 
7133 // Fold
7134 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7135 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7136 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7137 //   (fp_to_int (fceil X))      -> fcvt X, rup
7138 //   (fp_to_int (fround X))     -> fcvt X, rmm
7139 // FIXME: We should also do this for fp_to_int_sat.
7140 static SDValue performFP_TO_INTCombine(SDNode *N,
7141                                        TargetLowering::DAGCombinerInfo &DCI,
7142                                        const RISCVSubtarget &Subtarget) {
7143   SelectionDAG &DAG = DCI.DAG;
7144   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7145   MVT XLenVT = Subtarget.getXLenVT();
7146 
7147   // Only handle XLen or i32 types. Other types narrower than XLen will
7148   // eventually be legalized to XLenVT.
7149   EVT VT = N->getValueType(0);
7150   if (VT != MVT::i32 && VT != XLenVT)
7151     return SDValue();
7152 
7153   SDValue Src = N->getOperand(0);
7154 
7155   // Ensure the FP type is also legal.
7156   if (!TLI.isTypeLegal(Src.getValueType()))
7157     return SDValue();
7158 
7159   // Don't do this for f16 with Zfhmin and not Zfh.
7160   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7161     return SDValue();
7162 
7163   RISCVFPRndMode::RoundingMode FRM;
7164   switch (Src->getOpcode()) {
7165   default:
7166     return SDValue();
7167   case ISD::FROUNDEVEN: FRM = RISCVFPRndMode::RNE; break;
7168   case ISD::FTRUNC:     FRM = RISCVFPRndMode::RTZ; break;
7169   case ISD::FFLOOR:     FRM = RISCVFPRndMode::RDN; break;
7170   case ISD::FCEIL:      FRM = RISCVFPRndMode::RUP; break;
7171   case ISD::FROUND:     FRM = RISCVFPRndMode::RMM; break;
7172   }
7173 
7174   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7175 
7176   unsigned Opc;
7177   if (VT == XLenVT)
7178     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7179   else
7180     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7181 
7182   SDLoc DL(N);
7183   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7184                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7185   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7186 }
7187 
7188 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7189                                                DAGCombinerInfo &DCI) const {
7190   SelectionDAG &DAG = DCI.DAG;
7191 
7192   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7193   // bits are demanded. N will be added to the Worklist if it was not deleted.
7194   // Caller should return SDValue(N, 0) if this returns true.
7195   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7196     SDValue Op = N->getOperand(OpNo);
7197     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7198     if (!SimplifyDemandedBits(Op, Mask, DCI))
7199       return false;
7200 
7201     if (N->getOpcode() != ISD::DELETED_NODE)
7202       DCI.AddToWorklist(N);
7203     return true;
7204   };
7205 
7206   switch (N->getOpcode()) {
7207   default:
7208     break;
7209   case RISCVISD::SplitF64: {
7210     SDValue Op0 = N->getOperand(0);
7211     // If the input to SplitF64 is just BuildPairF64 then the operation is
7212     // redundant. Instead, use BuildPairF64's operands directly.
7213     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7214       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7215 
7216     SDLoc DL(N);
7217 
7218     // It's cheaper to materialise two 32-bit integers than to load a double
7219     // from the constant pool and transfer it to integer registers through the
7220     // stack.
7221     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7222       APInt V = C->getValueAPF().bitcastToAPInt();
7223       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7224       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7225       return DCI.CombineTo(N, Lo, Hi);
7226     }
7227 
7228     // This is a target-specific version of a DAGCombine performed in
7229     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7230     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7231     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7232     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7233         !Op0.getNode()->hasOneUse())
7234       break;
7235     SDValue NewSplitF64 =
7236         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7237                     Op0.getOperand(0));
7238     SDValue Lo = NewSplitF64.getValue(0);
7239     SDValue Hi = NewSplitF64.getValue(1);
7240     APInt SignBit = APInt::getSignMask(32);
7241     if (Op0.getOpcode() == ISD::FNEG) {
7242       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7243                                   DAG.getConstant(SignBit, DL, MVT::i32));
7244       return DCI.CombineTo(N, Lo, NewHi);
7245     }
7246     assert(Op0.getOpcode() == ISD::FABS);
7247     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7248                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7249     return DCI.CombineTo(N, Lo, NewHi);
7250   }
7251   case RISCVISD::SLLW:
7252   case RISCVISD::SRAW:
7253   case RISCVISD::SRLW:
7254   case RISCVISD::ROLW:
7255   case RISCVISD::RORW: {
7256     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7257     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7258         SimplifyDemandedLowBitsHelper(1, 5))
7259       return SDValue(N, 0);
7260     break;
7261   }
7262   case RISCVISD::CLZW:
7263   case RISCVISD::CTZW: {
7264     // Only the lower 32 bits of the first operand are read
7265     if (SimplifyDemandedLowBitsHelper(0, 32))
7266       return SDValue(N, 0);
7267     break;
7268   }
7269   case RISCVISD::FSL:
7270   case RISCVISD::FSR: {
7271     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
7272     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
7273     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7274     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
7275       return SDValue(N, 0);
7276     break;
7277   }
7278   case RISCVISD::FSLW:
7279   case RISCVISD::FSRW: {
7280     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
7281     // read.
7282     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7283         SimplifyDemandedLowBitsHelper(1, 32) ||
7284         SimplifyDemandedLowBitsHelper(2, 6))
7285       return SDValue(N, 0);
7286     break;
7287   }
7288   case RISCVISD::GREV:
7289   case RISCVISD::GORC: {
7290     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7291     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7292     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7293     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7294       return SDValue(N, 0);
7295 
7296     return combineGREVI_GORCI(N, DAG);
7297   }
7298   case RISCVISD::GREVW:
7299   case RISCVISD::GORCW: {
7300     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7301     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7302         SimplifyDemandedLowBitsHelper(1, 5))
7303       return SDValue(N, 0);
7304 
7305     return combineGREVI_GORCI(N, DAG);
7306   }
7307   case RISCVISD::SHFL:
7308   case RISCVISD::UNSHFL: {
7309     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7310     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7311     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7312     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7313       return SDValue(N, 0);
7314 
7315     break;
7316   }
7317   case RISCVISD::SHFLW:
7318   case RISCVISD::UNSHFLW: {
7319     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7320     SDValue LHS = N->getOperand(0);
7321     SDValue RHS = N->getOperand(1);
7322     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7323     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7324     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7325         SimplifyDemandedLowBitsHelper(1, 4))
7326       return SDValue(N, 0);
7327 
7328     break;
7329   }
7330   case RISCVISD::BCOMPRESSW:
7331   case RISCVISD::BDECOMPRESSW: {
7332     // Only the lower 32 bits of LHS and RHS are read.
7333     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7334         SimplifyDemandedLowBitsHelper(1, 32))
7335       return SDValue(N, 0);
7336 
7337     break;
7338   }
7339   case RISCVISD::FMV_X_ANYEXTH:
7340   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7341     SDLoc DL(N);
7342     SDValue Op0 = N->getOperand(0);
7343     MVT VT = N->getSimpleValueType(0);
7344     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7345     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7346     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7347     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7348          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7349         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7350          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7351       assert(Op0.getOperand(0).getValueType() == VT &&
7352              "Unexpected value type!");
7353       return Op0.getOperand(0);
7354     }
7355 
7356     // This is a target-specific version of a DAGCombine performed in
7357     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7358     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7359     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7360     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7361         !Op0.getNode()->hasOneUse())
7362       break;
7363     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7364     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7365     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7366     if (Op0.getOpcode() == ISD::FNEG)
7367       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7368                          DAG.getConstant(SignBit, DL, VT));
7369 
7370     assert(Op0.getOpcode() == ISD::FABS);
7371     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7372                        DAG.getConstant(~SignBit, DL, VT));
7373   }
7374   case ISD::ADD:
7375     return performADDCombine(N, DAG, Subtarget);
7376   case ISD::SUB:
7377     return performSUBCombine(N, DAG);
7378   case ISD::AND:
7379     return performANDCombine(N, DAG);
7380   case ISD::OR:
7381     return performORCombine(N, DAG, Subtarget);
7382   case ISD::XOR:
7383     return performXORCombine(N, DAG);
7384   case ISD::ANY_EXTEND:
7385     return performANY_EXTENDCombine(N, DCI, Subtarget);
7386   case ISD::ZERO_EXTEND:
7387     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7388     // type legalization. This is safe because fp_to_uint produces poison if
7389     // it overflows.
7390     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7391       SDValue Src = N->getOperand(0);
7392       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7393           isTypeLegal(Src.getOperand(0).getValueType()))
7394         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7395                            Src.getOperand(0));
7396       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7397           isTypeLegal(Src.getOperand(1).getValueType())) {
7398         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7399         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7400                                   Src.getOperand(0), Src.getOperand(1));
7401         DCI.CombineTo(N, Res);
7402         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7403         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7404         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7405       }
7406     }
7407     return SDValue();
7408   case RISCVISD::SELECT_CC: {
7409     // Transform
7410     SDValue LHS = N->getOperand(0);
7411     SDValue RHS = N->getOperand(1);
7412     SDValue TrueV = N->getOperand(3);
7413     SDValue FalseV = N->getOperand(4);
7414 
7415     // If the True and False values are the same, we don't need a select_cc.
7416     if (TrueV == FalseV)
7417       return TrueV;
7418 
7419     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7420     if (!ISD::isIntEqualitySetCC(CCVal))
7421       break;
7422 
7423     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7424     //      (select_cc X, Y, lt, trueV, falseV)
7425     // Sometimes the setcc is introduced after select_cc has been formed.
7426     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7427         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7428       // If we're looking for eq 0 instead of ne 0, we need to invert the
7429       // condition.
7430       bool Invert = CCVal == ISD::SETEQ;
7431       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7432       if (Invert)
7433         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7434 
7435       SDLoc DL(N);
7436       RHS = LHS.getOperand(1);
7437       LHS = LHS.getOperand(0);
7438       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7439 
7440       SDValue TargetCC = DAG.getCondCode(CCVal);
7441       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7442                          {LHS, RHS, TargetCC, TrueV, FalseV});
7443     }
7444 
7445     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7446     //      (select_cc X, Y, eq/ne, trueV, falseV)
7447     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7448       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7449                          {LHS.getOperand(0), LHS.getOperand(1),
7450                           N->getOperand(2), TrueV, FalseV});
7451     // (select_cc X, 1, setne, trueV, falseV) ->
7452     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7453     // This can occur when legalizing some floating point comparisons.
7454     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7455     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7456       SDLoc DL(N);
7457       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7458       SDValue TargetCC = DAG.getCondCode(CCVal);
7459       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7460       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7461                          {LHS, RHS, TargetCC, TrueV, FalseV});
7462     }
7463 
7464     break;
7465   }
7466   case RISCVISD::BR_CC: {
7467     SDValue LHS = N->getOperand(1);
7468     SDValue RHS = N->getOperand(2);
7469     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7470     if (!ISD::isIntEqualitySetCC(CCVal))
7471       break;
7472 
7473     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7474     //      (br_cc X, Y, lt, dest)
7475     // Sometimes the setcc is introduced after br_cc has been formed.
7476     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7477         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7478       // If we're looking for eq 0 instead of ne 0, we need to invert the
7479       // condition.
7480       bool Invert = CCVal == ISD::SETEQ;
7481       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7482       if (Invert)
7483         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7484 
7485       SDLoc DL(N);
7486       RHS = LHS.getOperand(1);
7487       LHS = LHS.getOperand(0);
7488       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7489 
7490       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7491                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7492                          N->getOperand(4));
7493     }
7494 
7495     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7496     //      (br_cc X, Y, eq/ne, trueV, falseV)
7497     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7498       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7499                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7500                          N->getOperand(3), N->getOperand(4));
7501 
7502     // (br_cc X, 1, setne, br_cc) ->
7503     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7504     // This can occur when legalizing some floating point comparisons.
7505     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7506     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7507       SDLoc DL(N);
7508       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7509       SDValue TargetCC = DAG.getCondCode(CCVal);
7510       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7511       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7512                          N->getOperand(0), LHS, RHS, TargetCC,
7513                          N->getOperand(4));
7514     }
7515     break;
7516   }
7517   case ISD::FP_TO_SINT:
7518   case ISD::FP_TO_UINT:
7519     return performFP_TO_INTCombine(N, DCI, Subtarget);
7520   case ISD::FCOPYSIGN: {
7521     EVT VT = N->getValueType(0);
7522     if (!VT.isVector())
7523       break;
7524     // There is a form of VFSGNJ which injects the negated sign of its second
7525     // operand. Try and bubble any FNEG up after the extend/round to produce
7526     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7527     // TRUNC=1.
7528     SDValue In2 = N->getOperand(1);
7529     // Avoid cases where the extend/round has multiple uses, as duplicating
7530     // those is typically more expensive than removing a fneg.
7531     if (!In2.hasOneUse())
7532       break;
7533     if (In2.getOpcode() != ISD::FP_EXTEND &&
7534         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7535       break;
7536     In2 = In2.getOperand(0);
7537     if (In2.getOpcode() != ISD::FNEG)
7538       break;
7539     SDLoc DL(N);
7540     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7541     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7542                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7543   }
7544   case ISD::MGATHER:
7545   case ISD::MSCATTER:
7546   case ISD::VP_GATHER:
7547   case ISD::VP_SCATTER: {
7548     if (!DCI.isBeforeLegalize())
7549       break;
7550     SDValue Index, ScaleOp;
7551     bool IsIndexScaled = false;
7552     bool IsIndexSigned = false;
7553     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7554       Index = VPGSN->getIndex();
7555       ScaleOp = VPGSN->getScale();
7556       IsIndexScaled = VPGSN->isIndexScaled();
7557       IsIndexSigned = VPGSN->isIndexSigned();
7558     } else {
7559       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7560       Index = MGSN->getIndex();
7561       ScaleOp = MGSN->getScale();
7562       IsIndexScaled = MGSN->isIndexScaled();
7563       IsIndexSigned = MGSN->isIndexSigned();
7564     }
7565     EVT IndexVT = Index.getValueType();
7566     MVT XLenVT = Subtarget.getXLenVT();
7567     // RISCV indexed loads only support the "unsigned unscaled" addressing
7568     // mode, so anything else must be manually legalized.
7569     bool NeedsIdxLegalization =
7570         IsIndexScaled ||
7571         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7572     if (!NeedsIdxLegalization)
7573       break;
7574 
7575     SDLoc DL(N);
7576 
7577     // Any index legalization should first promote to XLenVT, so we don't lose
7578     // bits when scaling. This may create an illegal index type so we let
7579     // LLVM's legalization take care of the splitting.
7580     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7581     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7582       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7583       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7584                           DL, IndexVT, Index);
7585     }
7586 
7587     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7588     if (IsIndexScaled && Scale != 1) {
7589       // Manually scale the indices by the element size.
7590       // TODO: Sanitize the scale operand here?
7591       // TODO: For VP nodes, should we use VP_SHL here?
7592       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7593       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7594       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7595     }
7596 
7597     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7598     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7599       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7600                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7601                               VPGN->getScale(), VPGN->getMask(),
7602                               VPGN->getVectorLength()},
7603                              VPGN->getMemOperand(), NewIndexTy);
7604     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7605       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7606                               {VPSN->getChain(), VPSN->getValue(),
7607                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7608                                VPSN->getMask(), VPSN->getVectorLength()},
7609                               VPSN->getMemOperand(), NewIndexTy);
7610     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7611       return DAG.getMaskedGather(
7612           N->getVTList(), MGN->getMemoryVT(), DL,
7613           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7614            MGN->getBasePtr(), Index, MGN->getScale()},
7615           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7616     const auto *MSN = cast<MaskedScatterSDNode>(N);
7617     return DAG.getMaskedScatter(
7618         N->getVTList(), MSN->getMemoryVT(), DL,
7619         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7620          Index, MSN->getScale()},
7621         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7622   }
7623   case RISCVISD::SRA_VL:
7624   case RISCVISD::SRL_VL:
7625   case RISCVISD::SHL_VL: {
7626     SDValue ShAmt = N->getOperand(1);
7627     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7628       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7629       SDLoc DL(N);
7630       SDValue VL = N->getOperand(3);
7631       EVT VT = N->getValueType(0);
7632       ShAmt =
7633           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
7634       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
7635                          N->getOperand(2), N->getOperand(3));
7636     }
7637     break;
7638   }
7639   case ISD::SRA:
7640   case ISD::SRL:
7641   case ISD::SHL: {
7642     SDValue ShAmt = N->getOperand(1);
7643     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7644       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7645       SDLoc DL(N);
7646       EVT VT = N->getValueType(0);
7647       ShAmt =
7648           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
7649       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
7650     }
7651     break;
7652   }
7653   case RISCVISD::MUL_VL: {
7654     SDValue Op0 = N->getOperand(0);
7655     SDValue Op1 = N->getOperand(1);
7656     if (SDValue V = combineMUL_VLToVWMUL(N, Op0, Op1, DAG))
7657       return V;
7658     if (SDValue V = combineMUL_VLToVWMUL(N, Op1, Op0, DAG))
7659       return V;
7660     return SDValue();
7661   }
7662   case ISD::STORE: {
7663     auto *Store = cast<StoreSDNode>(N);
7664     SDValue Val = Store->getValue();
7665     // Combine store of vmv.x.s to vse with VL of 1.
7666     // FIXME: Support FP.
7667     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
7668       SDValue Src = Val.getOperand(0);
7669       EVT VecVT = Src.getValueType();
7670       EVT MemVT = Store->getMemoryVT();
7671       // The memory VT and the element type must match.
7672       if (VecVT.getVectorElementType() == MemVT) {
7673         SDLoc DL(N);
7674         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7675         return DAG.getStoreVP(Store->getChain(), DL, Src, Store->getBasePtr(),
7676                               DAG.getConstant(1, DL, MaskVT),
7677                               DAG.getConstant(1, DL, Subtarget.getXLenVT()),
7678                               Store->getPointerInfo(),
7679                               Store->getOriginalAlign(),
7680                               Store->getMemOperand()->getFlags());
7681       }
7682     }
7683 
7684     break;
7685   }
7686   }
7687 
7688   return SDValue();
7689 }
7690 
7691 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
7692     const SDNode *N, CombineLevel Level) const {
7693   // The following folds are only desirable if `(OP _, c1 << c2)` can be
7694   // materialised in fewer instructions than `(OP _, c1)`:
7695   //
7696   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7697   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7698   SDValue N0 = N->getOperand(0);
7699   EVT Ty = N0.getValueType();
7700   if (Ty.isScalarInteger() &&
7701       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
7702     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7703     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
7704     if (C1 && C2) {
7705       const APInt &C1Int = C1->getAPIntValue();
7706       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
7707 
7708       // We can materialise `c1 << c2` into an add immediate, so it's "free",
7709       // and the combine should happen, to potentially allow further combines
7710       // later.
7711       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
7712           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
7713         return true;
7714 
7715       // We can materialise `c1` in an add immediate, so it's "free", and the
7716       // combine should be prevented.
7717       if (C1Int.getMinSignedBits() <= 64 &&
7718           isLegalAddImmediate(C1Int.getSExtValue()))
7719         return false;
7720 
7721       // Neither constant will fit into an immediate, so find materialisation
7722       // costs.
7723       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
7724                                               Subtarget.getFeatureBits(),
7725                                               /*CompressionCost*/true);
7726       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
7727           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
7728           /*CompressionCost*/true);
7729 
7730       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
7731       // combine should be prevented.
7732       if (C1Cost < ShiftedC1Cost)
7733         return false;
7734     }
7735   }
7736   return true;
7737 }
7738 
7739 bool RISCVTargetLowering::targetShrinkDemandedConstant(
7740     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
7741     TargetLoweringOpt &TLO) const {
7742   // Delay this optimization as late as possible.
7743   if (!TLO.LegalOps)
7744     return false;
7745 
7746   EVT VT = Op.getValueType();
7747   if (VT.isVector())
7748     return false;
7749 
7750   // Only handle AND for now.
7751   if (Op.getOpcode() != ISD::AND)
7752     return false;
7753 
7754   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7755   if (!C)
7756     return false;
7757 
7758   const APInt &Mask = C->getAPIntValue();
7759 
7760   // Clear all non-demanded bits initially.
7761   APInt ShrunkMask = Mask & DemandedBits;
7762 
7763   // Try to make a smaller immediate by setting undemanded bits.
7764 
7765   APInt ExpandedMask = Mask | ~DemandedBits;
7766 
7767   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
7768     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
7769   };
7770   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
7771     if (NewMask == Mask)
7772       return true;
7773     SDLoc DL(Op);
7774     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
7775     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
7776     return TLO.CombineTo(Op, NewOp);
7777   };
7778 
7779   // If the shrunk mask fits in sign extended 12 bits, let the target
7780   // independent code apply it.
7781   if (ShrunkMask.isSignedIntN(12))
7782     return false;
7783 
7784   // Preserve (and X, 0xffff) when zext.h is supported.
7785   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
7786     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
7787     if (IsLegalMask(NewMask))
7788       return UseMask(NewMask);
7789   }
7790 
7791   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
7792   if (VT == MVT::i64) {
7793     APInt NewMask = APInt(64, 0xffffffff);
7794     if (IsLegalMask(NewMask))
7795       return UseMask(NewMask);
7796   }
7797 
7798   // For the remaining optimizations, we need to be able to make a negative
7799   // number through a combination of mask and undemanded bits.
7800   if (!ExpandedMask.isNegative())
7801     return false;
7802 
7803   // What is the fewest number of bits we need to represent the negative number.
7804   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
7805 
7806   // Try to make a 12 bit negative immediate. If that fails try to make a 32
7807   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
7808   APInt NewMask = ShrunkMask;
7809   if (MinSignedBits <= 12)
7810     NewMask.setBitsFrom(11);
7811   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
7812     NewMask.setBitsFrom(31);
7813   else
7814     return false;
7815 
7816   // Check that our new mask is a subset of the demanded mask.
7817   assert(IsLegalMask(NewMask));
7818   return UseMask(NewMask);
7819 }
7820 
7821 static void computeGREV(APInt &Src, unsigned ShAmt) {
7822   ShAmt &= Src.getBitWidth() - 1;
7823   uint64_t x = Src.getZExtValue();
7824   if (ShAmt & 1)
7825     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
7826   if (ShAmt & 2)
7827     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
7828   if (ShAmt & 4)
7829     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
7830   if (ShAmt & 8)
7831     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
7832   if (ShAmt & 16)
7833     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
7834   if (ShAmt & 32)
7835     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
7836   Src = x;
7837 }
7838 
7839 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
7840                                                         KnownBits &Known,
7841                                                         const APInt &DemandedElts,
7842                                                         const SelectionDAG &DAG,
7843                                                         unsigned Depth) const {
7844   unsigned BitWidth = Known.getBitWidth();
7845   unsigned Opc = Op.getOpcode();
7846   assert((Opc >= ISD::BUILTIN_OP_END ||
7847           Opc == ISD::INTRINSIC_WO_CHAIN ||
7848           Opc == ISD::INTRINSIC_W_CHAIN ||
7849           Opc == ISD::INTRINSIC_VOID) &&
7850          "Should use MaskedValueIsZero if you don't know whether Op"
7851          " is a target node!");
7852 
7853   Known.resetAll();
7854   switch (Opc) {
7855   default: break;
7856   case RISCVISD::SELECT_CC: {
7857     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
7858     // If we don't know any bits, early out.
7859     if (Known.isUnknown())
7860       break;
7861     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
7862 
7863     // Only known if known in both the LHS and RHS.
7864     Known = KnownBits::commonBits(Known, Known2);
7865     break;
7866   }
7867   case RISCVISD::REMUW: {
7868     KnownBits Known2;
7869     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7870     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7871     // We only care about the lower 32 bits.
7872     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
7873     // Restore the original width by sign extending.
7874     Known = Known.sext(BitWidth);
7875     break;
7876   }
7877   case RISCVISD::DIVUW: {
7878     KnownBits Known2;
7879     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
7880     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
7881     // We only care about the lower 32 bits.
7882     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
7883     // Restore the original width by sign extending.
7884     Known = Known.sext(BitWidth);
7885     break;
7886   }
7887   case RISCVISD::CTZW: {
7888     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7889     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
7890     unsigned LowBits = Log2_32(PossibleTZ) + 1;
7891     Known.Zero.setBitsFrom(LowBits);
7892     break;
7893   }
7894   case RISCVISD::CLZW: {
7895     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7896     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
7897     unsigned LowBits = Log2_32(PossibleLZ) + 1;
7898     Known.Zero.setBitsFrom(LowBits);
7899     break;
7900   }
7901   case RISCVISD::GREV:
7902   case RISCVISD::GREVW: {
7903     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7904       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
7905       if (Opc == RISCVISD::GREVW)
7906         Known = Known.trunc(32);
7907       unsigned ShAmt = C->getZExtValue();
7908       computeGREV(Known.Zero, ShAmt);
7909       computeGREV(Known.One, ShAmt);
7910       if (Opc == RISCVISD::GREVW)
7911         Known = Known.sext(BitWidth);
7912     }
7913     break;
7914   }
7915   case RISCVISD::READ_VLENB:
7916     // We assume VLENB is at least 16 bytes.
7917     Known.Zero.setLowBits(4);
7918     // We assume VLENB is no more than 65536 / 8 bytes.
7919     Known.Zero.setBitsFrom(14);
7920     break;
7921   case ISD::INTRINSIC_W_CHAIN: {
7922     unsigned IntNo = Op.getConstantOperandVal(1);
7923     switch (IntNo) {
7924     default:
7925       // We can't do anything for most intrinsics.
7926       break;
7927     case Intrinsic::riscv_vsetvli:
7928     case Intrinsic::riscv_vsetvlimax:
7929       // Assume that VL output is positive and would fit in an int32_t.
7930       // TODO: VLEN might be capped at 16 bits in a future V spec update.
7931       if (BitWidth >= 32)
7932         Known.Zero.setBitsFrom(31);
7933       break;
7934     }
7935     break;
7936   }
7937   }
7938 }
7939 
7940 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
7941     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
7942     unsigned Depth) const {
7943   switch (Op.getOpcode()) {
7944   default:
7945     break;
7946   case RISCVISD::SELECT_CC: {
7947     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
7948     if (Tmp == 1) return 1;  // Early out.
7949     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
7950     return std::min(Tmp, Tmp2);
7951   }
7952   case RISCVISD::SLLW:
7953   case RISCVISD::SRAW:
7954   case RISCVISD::SRLW:
7955   case RISCVISD::DIVW:
7956   case RISCVISD::DIVUW:
7957   case RISCVISD::REMUW:
7958   case RISCVISD::ROLW:
7959   case RISCVISD::RORW:
7960   case RISCVISD::GREVW:
7961   case RISCVISD::GORCW:
7962   case RISCVISD::FSLW:
7963   case RISCVISD::FSRW:
7964   case RISCVISD::SHFLW:
7965   case RISCVISD::UNSHFLW:
7966   case RISCVISD::BCOMPRESSW:
7967   case RISCVISD::BDECOMPRESSW:
7968   case RISCVISD::FCVT_W_RV64:
7969   case RISCVISD::FCVT_WU_RV64:
7970   case RISCVISD::STRICT_FCVT_W_RV64:
7971   case RISCVISD::STRICT_FCVT_WU_RV64:
7972     // TODO: As the result is sign-extended, this is conservatively correct. A
7973     // more precise answer could be calculated for SRAW depending on known
7974     // bits in the shift amount.
7975     return 33;
7976   case RISCVISD::SHFL:
7977   case RISCVISD::UNSHFL: {
7978     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
7979     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
7980     // will stay within the upper 32 bits. If there were more than 32 sign bits
7981     // before there will be at least 33 sign bits after.
7982     if (Op.getValueType() == MVT::i64 &&
7983         isa<ConstantSDNode>(Op.getOperand(1)) &&
7984         (Op.getConstantOperandVal(1) & 0x10) == 0) {
7985       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
7986       if (Tmp > 32)
7987         return 33;
7988     }
7989     break;
7990   }
7991   case RISCVISD::VMV_X_S:
7992     // The number of sign bits of the scalar result is computed by obtaining the
7993     // element type of the input vector operand, subtracting its width from the
7994     // XLEN, and then adding one (sign bit within the element type). If the
7995     // element type is wider than XLen, the least-significant XLEN bits are
7996     // taken.
7997     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
7998       return 1;
7999     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
8000   }
8001 
8002   return 1;
8003 }
8004 
8005 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8006                                                   MachineBasicBlock *BB) {
8007   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8008 
8009   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8010   // Should the count have wrapped while it was being read, we need to try
8011   // again.
8012   // ...
8013   // read:
8014   // rdcycleh x3 # load high word of cycle
8015   // rdcycle  x2 # load low word of cycle
8016   // rdcycleh x4 # load high word of cycle
8017   // bne x3, x4, read # check if high word reads match, otherwise try again
8018   // ...
8019 
8020   MachineFunction &MF = *BB->getParent();
8021   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8022   MachineFunction::iterator It = ++BB->getIterator();
8023 
8024   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8025   MF.insert(It, LoopMBB);
8026 
8027   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8028   MF.insert(It, DoneMBB);
8029 
8030   // Transfer the remainder of BB and its successor edges to DoneMBB.
8031   DoneMBB->splice(DoneMBB->begin(), BB,
8032                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8033   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8034 
8035   BB->addSuccessor(LoopMBB);
8036 
8037   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8038   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8039   Register LoReg = MI.getOperand(0).getReg();
8040   Register HiReg = MI.getOperand(1).getReg();
8041   DebugLoc DL = MI.getDebugLoc();
8042 
8043   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8044   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8045       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8046       .addReg(RISCV::X0);
8047   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8048       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8049       .addReg(RISCV::X0);
8050   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8051       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8052       .addReg(RISCV::X0);
8053 
8054   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8055       .addReg(HiReg)
8056       .addReg(ReadAgainReg)
8057       .addMBB(LoopMBB);
8058 
8059   LoopMBB->addSuccessor(LoopMBB);
8060   LoopMBB->addSuccessor(DoneMBB);
8061 
8062   MI.eraseFromParent();
8063 
8064   return DoneMBB;
8065 }
8066 
8067 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8068                                              MachineBasicBlock *BB) {
8069   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8070 
8071   MachineFunction &MF = *BB->getParent();
8072   DebugLoc DL = MI.getDebugLoc();
8073   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8074   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8075   Register LoReg = MI.getOperand(0).getReg();
8076   Register HiReg = MI.getOperand(1).getReg();
8077   Register SrcReg = MI.getOperand(2).getReg();
8078   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8079   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8080 
8081   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8082                           RI);
8083   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8084   MachineMemOperand *MMOLo =
8085       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8086   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8087       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8088   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8089       .addFrameIndex(FI)
8090       .addImm(0)
8091       .addMemOperand(MMOLo);
8092   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8093       .addFrameIndex(FI)
8094       .addImm(4)
8095       .addMemOperand(MMOHi);
8096   MI.eraseFromParent(); // The pseudo instruction is gone now.
8097   return BB;
8098 }
8099 
8100 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8101                                                  MachineBasicBlock *BB) {
8102   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8103          "Unexpected instruction");
8104 
8105   MachineFunction &MF = *BB->getParent();
8106   DebugLoc DL = MI.getDebugLoc();
8107   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8108   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8109   Register DstReg = MI.getOperand(0).getReg();
8110   Register LoReg = MI.getOperand(1).getReg();
8111   Register HiReg = MI.getOperand(2).getReg();
8112   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8113   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8114 
8115   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8116   MachineMemOperand *MMOLo =
8117       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8118   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8119       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8120   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8121       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8122       .addFrameIndex(FI)
8123       .addImm(0)
8124       .addMemOperand(MMOLo);
8125   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8126       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8127       .addFrameIndex(FI)
8128       .addImm(4)
8129       .addMemOperand(MMOHi);
8130   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8131   MI.eraseFromParent(); // The pseudo instruction is gone now.
8132   return BB;
8133 }
8134 
8135 static bool isSelectPseudo(MachineInstr &MI) {
8136   switch (MI.getOpcode()) {
8137   default:
8138     return false;
8139   case RISCV::Select_GPR_Using_CC_GPR:
8140   case RISCV::Select_FPR16_Using_CC_GPR:
8141   case RISCV::Select_FPR32_Using_CC_GPR:
8142   case RISCV::Select_FPR64_Using_CC_GPR:
8143     return true;
8144   }
8145 }
8146 
8147 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8148                                         unsigned RelOpcode, unsigned EqOpcode,
8149                                         const RISCVSubtarget &Subtarget) {
8150   DebugLoc DL = MI.getDebugLoc();
8151   Register DstReg = MI.getOperand(0).getReg();
8152   Register Src1Reg = MI.getOperand(1).getReg();
8153   Register Src2Reg = MI.getOperand(2).getReg();
8154   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8155   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8156   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8157 
8158   // Save the current FFLAGS.
8159   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8160 
8161   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8162                  .addReg(Src1Reg)
8163                  .addReg(Src2Reg);
8164   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8165     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8166 
8167   // Restore the FFLAGS.
8168   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8169       .addReg(SavedFFlags, RegState::Kill);
8170 
8171   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8172   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8173                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8174                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8175   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8176     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8177 
8178   // Erase the pseudoinstruction.
8179   MI.eraseFromParent();
8180   return BB;
8181 }
8182 
8183 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8184                                            MachineBasicBlock *BB,
8185                                            const RISCVSubtarget &Subtarget) {
8186   // To "insert" Select_* instructions, we actually have to insert the triangle
8187   // control-flow pattern.  The incoming instructions know the destination vreg
8188   // to set, the condition code register to branch on, the true/false values to
8189   // select between, and the condcode to use to select the appropriate branch.
8190   //
8191   // We produce the following control flow:
8192   //     HeadMBB
8193   //     |  \
8194   //     |  IfFalseMBB
8195   //     | /
8196   //    TailMBB
8197   //
8198   // When we find a sequence of selects we attempt to optimize their emission
8199   // by sharing the control flow. Currently we only handle cases where we have
8200   // multiple selects with the exact same condition (same LHS, RHS and CC).
8201   // The selects may be interleaved with other instructions if the other
8202   // instructions meet some requirements we deem safe:
8203   // - They are debug instructions. Otherwise,
8204   // - They do not have side-effects, do not access memory and their inputs do
8205   //   not depend on the results of the select pseudo-instructions.
8206   // The TrueV/FalseV operands of the selects cannot depend on the result of
8207   // previous selects in the sequence.
8208   // These conditions could be further relaxed. See the X86 target for a
8209   // related approach and more information.
8210   Register LHS = MI.getOperand(1).getReg();
8211   Register RHS = MI.getOperand(2).getReg();
8212   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8213 
8214   SmallVector<MachineInstr *, 4> SelectDebugValues;
8215   SmallSet<Register, 4> SelectDests;
8216   SelectDests.insert(MI.getOperand(0).getReg());
8217 
8218   MachineInstr *LastSelectPseudo = &MI;
8219 
8220   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8221        SequenceMBBI != E; ++SequenceMBBI) {
8222     if (SequenceMBBI->isDebugInstr())
8223       continue;
8224     else if (isSelectPseudo(*SequenceMBBI)) {
8225       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8226           SequenceMBBI->getOperand(2).getReg() != RHS ||
8227           SequenceMBBI->getOperand(3).getImm() != CC ||
8228           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8229           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8230         break;
8231       LastSelectPseudo = &*SequenceMBBI;
8232       SequenceMBBI->collectDebugValues(SelectDebugValues);
8233       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8234     } else {
8235       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8236           SequenceMBBI->mayLoadOrStore())
8237         break;
8238       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8239             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8240           }))
8241         break;
8242     }
8243   }
8244 
8245   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8246   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8247   DebugLoc DL = MI.getDebugLoc();
8248   MachineFunction::iterator I = ++BB->getIterator();
8249 
8250   MachineBasicBlock *HeadMBB = BB;
8251   MachineFunction *F = BB->getParent();
8252   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8253   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8254 
8255   F->insert(I, IfFalseMBB);
8256   F->insert(I, TailMBB);
8257 
8258   // Transfer debug instructions associated with the selects to TailMBB.
8259   for (MachineInstr *DebugInstr : SelectDebugValues) {
8260     TailMBB->push_back(DebugInstr->removeFromParent());
8261   }
8262 
8263   // Move all instructions after the sequence to TailMBB.
8264   TailMBB->splice(TailMBB->end(), HeadMBB,
8265                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8266   // Update machine-CFG edges by transferring all successors of the current
8267   // block to the new block which will contain the Phi nodes for the selects.
8268   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8269   // Set the successors for HeadMBB.
8270   HeadMBB->addSuccessor(IfFalseMBB);
8271   HeadMBB->addSuccessor(TailMBB);
8272 
8273   // Insert appropriate branch.
8274   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8275     .addReg(LHS)
8276     .addReg(RHS)
8277     .addMBB(TailMBB);
8278 
8279   // IfFalseMBB just falls through to TailMBB.
8280   IfFalseMBB->addSuccessor(TailMBB);
8281 
8282   // Create PHIs for all of the select pseudo-instructions.
8283   auto SelectMBBI = MI.getIterator();
8284   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8285   auto InsertionPoint = TailMBB->begin();
8286   while (SelectMBBI != SelectEnd) {
8287     auto Next = std::next(SelectMBBI);
8288     if (isSelectPseudo(*SelectMBBI)) {
8289       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8290       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8291               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8292           .addReg(SelectMBBI->getOperand(4).getReg())
8293           .addMBB(HeadMBB)
8294           .addReg(SelectMBBI->getOperand(5).getReg())
8295           .addMBB(IfFalseMBB);
8296       SelectMBBI->eraseFromParent();
8297     }
8298     SelectMBBI = Next;
8299   }
8300 
8301   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8302   return TailMBB;
8303 }
8304 
8305 MachineBasicBlock *
8306 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8307                                                  MachineBasicBlock *BB) const {
8308   switch (MI.getOpcode()) {
8309   default:
8310     llvm_unreachable("Unexpected instr type to insert");
8311   case RISCV::ReadCycleWide:
8312     assert(!Subtarget.is64Bit() &&
8313            "ReadCycleWrite is only to be used on riscv32");
8314     return emitReadCycleWidePseudo(MI, BB);
8315   case RISCV::Select_GPR_Using_CC_GPR:
8316   case RISCV::Select_FPR16_Using_CC_GPR:
8317   case RISCV::Select_FPR32_Using_CC_GPR:
8318   case RISCV::Select_FPR64_Using_CC_GPR:
8319     return emitSelectPseudo(MI, BB, Subtarget);
8320   case RISCV::BuildPairF64Pseudo:
8321     return emitBuildPairF64Pseudo(MI, BB);
8322   case RISCV::SplitF64Pseudo:
8323     return emitSplitF64Pseudo(MI, BB);
8324   case RISCV::PseudoQuietFLE_H:
8325     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8326   case RISCV::PseudoQuietFLT_H:
8327     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8328   case RISCV::PseudoQuietFLE_S:
8329     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8330   case RISCV::PseudoQuietFLT_S:
8331     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8332   case RISCV::PseudoQuietFLE_D:
8333     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8334   case RISCV::PseudoQuietFLT_D:
8335     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8336   }
8337 }
8338 
8339 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8340                                                         SDNode *Node) const {
8341   // Add FRM dependency to any instructions with dynamic rounding mode.
8342   unsigned Opc = MI.getOpcode();
8343   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8344   if (Idx < 0)
8345     return;
8346   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8347     return;
8348   // If the instruction already reads FRM, don't add another read.
8349   if (MI.readsRegister(RISCV::FRM))
8350     return;
8351   MI.addOperand(
8352       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8353 }
8354 
8355 // Calling Convention Implementation.
8356 // The expectations for frontend ABI lowering vary from target to target.
8357 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8358 // details, but this is a longer term goal. For now, we simply try to keep the
8359 // role of the frontend as simple and well-defined as possible. The rules can
8360 // be summarised as:
8361 // * Never split up large scalar arguments. We handle them here.
8362 // * If a hardfloat calling convention is being used, and the struct may be
8363 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8364 // available, then pass as two separate arguments. If either the GPRs or FPRs
8365 // are exhausted, then pass according to the rule below.
8366 // * If a struct could never be passed in registers or directly in a stack
8367 // slot (as it is larger than 2*XLEN and the floating point rules don't
8368 // apply), then pass it using a pointer with the byval attribute.
8369 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8370 // word-sized array or a 2*XLEN scalar (depending on alignment).
8371 // * The frontend can determine whether a struct is returned by reference or
8372 // not based on its size and fields. If it will be returned by reference, the
8373 // frontend must modify the prototype so a pointer with the sret annotation is
8374 // passed as the first argument. This is not necessary for large scalar
8375 // returns.
8376 // * Struct return values and varargs should be coerced to structs containing
8377 // register-size fields in the same situations they would be for fixed
8378 // arguments.
8379 
8380 static const MCPhysReg ArgGPRs[] = {
8381   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8382   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8383 };
8384 static const MCPhysReg ArgFPR16s[] = {
8385   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8386   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8387 };
8388 static const MCPhysReg ArgFPR32s[] = {
8389   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8390   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8391 };
8392 static const MCPhysReg ArgFPR64s[] = {
8393   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8394   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8395 };
8396 // This is an interim calling convention and it may be changed in the future.
8397 static const MCPhysReg ArgVRs[] = {
8398     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8399     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8400     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8401 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8402                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8403                                      RISCV::V20M2, RISCV::V22M2};
8404 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8405                                      RISCV::V20M4};
8406 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8407 
8408 // Pass a 2*XLEN argument that has been split into two XLEN values through
8409 // registers or the stack as necessary.
8410 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8411                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8412                                 MVT ValVT2, MVT LocVT2,
8413                                 ISD::ArgFlagsTy ArgFlags2) {
8414   unsigned XLenInBytes = XLen / 8;
8415   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8416     // At least one half can be passed via register.
8417     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8418                                      VA1.getLocVT(), CCValAssign::Full));
8419   } else {
8420     // Both halves must be passed on the stack, with proper alignment.
8421     Align StackAlign =
8422         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8423     State.addLoc(
8424         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8425                             State.AllocateStack(XLenInBytes, StackAlign),
8426                             VA1.getLocVT(), CCValAssign::Full));
8427     State.addLoc(CCValAssign::getMem(
8428         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8429         LocVT2, CCValAssign::Full));
8430     return false;
8431   }
8432 
8433   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8434     // The second half can also be passed via register.
8435     State.addLoc(
8436         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8437   } else {
8438     // The second half is passed via the stack, without additional alignment.
8439     State.addLoc(CCValAssign::getMem(
8440         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8441         LocVT2, CCValAssign::Full));
8442   }
8443 
8444   return false;
8445 }
8446 
8447 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8448                                Optional<unsigned> FirstMaskArgument,
8449                                CCState &State, const RISCVTargetLowering &TLI) {
8450   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8451   if (RC == &RISCV::VRRegClass) {
8452     // Assign the first mask argument to V0.
8453     // This is an interim calling convention and it may be changed in the
8454     // future.
8455     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8456       return State.AllocateReg(RISCV::V0);
8457     return State.AllocateReg(ArgVRs);
8458   }
8459   if (RC == &RISCV::VRM2RegClass)
8460     return State.AllocateReg(ArgVRM2s);
8461   if (RC == &RISCV::VRM4RegClass)
8462     return State.AllocateReg(ArgVRM4s);
8463   if (RC == &RISCV::VRM8RegClass)
8464     return State.AllocateReg(ArgVRM8s);
8465   llvm_unreachable("Unhandled register class for ValueType");
8466 }
8467 
8468 // Implements the RISC-V calling convention. Returns true upon failure.
8469 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8470                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8471                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8472                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8473                      Optional<unsigned> FirstMaskArgument) {
8474   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8475   assert(XLen == 32 || XLen == 64);
8476   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8477 
8478   // Any return value split in to more than two values can't be returned
8479   // directly. Vectors are returned via the available vector registers.
8480   if (!LocVT.isVector() && IsRet && ValNo > 1)
8481     return true;
8482 
8483   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8484   // variadic argument, or if no F16/F32 argument registers are available.
8485   bool UseGPRForF16_F32 = true;
8486   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8487   // variadic argument, or if no F64 argument registers are available.
8488   bool UseGPRForF64 = true;
8489 
8490   switch (ABI) {
8491   default:
8492     llvm_unreachable("Unexpected ABI");
8493   case RISCVABI::ABI_ILP32:
8494   case RISCVABI::ABI_LP64:
8495     break;
8496   case RISCVABI::ABI_ILP32F:
8497   case RISCVABI::ABI_LP64F:
8498     UseGPRForF16_F32 = !IsFixed;
8499     break;
8500   case RISCVABI::ABI_ILP32D:
8501   case RISCVABI::ABI_LP64D:
8502     UseGPRForF16_F32 = !IsFixed;
8503     UseGPRForF64 = !IsFixed;
8504     break;
8505   }
8506 
8507   // FPR16, FPR32, and FPR64 alias each other.
8508   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8509     UseGPRForF16_F32 = true;
8510     UseGPRForF64 = true;
8511   }
8512 
8513   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8514   // similar local variables rather than directly checking against the target
8515   // ABI.
8516 
8517   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8518     LocVT = XLenVT;
8519     LocInfo = CCValAssign::BCvt;
8520   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8521     LocVT = MVT::i64;
8522     LocInfo = CCValAssign::BCvt;
8523   }
8524 
8525   // If this is a variadic argument, the RISC-V calling convention requires
8526   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8527   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8528   // be used regardless of whether the original argument was split during
8529   // legalisation or not. The argument will not be passed by registers if the
8530   // original type is larger than 2*XLEN, so the register alignment rule does
8531   // not apply.
8532   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8533   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8534       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8535     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8536     // Skip 'odd' register if necessary.
8537     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8538       State.AllocateReg(ArgGPRs);
8539   }
8540 
8541   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8542   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8543       State.getPendingArgFlags();
8544 
8545   assert(PendingLocs.size() == PendingArgFlags.size() &&
8546          "PendingLocs and PendingArgFlags out of sync");
8547 
8548   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8549   // registers are exhausted.
8550   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8551     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8552            "Can't lower f64 if it is split");
8553     // Depending on available argument GPRS, f64 may be passed in a pair of
8554     // GPRs, split between a GPR and the stack, or passed completely on the
8555     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8556     // cases.
8557     Register Reg = State.AllocateReg(ArgGPRs);
8558     LocVT = MVT::i32;
8559     if (!Reg) {
8560       unsigned StackOffset = State.AllocateStack(8, Align(8));
8561       State.addLoc(
8562           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8563       return false;
8564     }
8565     if (!State.AllocateReg(ArgGPRs))
8566       State.AllocateStack(4, Align(4));
8567     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8568     return false;
8569   }
8570 
8571   // Fixed-length vectors are located in the corresponding scalable-vector
8572   // container types.
8573   if (ValVT.isFixedLengthVector())
8574     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8575 
8576   // Split arguments might be passed indirectly, so keep track of the pending
8577   // values. Split vectors are passed via a mix of registers and indirectly, so
8578   // treat them as we would any other argument.
8579   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8580     LocVT = XLenVT;
8581     LocInfo = CCValAssign::Indirect;
8582     PendingLocs.push_back(
8583         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8584     PendingArgFlags.push_back(ArgFlags);
8585     if (!ArgFlags.isSplitEnd()) {
8586       return false;
8587     }
8588   }
8589 
8590   // If the split argument only had two elements, it should be passed directly
8591   // in registers or on the stack.
8592   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8593       PendingLocs.size() <= 2) {
8594     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8595     // Apply the normal calling convention rules to the first half of the
8596     // split argument.
8597     CCValAssign VA = PendingLocs[0];
8598     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8599     PendingLocs.clear();
8600     PendingArgFlags.clear();
8601     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8602                                ArgFlags);
8603   }
8604 
8605   // Allocate to a register if possible, or else a stack slot.
8606   Register Reg;
8607   unsigned StoreSizeBytes = XLen / 8;
8608   Align StackAlign = Align(XLen / 8);
8609 
8610   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8611     Reg = State.AllocateReg(ArgFPR16s);
8612   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8613     Reg = State.AllocateReg(ArgFPR32s);
8614   else if (ValVT == MVT::f64 && !UseGPRForF64)
8615     Reg = State.AllocateReg(ArgFPR64s);
8616   else if (ValVT.isVector()) {
8617     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8618     if (!Reg) {
8619       // For return values, the vector must be passed fully via registers or
8620       // via the stack.
8621       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
8622       // but we're using all of them.
8623       if (IsRet)
8624         return true;
8625       // Try using a GPR to pass the address
8626       if ((Reg = State.AllocateReg(ArgGPRs))) {
8627         LocVT = XLenVT;
8628         LocInfo = CCValAssign::Indirect;
8629       } else if (ValVT.isScalableVector()) {
8630         LocVT = XLenVT;
8631         LocInfo = CCValAssign::Indirect;
8632       } else {
8633         // Pass fixed-length vectors on the stack.
8634         LocVT = ValVT;
8635         StoreSizeBytes = ValVT.getStoreSize();
8636         // Align vectors to their element sizes, being careful for vXi1
8637         // vectors.
8638         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8639       }
8640     }
8641   } else {
8642     Reg = State.AllocateReg(ArgGPRs);
8643   }
8644 
8645   unsigned StackOffset =
8646       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
8647 
8648   // If we reach this point and PendingLocs is non-empty, we must be at the
8649   // end of a split argument that must be passed indirectly.
8650   if (!PendingLocs.empty()) {
8651     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
8652     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
8653 
8654     for (auto &It : PendingLocs) {
8655       if (Reg)
8656         It.convertToReg(Reg);
8657       else
8658         It.convertToMem(StackOffset);
8659       State.addLoc(It);
8660     }
8661     PendingLocs.clear();
8662     PendingArgFlags.clear();
8663     return false;
8664   }
8665 
8666   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
8667           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
8668          "Expected an XLenVT or vector types at this stage");
8669 
8670   if (Reg) {
8671     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8672     return false;
8673   }
8674 
8675   // When a floating-point value is passed on the stack, no bit-conversion is
8676   // needed.
8677   if (ValVT.isFloatingPoint()) {
8678     LocVT = ValVT;
8679     LocInfo = CCValAssign::Full;
8680   }
8681   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8682   return false;
8683 }
8684 
8685 template <typename ArgTy>
8686 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
8687   for (const auto &ArgIdx : enumerate(Args)) {
8688     MVT ArgVT = ArgIdx.value().VT;
8689     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
8690       return ArgIdx.index();
8691   }
8692   return None;
8693 }
8694 
8695 void RISCVTargetLowering::analyzeInputArgs(
8696     MachineFunction &MF, CCState &CCInfo,
8697     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
8698     RISCVCCAssignFn Fn) const {
8699   unsigned NumArgs = Ins.size();
8700   FunctionType *FType = MF.getFunction().getFunctionType();
8701 
8702   Optional<unsigned> FirstMaskArgument;
8703   if (Subtarget.hasVInstructions())
8704     FirstMaskArgument = preAssignMask(Ins);
8705 
8706   for (unsigned i = 0; i != NumArgs; ++i) {
8707     MVT ArgVT = Ins[i].VT;
8708     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
8709 
8710     Type *ArgTy = nullptr;
8711     if (IsRet)
8712       ArgTy = FType->getReturnType();
8713     else if (Ins[i].isOrigArg())
8714       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
8715 
8716     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8717     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8718            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
8719            FirstMaskArgument)) {
8720       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
8721                         << EVT(ArgVT).getEVTString() << '\n');
8722       llvm_unreachable(nullptr);
8723     }
8724   }
8725 }
8726 
8727 void RISCVTargetLowering::analyzeOutputArgs(
8728     MachineFunction &MF, CCState &CCInfo,
8729     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
8730     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
8731   unsigned NumArgs = Outs.size();
8732 
8733   Optional<unsigned> FirstMaskArgument;
8734   if (Subtarget.hasVInstructions())
8735     FirstMaskArgument = preAssignMask(Outs);
8736 
8737   for (unsigned i = 0; i != NumArgs; i++) {
8738     MVT ArgVT = Outs[i].VT;
8739     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8740     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
8741 
8742     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8743     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
8744            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
8745            FirstMaskArgument)) {
8746       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
8747                         << EVT(ArgVT).getEVTString() << "\n");
8748       llvm_unreachable(nullptr);
8749     }
8750   }
8751 }
8752 
8753 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
8754 // values.
8755 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
8756                                    const CCValAssign &VA, const SDLoc &DL,
8757                                    const RISCVSubtarget &Subtarget) {
8758   switch (VA.getLocInfo()) {
8759   default:
8760     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8761   case CCValAssign::Full:
8762     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
8763       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
8764     break;
8765   case CCValAssign::BCvt:
8766     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8767       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
8768     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8769       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
8770     else
8771       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
8772     break;
8773   }
8774   return Val;
8775 }
8776 
8777 // The caller is responsible for loading the full value if the argument is
8778 // passed with CCValAssign::Indirect.
8779 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
8780                                 const CCValAssign &VA, const SDLoc &DL,
8781                                 const RISCVTargetLowering &TLI) {
8782   MachineFunction &MF = DAG.getMachineFunction();
8783   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8784   EVT LocVT = VA.getLocVT();
8785   SDValue Val;
8786   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
8787   Register VReg = RegInfo.createVirtualRegister(RC);
8788   RegInfo.addLiveIn(VA.getLocReg(), VReg);
8789   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
8790 
8791   if (VA.getLocInfo() == CCValAssign::Indirect)
8792     return Val;
8793 
8794   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
8795 }
8796 
8797 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
8798                                    const CCValAssign &VA, const SDLoc &DL,
8799                                    const RISCVSubtarget &Subtarget) {
8800   EVT LocVT = VA.getLocVT();
8801 
8802   switch (VA.getLocInfo()) {
8803   default:
8804     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8805   case CCValAssign::Full:
8806     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
8807       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
8808     break;
8809   case CCValAssign::BCvt:
8810     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
8811       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
8812     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
8813       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
8814     else
8815       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
8816     break;
8817   }
8818   return Val;
8819 }
8820 
8821 // The caller is responsible for loading the full value if the argument is
8822 // passed with CCValAssign::Indirect.
8823 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
8824                                 const CCValAssign &VA, const SDLoc &DL) {
8825   MachineFunction &MF = DAG.getMachineFunction();
8826   MachineFrameInfo &MFI = MF.getFrameInfo();
8827   EVT LocVT = VA.getLocVT();
8828   EVT ValVT = VA.getValVT();
8829   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
8830   if (ValVT.isScalableVector()) {
8831     // When the value is a scalable vector, we save the pointer which points to
8832     // the scalable vector value in the stack. The ValVT will be the pointer
8833     // type, instead of the scalable vector type.
8834     ValVT = LocVT;
8835   }
8836   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
8837                                  /*IsImmutable=*/true);
8838   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
8839   SDValue Val;
8840 
8841   ISD::LoadExtType ExtType;
8842   switch (VA.getLocInfo()) {
8843   default:
8844     llvm_unreachable("Unexpected CCValAssign::LocInfo");
8845   case CCValAssign::Full:
8846   case CCValAssign::Indirect:
8847   case CCValAssign::BCvt:
8848     ExtType = ISD::NON_EXTLOAD;
8849     break;
8850   }
8851   Val = DAG.getExtLoad(
8852       ExtType, DL, LocVT, Chain, FIN,
8853       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
8854   return Val;
8855 }
8856 
8857 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
8858                                        const CCValAssign &VA, const SDLoc &DL) {
8859   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
8860          "Unexpected VA");
8861   MachineFunction &MF = DAG.getMachineFunction();
8862   MachineFrameInfo &MFI = MF.getFrameInfo();
8863   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8864 
8865   if (VA.isMemLoc()) {
8866     // f64 is passed on the stack.
8867     int FI =
8868         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
8869     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8870     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
8871                        MachinePointerInfo::getFixedStack(MF, FI));
8872   }
8873 
8874   assert(VA.isRegLoc() && "Expected register VA assignment");
8875 
8876   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8877   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
8878   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
8879   SDValue Hi;
8880   if (VA.getLocReg() == RISCV::X17) {
8881     // Second half of f64 is passed on the stack.
8882     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
8883     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
8884     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
8885                      MachinePointerInfo::getFixedStack(MF, FI));
8886   } else {
8887     // Second half of f64 is passed in another GPR.
8888     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8889     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
8890     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
8891   }
8892   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
8893 }
8894 
8895 // FastCC has less than 1% performance improvement for some particular
8896 // benchmark. But theoretically, it may has benenfit for some cases.
8897 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
8898                             unsigned ValNo, MVT ValVT, MVT LocVT,
8899                             CCValAssign::LocInfo LocInfo,
8900                             ISD::ArgFlagsTy ArgFlags, CCState &State,
8901                             bool IsFixed, bool IsRet, Type *OrigTy,
8902                             const RISCVTargetLowering &TLI,
8903                             Optional<unsigned> FirstMaskArgument) {
8904 
8905   // X5 and X6 might be used for save-restore libcall.
8906   static const MCPhysReg GPRList[] = {
8907       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
8908       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
8909       RISCV::X29, RISCV::X30, RISCV::X31};
8910 
8911   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
8912     if (unsigned Reg = State.AllocateReg(GPRList)) {
8913       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8914       return false;
8915     }
8916   }
8917 
8918   if (LocVT == MVT::f16) {
8919     static const MCPhysReg FPR16List[] = {
8920         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
8921         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
8922         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
8923         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
8924     if (unsigned Reg = State.AllocateReg(FPR16List)) {
8925       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8926       return false;
8927     }
8928   }
8929 
8930   if (LocVT == MVT::f32) {
8931     static const MCPhysReg FPR32List[] = {
8932         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
8933         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
8934         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
8935         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
8936     if (unsigned Reg = State.AllocateReg(FPR32List)) {
8937       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8938       return false;
8939     }
8940   }
8941 
8942   if (LocVT == MVT::f64) {
8943     static const MCPhysReg FPR64List[] = {
8944         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
8945         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
8946         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
8947         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
8948     if (unsigned Reg = State.AllocateReg(FPR64List)) {
8949       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8950       return false;
8951     }
8952   }
8953 
8954   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
8955     unsigned Offset4 = State.AllocateStack(4, Align(4));
8956     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
8957     return false;
8958   }
8959 
8960   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
8961     unsigned Offset5 = State.AllocateStack(8, Align(8));
8962     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
8963     return false;
8964   }
8965 
8966   if (LocVT.isVector()) {
8967     if (unsigned Reg =
8968             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
8969       // Fixed-length vectors are located in the corresponding scalable-vector
8970       // container types.
8971       if (ValVT.isFixedLengthVector())
8972         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8973       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8974     } else {
8975       // Try and pass the address via a "fast" GPR.
8976       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
8977         LocInfo = CCValAssign::Indirect;
8978         LocVT = TLI.getSubtarget().getXLenVT();
8979         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
8980       } else if (ValVT.isFixedLengthVector()) {
8981         auto StackAlign =
8982             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
8983         unsigned StackOffset =
8984             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
8985         State.addLoc(
8986             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8987       } else {
8988         // Can't pass scalable vectors on the stack.
8989         return true;
8990       }
8991     }
8992 
8993     return false;
8994   }
8995 
8996   return true; // CC didn't match.
8997 }
8998 
8999 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9000                          CCValAssign::LocInfo LocInfo,
9001                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9002 
9003   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9004     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9005     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9006     static const MCPhysReg GPRList[] = {
9007         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9008         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9009     if (unsigned Reg = State.AllocateReg(GPRList)) {
9010       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9011       return false;
9012     }
9013   }
9014 
9015   if (LocVT == MVT::f32) {
9016     // Pass in STG registers: F1, ..., F6
9017     //                        fs0 ... fs5
9018     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9019                                           RISCV::F18_F, RISCV::F19_F,
9020                                           RISCV::F20_F, RISCV::F21_F};
9021     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9022       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9023       return false;
9024     }
9025   }
9026 
9027   if (LocVT == MVT::f64) {
9028     // Pass in STG registers: D1, ..., D6
9029     //                        fs6 ... fs11
9030     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9031                                           RISCV::F24_D, RISCV::F25_D,
9032                                           RISCV::F26_D, RISCV::F27_D};
9033     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9034       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9035       return false;
9036     }
9037   }
9038 
9039   report_fatal_error("No registers left in GHC calling convention");
9040   return true;
9041 }
9042 
9043 // Transform physical registers into virtual registers.
9044 SDValue RISCVTargetLowering::LowerFormalArguments(
9045     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9046     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9047     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9048 
9049   MachineFunction &MF = DAG.getMachineFunction();
9050 
9051   switch (CallConv) {
9052   default:
9053     report_fatal_error("Unsupported calling convention");
9054   case CallingConv::C:
9055   case CallingConv::Fast:
9056     break;
9057   case CallingConv::GHC:
9058     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9059         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9060       report_fatal_error(
9061         "GHC calling convention requires the F and D instruction set extensions");
9062   }
9063 
9064   const Function &Func = MF.getFunction();
9065   if (Func.hasFnAttribute("interrupt")) {
9066     if (!Func.arg_empty())
9067       report_fatal_error(
9068         "Functions with the interrupt attribute cannot have arguments!");
9069 
9070     StringRef Kind =
9071       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9072 
9073     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9074       report_fatal_error(
9075         "Function interrupt attribute argument not supported!");
9076   }
9077 
9078   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9079   MVT XLenVT = Subtarget.getXLenVT();
9080   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9081   // Used with vargs to acumulate store chains.
9082   std::vector<SDValue> OutChains;
9083 
9084   // Assign locations to all of the incoming arguments.
9085   SmallVector<CCValAssign, 16> ArgLocs;
9086   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9087 
9088   if (CallConv == CallingConv::GHC)
9089     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9090   else
9091     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9092                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9093                                                    : CC_RISCV);
9094 
9095   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9096     CCValAssign &VA = ArgLocs[i];
9097     SDValue ArgValue;
9098     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9099     // case.
9100     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9101       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9102     else if (VA.isRegLoc())
9103       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9104     else
9105       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9106 
9107     if (VA.getLocInfo() == CCValAssign::Indirect) {
9108       // If the original argument was split and passed by reference (e.g. i128
9109       // on RV32), we need to load all parts of it here (using the same
9110       // address). Vectors may be partly split to registers and partly to the
9111       // stack, in which case the base address is partly offset and subsequent
9112       // stores are relative to that.
9113       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9114                                    MachinePointerInfo()));
9115       unsigned ArgIndex = Ins[i].OrigArgIndex;
9116       unsigned ArgPartOffset = Ins[i].PartOffset;
9117       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9118       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9119         CCValAssign &PartVA = ArgLocs[i + 1];
9120         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9121         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9122         if (PartVA.getValVT().isScalableVector())
9123           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9124         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9125         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9126                                      MachinePointerInfo()));
9127         ++i;
9128       }
9129       continue;
9130     }
9131     InVals.push_back(ArgValue);
9132   }
9133 
9134   if (IsVarArg) {
9135     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9136     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9137     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9138     MachineFrameInfo &MFI = MF.getFrameInfo();
9139     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9140     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9141 
9142     // Offset of the first variable argument from stack pointer, and size of
9143     // the vararg save area. For now, the varargs save area is either zero or
9144     // large enough to hold a0-a7.
9145     int VaArgOffset, VarArgsSaveSize;
9146 
9147     // If all registers are allocated, then all varargs must be passed on the
9148     // stack and we don't need to save any argregs.
9149     if (ArgRegs.size() == Idx) {
9150       VaArgOffset = CCInfo.getNextStackOffset();
9151       VarArgsSaveSize = 0;
9152     } else {
9153       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9154       VaArgOffset = -VarArgsSaveSize;
9155     }
9156 
9157     // Record the frame index of the first variable argument
9158     // which is a value necessary to VASTART.
9159     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9160     RVFI->setVarArgsFrameIndex(FI);
9161 
9162     // If saving an odd number of registers then create an extra stack slot to
9163     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9164     // offsets to even-numbered registered remain 2*XLEN-aligned.
9165     if (Idx % 2) {
9166       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9167       VarArgsSaveSize += XLenInBytes;
9168     }
9169 
9170     // Copy the integer registers that may have been used for passing varargs
9171     // to the vararg save area.
9172     for (unsigned I = Idx; I < ArgRegs.size();
9173          ++I, VaArgOffset += XLenInBytes) {
9174       const Register Reg = RegInfo.createVirtualRegister(RC);
9175       RegInfo.addLiveIn(ArgRegs[I], Reg);
9176       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9177       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9178       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9179       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9180                                    MachinePointerInfo::getFixedStack(MF, FI));
9181       cast<StoreSDNode>(Store.getNode())
9182           ->getMemOperand()
9183           ->setValue((Value *)nullptr);
9184       OutChains.push_back(Store);
9185     }
9186     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9187   }
9188 
9189   // All stores are grouped in one node to allow the matching between
9190   // the size of Ins and InVals. This only happens for vararg functions.
9191   if (!OutChains.empty()) {
9192     OutChains.push_back(Chain);
9193     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9194   }
9195 
9196   return Chain;
9197 }
9198 
9199 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9200 /// for tail call optimization.
9201 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9202 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9203     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9204     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9205 
9206   auto &Callee = CLI.Callee;
9207   auto CalleeCC = CLI.CallConv;
9208   auto &Outs = CLI.Outs;
9209   auto &Caller = MF.getFunction();
9210   auto CallerCC = Caller.getCallingConv();
9211 
9212   // Exception-handling functions need a special set of instructions to
9213   // indicate a return to the hardware. Tail-calling another function would
9214   // probably break this.
9215   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9216   // should be expanded as new function attributes are introduced.
9217   if (Caller.hasFnAttribute("interrupt"))
9218     return false;
9219 
9220   // Do not tail call opt if the stack is used to pass parameters.
9221   if (CCInfo.getNextStackOffset() != 0)
9222     return false;
9223 
9224   // Do not tail call opt if any parameters need to be passed indirectly.
9225   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9226   // passed indirectly. So the address of the value will be passed in a
9227   // register, or if not available, then the address is put on the stack. In
9228   // order to pass indirectly, space on the stack often needs to be allocated
9229   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9230   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9231   // are passed CCValAssign::Indirect.
9232   for (auto &VA : ArgLocs)
9233     if (VA.getLocInfo() == CCValAssign::Indirect)
9234       return false;
9235 
9236   // Do not tail call opt if either caller or callee uses struct return
9237   // semantics.
9238   auto IsCallerStructRet = Caller.hasStructRetAttr();
9239   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9240   if (IsCallerStructRet || IsCalleeStructRet)
9241     return false;
9242 
9243   // Externally-defined functions with weak linkage should not be
9244   // tail-called. The behaviour of branch instructions in this situation (as
9245   // used for tail calls) is implementation-defined, so we cannot rely on the
9246   // linker replacing the tail call with a return.
9247   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9248     const GlobalValue *GV = G->getGlobal();
9249     if (GV->hasExternalWeakLinkage())
9250       return false;
9251   }
9252 
9253   // The callee has to preserve all registers the caller needs to preserve.
9254   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9255   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9256   if (CalleeCC != CallerCC) {
9257     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9258     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9259       return false;
9260   }
9261 
9262   // Byval parameters hand the function a pointer directly into the stack area
9263   // we want to reuse during a tail call. Working around this *is* possible
9264   // but less efficient and uglier in LowerCall.
9265   for (auto &Arg : Outs)
9266     if (Arg.Flags.isByVal())
9267       return false;
9268 
9269   return true;
9270 }
9271 
9272 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9273   return DAG.getDataLayout().getPrefTypeAlign(
9274       VT.getTypeForEVT(*DAG.getContext()));
9275 }
9276 
9277 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9278 // and output parameter nodes.
9279 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9280                                        SmallVectorImpl<SDValue> &InVals) const {
9281   SelectionDAG &DAG = CLI.DAG;
9282   SDLoc &DL = CLI.DL;
9283   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9284   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9285   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9286   SDValue Chain = CLI.Chain;
9287   SDValue Callee = CLI.Callee;
9288   bool &IsTailCall = CLI.IsTailCall;
9289   CallingConv::ID CallConv = CLI.CallConv;
9290   bool IsVarArg = CLI.IsVarArg;
9291   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9292   MVT XLenVT = Subtarget.getXLenVT();
9293 
9294   MachineFunction &MF = DAG.getMachineFunction();
9295 
9296   // Analyze the operands of the call, assigning locations to each operand.
9297   SmallVector<CCValAssign, 16> ArgLocs;
9298   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9299 
9300   if (CallConv == CallingConv::GHC)
9301     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9302   else
9303     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9304                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9305                                                     : CC_RISCV);
9306 
9307   // Check if it's really possible to do a tail call.
9308   if (IsTailCall)
9309     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9310 
9311   if (IsTailCall)
9312     ++NumTailCalls;
9313   else if (CLI.CB && CLI.CB->isMustTailCall())
9314     report_fatal_error("failed to perform tail call elimination on a call "
9315                        "site marked musttail");
9316 
9317   // Get a count of how many bytes are to be pushed on the stack.
9318   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9319 
9320   // Create local copies for byval args
9321   SmallVector<SDValue, 8> ByValArgs;
9322   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9323     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9324     if (!Flags.isByVal())
9325       continue;
9326 
9327     SDValue Arg = OutVals[i];
9328     unsigned Size = Flags.getByValSize();
9329     Align Alignment = Flags.getNonZeroByValAlign();
9330 
9331     int FI =
9332         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9333     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9334     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9335 
9336     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9337                           /*IsVolatile=*/false,
9338                           /*AlwaysInline=*/false, IsTailCall,
9339                           MachinePointerInfo(), MachinePointerInfo());
9340     ByValArgs.push_back(FIPtr);
9341   }
9342 
9343   if (!IsTailCall)
9344     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9345 
9346   // Copy argument values to their designated locations.
9347   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9348   SmallVector<SDValue, 8> MemOpChains;
9349   SDValue StackPtr;
9350   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9351     CCValAssign &VA = ArgLocs[i];
9352     SDValue ArgValue = OutVals[i];
9353     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9354 
9355     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9356     bool IsF64OnRV32DSoftABI =
9357         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9358     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9359       SDValue SplitF64 = DAG.getNode(
9360           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9361       SDValue Lo = SplitF64.getValue(0);
9362       SDValue Hi = SplitF64.getValue(1);
9363 
9364       Register RegLo = VA.getLocReg();
9365       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9366 
9367       if (RegLo == RISCV::X17) {
9368         // Second half of f64 is passed on the stack.
9369         // Work out the address of the stack slot.
9370         if (!StackPtr.getNode())
9371           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9372         // Emit the store.
9373         MemOpChains.push_back(
9374             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9375       } else {
9376         // Second half of f64 is passed in another GPR.
9377         assert(RegLo < RISCV::X31 && "Invalid register pair");
9378         Register RegHigh = RegLo + 1;
9379         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9380       }
9381       continue;
9382     }
9383 
9384     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9385     // as any other MemLoc.
9386 
9387     // Promote the value if needed.
9388     // For now, only handle fully promoted and indirect arguments.
9389     if (VA.getLocInfo() == CCValAssign::Indirect) {
9390       // Store the argument in a stack slot and pass its address.
9391       Align StackAlign =
9392           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9393                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9394       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9395       // If the original argument was split (e.g. i128), we need
9396       // to store the required parts of it here (and pass just one address).
9397       // Vectors may be partly split to registers and partly to the stack, in
9398       // which case the base address is partly offset and subsequent stores are
9399       // relative to that.
9400       unsigned ArgIndex = Outs[i].OrigArgIndex;
9401       unsigned ArgPartOffset = Outs[i].PartOffset;
9402       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9403       // Calculate the total size to store. We don't have access to what we're
9404       // actually storing other than performing the loop and collecting the
9405       // info.
9406       SmallVector<std::pair<SDValue, SDValue>> Parts;
9407       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9408         SDValue PartValue = OutVals[i + 1];
9409         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9410         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9411         EVT PartVT = PartValue.getValueType();
9412         if (PartVT.isScalableVector())
9413           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9414         StoredSize += PartVT.getStoreSize();
9415         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9416         Parts.push_back(std::make_pair(PartValue, Offset));
9417         ++i;
9418       }
9419       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9420       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9421       MemOpChains.push_back(
9422           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9423                        MachinePointerInfo::getFixedStack(MF, FI)));
9424       for (const auto &Part : Parts) {
9425         SDValue PartValue = Part.first;
9426         SDValue PartOffset = Part.second;
9427         SDValue Address =
9428             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9429         MemOpChains.push_back(
9430             DAG.getStore(Chain, DL, PartValue, Address,
9431                          MachinePointerInfo::getFixedStack(MF, FI)));
9432       }
9433       ArgValue = SpillSlot;
9434     } else {
9435       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9436     }
9437 
9438     // Use local copy if it is a byval arg.
9439     if (Flags.isByVal())
9440       ArgValue = ByValArgs[j++];
9441 
9442     if (VA.isRegLoc()) {
9443       // Queue up the argument copies and emit them at the end.
9444       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9445     } else {
9446       assert(VA.isMemLoc() && "Argument not register or memory");
9447       assert(!IsTailCall && "Tail call not allowed if stack is used "
9448                             "for passing parameters");
9449 
9450       // Work out the address of the stack slot.
9451       if (!StackPtr.getNode())
9452         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9453       SDValue Address =
9454           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9455                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9456 
9457       // Emit the store.
9458       MemOpChains.push_back(
9459           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9460     }
9461   }
9462 
9463   // Join the stores, which are independent of one another.
9464   if (!MemOpChains.empty())
9465     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9466 
9467   SDValue Glue;
9468 
9469   // Build a sequence of copy-to-reg nodes, chained and glued together.
9470   for (auto &Reg : RegsToPass) {
9471     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9472     Glue = Chain.getValue(1);
9473   }
9474 
9475   // Validate that none of the argument registers have been marked as
9476   // reserved, if so report an error. Do the same for the return address if this
9477   // is not a tailcall.
9478   validateCCReservedRegs(RegsToPass, MF);
9479   if (!IsTailCall &&
9480       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9481     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9482         MF.getFunction(),
9483         "Return address register required, but has been reserved."});
9484 
9485   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9486   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9487   // split it and then direct call can be matched by PseudoCALL.
9488   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9489     const GlobalValue *GV = S->getGlobal();
9490 
9491     unsigned OpFlags = RISCVII::MO_CALL;
9492     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9493       OpFlags = RISCVII::MO_PLT;
9494 
9495     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9496   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9497     unsigned OpFlags = RISCVII::MO_CALL;
9498 
9499     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9500                                                  nullptr))
9501       OpFlags = RISCVII::MO_PLT;
9502 
9503     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9504   }
9505 
9506   // The first call operand is the chain and the second is the target address.
9507   SmallVector<SDValue, 8> Ops;
9508   Ops.push_back(Chain);
9509   Ops.push_back(Callee);
9510 
9511   // Add argument registers to the end of the list so that they are
9512   // known live into the call.
9513   for (auto &Reg : RegsToPass)
9514     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9515 
9516   if (!IsTailCall) {
9517     // Add a register mask operand representing the call-preserved registers.
9518     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9519     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9520     assert(Mask && "Missing call preserved mask for calling convention");
9521     Ops.push_back(DAG.getRegisterMask(Mask));
9522   }
9523 
9524   // Glue the call to the argument copies, if any.
9525   if (Glue.getNode())
9526     Ops.push_back(Glue);
9527 
9528   // Emit the call.
9529   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9530 
9531   if (IsTailCall) {
9532     MF.getFrameInfo().setHasTailCall();
9533     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9534   }
9535 
9536   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9537   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9538   Glue = Chain.getValue(1);
9539 
9540   // Mark the end of the call, which is glued to the call itself.
9541   Chain = DAG.getCALLSEQ_END(Chain,
9542                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9543                              DAG.getConstant(0, DL, PtrVT, true),
9544                              Glue, DL);
9545   Glue = Chain.getValue(1);
9546 
9547   // Assign locations to each value returned by this call.
9548   SmallVector<CCValAssign, 16> RVLocs;
9549   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9550   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9551 
9552   // Copy all of the result registers out of their specified physreg.
9553   for (auto &VA : RVLocs) {
9554     // Copy the value out
9555     SDValue RetValue =
9556         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9557     // Glue the RetValue to the end of the call sequence
9558     Chain = RetValue.getValue(1);
9559     Glue = RetValue.getValue(2);
9560 
9561     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9562       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9563       SDValue RetValue2 =
9564           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9565       Chain = RetValue2.getValue(1);
9566       Glue = RetValue2.getValue(2);
9567       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9568                              RetValue2);
9569     }
9570 
9571     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9572 
9573     InVals.push_back(RetValue);
9574   }
9575 
9576   return Chain;
9577 }
9578 
9579 bool RISCVTargetLowering::CanLowerReturn(
9580     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9581     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9582   SmallVector<CCValAssign, 16> RVLocs;
9583   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9584 
9585   Optional<unsigned> FirstMaskArgument;
9586   if (Subtarget.hasVInstructions())
9587     FirstMaskArgument = preAssignMask(Outs);
9588 
9589   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9590     MVT VT = Outs[i].VT;
9591     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9592     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9593     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9594                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9595                  *this, FirstMaskArgument))
9596       return false;
9597   }
9598   return true;
9599 }
9600 
9601 SDValue
9602 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9603                                  bool IsVarArg,
9604                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9605                                  const SmallVectorImpl<SDValue> &OutVals,
9606                                  const SDLoc &DL, SelectionDAG &DAG) const {
9607   const MachineFunction &MF = DAG.getMachineFunction();
9608   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9609 
9610   // Stores the assignment of the return value to a location.
9611   SmallVector<CCValAssign, 16> RVLocs;
9612 
9613   // Info about the registers and stack slot.
9614   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9615                  *DAG.getContext());
9616 
9617   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9618                     nullptr, CC_RISCV);
9619 
9620   if (CallConv == CallingConv::GHC && !RVLocs.empty())
9621     report_fatal_error("GHC functions return void only");
9622 
9623   SDValue Glue;
9624   SmallVector<SDValue, 4> RetOps(1, Chain);
9625 
9626   // Copy the result values into the output registers.
9627   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
9628     SDValue Val = OutVals[i];
9629     CCValAssign &VA = RVLocs[i];
9630     assert(VA.isRegLoc() && "Can only return in registers!");
9631 
9632     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9633       // Handle returning f64 on RV32D with a soft float ABI.
9634       assert(VA.isRegLoc() && "Expected return via registers");
9635       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
9636                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
9637       SDValue Lo = SplitF64.getValue(0);
9638       SDValue Hi = SplitF64.getValue(1);
9639       Register RegLo = VA.getLocReg();
9640       assert(RegLo < RISCV::X31 && "Invalid register pair");
9641       Register RegHi = RegLo + 1;
9642 
9643       if (STI.isRegisterReservedByUser(RegLo) ||
9644           STI.isRegisterReservedByUser(RegHi))
9645         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9646             MF.getFunction(),
9647             "Return value register required, but has been reserved."});
9648 
9649       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
9650       Glue = Chain.getValue(1);
9651       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
9652       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
9653       Glue = Chain.getValue(1);
9654       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
9655     } else {
9656       // Handle a 'normal' return.
9657       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
9658       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
9659 
9660       if (STI.isRegisterReservedByUser(VA.getLocReg()))
9661         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9662             MF.getFunction(),
9663             "Return value register required, but has been reserved."});
9664 
9665       // Guarantee that all emitted copies are stuck together.
9666       Glue = Chain.getValue(1);
9667       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
9668     }
9669   }
9670 
9671   RetOps[0] = Chain; // Update chain.
9672 
9673   // Add the glue node if we have it.
9674   if (Glue.getNode()) {
9675     RetOps.push_back(Glue);
9676   }
9677 
9678   unsigned RetOpc = RISCVISD::RET_FLAG;
9679   // Interrupt service routines use different return instructions.
9680   const Function &Func = DAG.getMachineFunction().getFunction();
9681   if (Func.hasFnAttribute("interrupt")) {
9682     if (!Func.getReturnType()->isVoidTy())
9683       report_fatal_error(
9684           "Functions with the interrupt attribute must have void return type!");
9685 
9686     MachineFunction &MF = DAG.getMachineFunction();
9687     StringRef Kind =
9688       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9689 
9690     if (Kind == "user")
9691       RetOpc = RISCVISD::URET_FLAG;
9692     else if (Kind == "supervisor")
9693       RetOpc = RISCVISD::SRET_FLAG;
9694     else
9695       RetOpc = RISCVISD::MRET_FLAG;
9696   }
9697 
9698   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
9699 }
9700 
9701 void RISCVTargetLowering::validateCCReservedRegs(
9702     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
9703     MachineFunction &MF) const {
9704   const Function &F = MF.getFunction();
9705   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9706 
9707   if (llvm::any_of(Regs, [&STI](auto Reg) {
9708         return STI.isRegisterReservedByUser(Reg.first);
9709       }))
9710     F.getContext().diagnose(DiagnosticInfoUnsupported{
9711         F, "Argument register required, but has been reserved."});
9712 }
9713 
9714 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
9715   return CI->isTailCall();
9716 }
9717 
9718 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
9719 #define NODE_NAME_CASE(NODE)                                                   \
9720   case RISCVISD::NODE:                                                         \
9721     return "RISCVISD::" #NODE;
9722   // clang-format off
9723   switch ((RISCVISD::NodeType)Opcode) {
9724   case RISCVISD::FIRST_NUMBER:
9725     break;
9726   NODE_NAME_CASE(RET_FLAG)
9727   NODE_NAME_CASE(URET_FLAG)
9728   NODE_NAME_CASE(SRET_FLAG)
9729   NODE_NAME_CASE(MRET_FLAG)
9730   NODE_NAME_CASE(CALL)
9731   NODE_NAME_CASE(SELECT_CC)
9732   NODE_NAME_CASE(BR_CC)
9733   NODE_NAME_CASE(BuildPairF64)
9734   NODE_NAME_CASE(SplitF64)
9735   NODE_NAME_CASE(TAIL)
9736   NODE_NAME_CASE(MULHSU)
9737   NODE_NAME_CASE(SLLW)
9738   NODE_NAME_CASE(SRAW)
9739   NODE_NAME_CASE(SRLW)
9740   NODE_NAME_CASE(DIVW)
9741   NODE_NAME_CASE(DIVUW)
9742   NODE_NAME_CASE(REMUW)
9743   NODE_NAME_CASE(ROLW)
9744   NODE_NAME_CASE(RORW)
9745   NODE_NAME_CASE(CLZW)
9746   NODE_NAME_CASE(CTZW)
9747   NODE_NAME_CASE(FSLW)
9748   NODE_NAME_CASE(FSRW)
9749   NODE_NAME_CASE(FSL)
9750   NODE_NAME_CASE(FSR)
9751   NODE_NAME_CASE(FMV_H_X)
9752   NODE_NAME_CASE(FMV_X_ANYEXTH)
9753   NODE_NAME_CASE(FMV_W_X_RV64)
9754   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
9755   NODE_NAME_CASE(FCVT_X)
9756   NODE_NAME_CASE(FCVT_XU)
9757   NODE_NAME_CASE(FCVT_W_RV64)
9758   NODE_NAME_CASE(FCVT_WU_RV64)
9759   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
9760   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
9761   NODE_NAME_CASE(READ_CYCLE_WIDE)
9762   NODE_NAME_CASE(GREV)
9763   NODE_NAME_CASE(GREVW)
9764   NODE_NAME_CASE(GORC)
9765   NODE_NAME_CASE(GORCW)
9766   NODE_NAME_CASE(SHFL)
9767   NODE_NAME_CASE(SHFLW)
9768   NODE_NAME_CASE(UNSHFL)
9769   NODE_NAME_CASE(UNSHFLW)
9770   NODE_NAME_CASE(BFP)
9771   NODE_NAME_CASE(BFPW)
9772   NODE_NAME_CASE(BCOMPRESS)
9773   NODE_NAME_CASE(BCOMPRESSW)
9774   NODE_NAME_CASE(BDECOMPRESS)
9775   NODE_NAME_CASE(BDECOMPRESSW)
9776   NODE_NAME_CASE(VMV_V_X_VL)
9777   NODE_NAME_CASE(VFMV_V_F_VL)
9778   NODE_NAME_CASE(VMV_X_S)
9779   NODE_NAME_CASE(VMV_S_X_VL)
9780   NODE_NAME_CASE(VFMV_S_F_VL)
9781   NODE_NAME_CASE(SPLAT_VECTOR_I64)
9782   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
9783   NODE_NAME_CASE(READ_VLENB)
9784   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
9785   NODE_NAME_CASE(VSLIDEUP_VL)
9786   NODE_NAME_CASE(VSLIDE1UP_VL)
9787   NODE_NAME_CASE(VSLIDEDOWN_VL)
9788   NODE_NAME_CASE(VSLIDE1DOWN_VL)
9789   NODE_NAME_CASE(VID_VL)
9790   NODE_NAME_CASE(VFNCVT_ROD_VL)
9791   NODE_NAME_CASE(VECREDUCE_ADD_VL)
9792   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
9793   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
9794   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
9795   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
9796   NODE_NAME_CASE(VECREDUCE_AND_VL)
9797   NODE_NAME_CASE(VECREDUCE_OR_VL)
9798   NODE_NAME_CASE(VECREDUCE_XOR_VL)
9799   NODE_NAME_CASE(VECREDUCE_FADD_VL)
9800   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
9801   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
9802   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
9803   NODE_NAME_CASE(ADD_VL)
9804   NODE_NAME_CASE(AND_VL)
9805   NODE_NAME_CASE(MUL_VL)
9806   NODE_NAME_CASE(OR_VL)
9807   NODE_NAME_CASE(SDIV_VL)
9808   NODE_NAME_CASE(SHL_VL)
9809   NODE_NAME_CASE(SREM_VL)
9810   NODE_NAME_CASE(SRA_VL)
9811   NODE_NAME_CASE(SRL_VL)
9812   NODE_NAME_CASE(SUB_VL)
9813   NODE_NAME_CASE(UDIV_VL)
9814   NODE_NAME_CASE(UREM_VL)
9815   NODE_NAME_CASE(XOR_VL)
9816   NODE_NAME_CASE(SADDSAT_VL)
9817   NODE_NAME_CASE(UADDSAT_VL)
9818   NODE_NAME_CASE(SSUBSAT_VL)
9819   NODE_NAME_CASE(USUBSAT_VL)
9820   NODE_NAME_CASE(FADD_VL)
9821   NODE_NAME_CASE(FSUB_VL)
9822   NODE_NAME_CASE(FMUL_VL)
9823   NODE_NAME_CASE(FDIV_VL)
9824   NODE_NAME_CASE(FNEG_VL)
9825   NODE_NAME_CASE(FABS_VL)
9826   NODE_NAME_CASE(FSQRT_VL)
9827   NODE_NAME_CASE(FMA_VL)
9828   NODE_NAME_CASE(FCOPYSIGN_VL)
9829   NODE_NAME_CASE(SMIN_VL)
9830   NODE_NAME_CASE(SMAX_VL)
9831   NODE_NAME_CASE(UMIN_VL)
9832   NODE_NAME_CASE(UMAX_VL)
9833   NODE_NAME_CASE(FMINNUM_VL)
9834   NODE_NAME_CASE(FMAXNUM_VL)
9835   NODE_NAME_CASE(MULHS_VL)
9836   NODE_NAME_CASE(MULHU_VL)
9837   NODE_NAME_CASE(FP_TO_SINT_VL)
9838   NODE_NAME_CASE(FP_TO_UINT_VL)
9839   NODE_NAME_CASE(SINT_TO_FP_VL)
9840   NODE_NAME_CASE(UINT_TO_FP_VL)
9841   NODE_NAME_CASE(FP_EXTEND_VL)
9842   NODE_NAME_CASE(FP_ROUND_VL)
9843   NODE_NAME_CASE(VWMUL_VL)
9844   NODE_NAME_CASE(VWMULU_VL)
9845   NODE_NAME_CASE(SETCC_VL)
9846   NODE_NAME_CASE(VSELECT_VL)
9847   NODE_NAME_CASE(VMAND_VL)
9848   NODE_NAME_CASE(VMOR_VL)
9849   NODE_NAME_CASE(VMXOR_VL)
9850   NODE_NAME_CASE(VMCLR_VL)
9851   NODE_NAME_CASE(VMSET_VL)
9852   NODE_NAME_CASE(VRGATHER_VX_VL)
9853   NODE_NAME_CASE(VRGATHER_VV_VL)
9854   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
9855   NODE_NAME_CASE(VSEXT_VL)
9856   NODE_NAME_CASE(VZEXT_VL)
9857   NODE_NAME_CASE(VCPOP_VL)
9858   NODE_NAME_CASE(VLE_VL)
9859   NODE_NAME_CASE(VSE_VL)
9860   NODE_NAME_CASE(READ_CSR)
9861   NODE_NAME_CASE(WRITE_CSR)
9862   NODE_NAME_CASE(SWAP_CSR)
9863   }
9864   // clang-format on
9865   return nullptr;
9866 #undef NODE_NAME_CASE
9867 }
9868 
9869 /// getConstraintType - Given a constraint letter, return the type of
9870 /// constraint it is for this target.
9871 RISCVTargetLowering::ConstraintType
9872 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
9873   if (Constraint.size() == 1) {
9874     switch (Constraint[0]) {
9875     default:
9876       break;
9877     case 'f':
9878       return C_RegisterClass;
9879     case 'I':
9880     case 'J':
9881     case 'K':
9882       return C_Immediate;
9883     case 'A':
9884       return C_Memory;
9885     case 'S': // A symbolic address
9886       return C_Other;
9887     }
9888   } else {
9889     if (Constraint == "vr" || Constraint == "vm")
9890       return C_RegisterClass;
9891   }
9892   return TargetLowering::getConstraintType(Constraint);
9893 }
9894 
9895 std::pair<unsigned, const TargetRegisterClass *>
9896 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9897                                                   StringRef Constraint,
9898                                                   MVT VT) const {
9899   // First, see if this is a constraint that directly corresponds to a
9900   // RISCV register class.
9901   if (Constraint.size() == 1) {
9902     switch (Constraint[0]) {
9903     case 'r':
9904       // TODO: Support fixed vectors up to XLen for P extension?
9905       if (VT.isVector())
9906         break;
9907       return std::make_pair(0U, &RISCV::GPRRegClass);
9908     case 'f':
9909       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
9910         return std::make_pair(0U, &RISCV::FPR16RegClass);
9911       if (Subtarget.hasStdExtF() && VT == MVT::f32)
9912         return std::make_pair(0U, &RISCV::FPR32RegClass);
9913       if (Subtarget.hasStdExtD() && VT == MVT::f64)
9914         return std::make_pair(0U, &RISCV::FPR64RegClass);
9915       break;
9916     default:
9917       break;
9918     }
9919   } else if (Constraint == "vr") {
9920     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
9921                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
9922       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
9923         return std::make_pair(0U, RC);
9924     }
9925   } else if (Constraint == "vm") {
9926     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
9927       return std::make_pair(0U, &RISCV::VMV0RegClass);
9928   }
9929 
9930   // Clang will correctly decode the usage of register name aliases into their
9931   // official names. However, other frontends like `rustc` do not. This allows
9932   // users of these frontends to use the ABI names for registers in LLVM-style
9933   // register constraints.
9934   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
9935                                .Case("{zero}", RISCV::X0)
9936                                .Case("{ra}", RISCV::X1)
9937                                .Case("{sp}", RISCV::X2)
9938                                .Case("{gp}", RISCV::X3)
9939                                .Case("{tp}", RISCV::X4)
9940                                .Case("{t0}", RISCV::X5)
9941                                .Case("{t1}", RISCV::X6)
9942                                .Case("{t2}", RISCV::X7)
9943                                .Cases("{s0}", "{fp}", RISCV::X8)
9944                                .Case("{s1}", RISCV::X9)
9945                                .Case("{a0}", RISCV::X10)
9946                                .Case("{a1}", RISCV::X11)
9947                                .Case("{a2}", RISCV::X12)
9948                                .Case("{a3}", RISCV::X13)
9949                                .Case("{a4}", RISCV::X14)
9950                                .Case("{a5}", RISCV::X15)
9951                                .Case("{a6}", RISCV::X16)
9952                                .Case("{a7}", RISCV::X17)
9953                                .Case("{s2}", RISCV::X18)
9954                                .Case("{s3}", RISCV::X19)
9955                                .Case("{s4}", RISCV::X20)
9956                                .Case("{s5}", RISCV::X21)
9957                                .Case("{s6}", RISCV::X22)
9958                                .Case("{s7}", RISCV::X23)
9959                                .Case("{s8}", RISCV::X24)
9960                                .Case("{s9}", RISCV::X25)
9961                                .Case("{s10}", RISCV::X26)
9962                                .Case("{s11}", RISCV::X27)
9963                                .Case("{t3}", RISCV::X28)
9964                                .Case("{t4}", RISCV::X29)
9965                                .Case("{t5}", RISCV::X30)
9966                                .Case("{t6}", RISCV::X31)
9967                                .Default(RISCV::NoRegister);
9968   if (XRegFromAlias != RISCV::NoRegister)
9969     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
9970 
9971   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
9972   // TableGen record rather than the AsmName to choose registers for InlineAsm
9973   // constraints, plus we want to match those names to the widest floating point
9974   // register type available, manually select floating point registers here.
9975   //
9976   // The second case is the ABI name of the register, so that frontends can also
9977   // use the ABI names in register constraint lists.
9978   if (Subtarget.hasStdExtF()) {
9979     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
9980                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
9981                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
9982                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
9983                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
9984                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
9985                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
9986                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
9987                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
9988                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
9989                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
9990                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
9991                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
9992                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
9993                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
9994                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
9995                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
9996                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
9997                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
9998                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
9999                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10000                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10001                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10002                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10003                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10004                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10005                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10006                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10007                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10008                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10009                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10010                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10011                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10012                         .Default(RISCV::NoRegister);
10013     if (FReg != RISCV::NoRegister) {
10014       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10015       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10016         unsigned RegNo = FReg - RISCV::F0_F;
10017         unsigned DReg = RISCV::F0_D + RegNo;
10018         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10019       }
10020       if (VT == MVT::f32 || VT == MVT::Other)
10021         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10022       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10023         unsigned RegNo = FReg - RISCV::F0_F;
10024         unsigned HReg = RISCV::F0_H + RegNo;
10025         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10026       }
10027     }
10028   }
10029 
10030   if (Subtarget.hasVInstructions()) {
10031     Register VReg = StringSwitch<Register>(Constraint.lower())
10032                         .Case("{v0}", RISCV::V0)
10033                         .Case("{v1}", RISCV::V1)
10034                         .Case("{v2}", RISCV::V2)
10035                         .Case("{v3}", RISCV::V3)
10036                         .Case("{v4}", RISCV::V4)
10037                         .Case("{v5}", RISCV::V5)
10038                         .Case("{v6}", RISCV::V6)
10039                         .Case("{v7}", RISCV::V7)
10040                         .Case("{v8}", RISCV::V8)
10041                         .Case("{v9}", RISCV::V9)
10042                         .Case("{v10}", RISCV::V10)
10043                         .Case("{v11}", RISCV::V11)
10044                         .Case("{v12}", RISCV::V12)
10045                         .Case("{v13}", RISCV::V13)
10046                         .Case("{v14}", RISCV::V14)
10047                         .Case("{v15}", RISCV::V15)
10048                         .Case("{v16}", RISCV::V16)
10049                         .Case("{v17}", RISCV::V17)
10050                         .Case("{v18}", RISCV::V18)
10051                         .Case("{v19}", RISCV::V19)
10052                         .Case("{v20}", RISCV::V20)
10053                         .Case("{v21}", RISCV::V21)
10054                         .Case("{v22}", RISCV::V22)
10055                         .Case("{v23}", RISCV::V23)
10056                         .Case("{v24}", RISCV::V24)
10057                         .Case("{v25}", RISCV::V25)
10058                         .Case("{v26}", RISCV::V26)
10059                         .Case("{v27}", RISCV::V27)
10060                         .Case("{v28}", RISCV::V28)
10061                         .Case("{v29}", RISCV::V29)
10062                         .Case("{v30}", RISCV::V30)
10063                         .Case("{v31}", RISCV::V31)
10064                         .Default(RISCV::NoRegister);
10065     if (VReg != RISCV::NoRegister) {
10066       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10067         return std::make_pair(VReg, &RISCV::VMRegClass);
10068       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10069         return std::make_pair(VReg, &RISCV::VRRegClass);
10070       for (const auto *RC :
10071            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10072         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10073           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10074           return std::make_pair(VReg, RC);
10075         }
10076       }
10077     }
10078   }
10079 
10080   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10081 }
10082 
10083 unsigned
10084 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10085   // Currently only support length 1 constraints.
10086   if (ConstraintCode.size() == 1) {
10087     switch (ConstraintCode[0]) {
10088     case 'A':
10089       return InlineAsm::Constraint_A;
10090     default:
10091       break;
10092     }
10093   }
10094 
10095   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10096 }
10097 
10098 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10099     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10100     SelectionDAG &DAG) const {
10101   // Currently only support length 1 constraints.
10102   if (Constraint.length() == 1) {
10103     switch (Constraint[0]) {
10104     case 'I':
10105       // Validate & create a 12-bit signed immediate operand.
10106       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10107         uint64_t CVal = C->getSExtValue();
10108         if (isInt<12>(CVal))
10109           Ops.push_back(
10110               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10111       }
10112       return;
10113     case 'J':
10114       // Validate & create an integer zero operand.
10115       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10116         if (C->getZExtValue() == 0)
10117           Ops.push_back(
10118               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10119       return;
10120     case 'K':
10121       // Validate & create a 5-bit unsigned immediate operand.
10122       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10123         uint64_t CVal = C->getZExtValue();
10124         if (isUInt<5>(CVal))
10125           Ops.push_back(
10126               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10127       }
10128       return;
10129     case 'S':
10130       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10131         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10132                                                  GA->getValueType(0)));
10133       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10134         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10135                                                 BA->getValueType(0)));
10136       }
10137       return;
10138     default:
10139       break;
10140     }
10141   }
10142   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10143 }
10144 
10145 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10146                                                    Instruction *Inst,
10147                                                    AtomicOrdering Ord) const {
10148   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10149     return Builder.CreateFence(Ord);
10150   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10151     return Builder.CreateFence(AtomicOrdering::Release);
10152   return nullptr;
10153 }
10154 
10155 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10156                                                     Instruction *Inst,
10157                                                     AtomicOrdering Ord) const {
10158   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10159     return Builder.CreateFence(AtomicOrdering::Acquire);
10160   return nullptr;
10161 }
10162 
10163 TargetLowering::AtomicExpansionKind
10164 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10165   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10166   // point operations can't be used in an lr/sc sequence without breaking the
10167   // forward-progress guarantee.
10168   if (AI->isFloatingPointOperation())
10169     return AtomicExpansionKind::CmpXChg;
10170 
10171   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10172   if (Size == 8 || Size == 16)
10173     return AtomicExpansionKind::MaskedIntrinsic;
10174   return AtomicExpansionKind::None;
10175 }
10176 
10177 static Intrinsic::ID
10178 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10179   if (XLen == 32) {
10180     switch (BinOp) {
10181     default:
10182       llvm_unreachable("Unexpected AtomicRMW BinOp");
10183     case AtomicRMWInst::Xchg:
10184       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10185     case AtomicRMWInst::Add:
10186       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10187     case AtomicRMWInst::Sub:
10188       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10189     case AtomicRMWInst::Nand:
10190       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10191     case AtomicRMWInst::Max:
10192       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10193     case AtomicRMWInst::Min:
10194       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10195     case AtomicRMWInst::UMax:
10196       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10197     case AtomicRMWInst::UMin:
10198       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10199     }
10200   }
10201 
10202   if (XLen == 64) {
10203     switch (BinOp) {
10204     default:
10205       llvm_unreachable("Unexpected AtomicRMW BinOp");
10206     case AtomicRMWInst::Xchg:
10207       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10208     case AtomicRMWInst::Add:
10209       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10210     case AtomicRMWInst::Sub:
10211       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10212     case AtomicRMWInst::Nand:
10213       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10214     case AtomicRMWInst::Max:
10215       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10216     case AtomicRMWInst::Min:
10217       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10218     case AtomicRMWInst::UMax:
10219       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10220     case AtomicRMWInst::UMin:
10221       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10222     }
10223   }
10224 
10225   llvm_unreachable("Unexpected XLen\n");
10226 }
10227 
10228 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10229     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10230     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10231   unsigned XLen = Subtarget.getXLen();
10232   Value *Ordering =
10233       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10234   Type *Tys[] = {AlignedAddr->getType()};
10235   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10236       AI->getModule(),
10237       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10238 
10239   if (XLen == 64) {
10240     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10241     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10242     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10243   }
10244 
10245   Value *Result;
10246 
10247   // Must pass the shift amount needed to sign extend the loaded value prior
10248   // to performing a signed comparison for min/max. ShiftAmt is the number of
10249   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10250   // is the number of bits to left+right shift the value in order to
10251   // sign-extend.
10252   if (AI->getOperation() == AtomicRMWInst::Min ||
10253       AI->getOperation() == AtomicRMWInst::Max) {
10254     const DataLayout &DL = AI->getModule()->getDataLayout();
10255     unsigned ValWidth =
10256         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10257     Value *SextShamt =
10258         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10259     Result = Builder.CreateCall(LrwOpScwLoop,
10260                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10261   } else {
10262     Result =
10263         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10264   }
10265 
10266   if (XLen == 64)
10267     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10268   return Result;
10269 }
10270 
10271 TargetLowering::AtomicExpansionKind
10272 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10273     AtomicCmpXchgInst *CI) const {
10274   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10275   if (Size == 8 || Size == 16)
10276     return AtomicExpansionKind::MaskedIntrinsic;
10277   return AtomicExpansionKind::None;
10278 }
10279 
10280 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10281     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10282     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10283   unsigned XLen = Subtarget.getXLen();
10284   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10285   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10286   if (XLen == 64) {
10287     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10288     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10289     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10290     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10291   }
10292   Type *Tys[] = {AlignedAddr->getType()};
10293   Function *MaskedCmpXchg =
10294       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10295   Value *Result = Builder.CreateCall(
10296       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10297   if (XLen == 64)
10298     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10299   return Result;
10300 }
10301 
10302 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10303   return false;
10304 }
10305 
10306 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10307                                                EVT VT) const {
10308   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10309     return false;
10310 
10311   switch (FPVT.getSimpleVT().SimpleTy) {
10312   case MVT::f16:
10313     return Subtarget.hasStdExtZfh();
10314   case MVT::f32:
10315     return Subtarget.hasStdExtF();
10316   case MVT::f64:
10317     return Subtarget.hasStdExtD();
10318   default:
10319     return false;
10320   }
10321 }
10322 
10323 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10324   // If we are using the small code model, we can reduce size of jump table
10325   // entry to 4 bytes.
10326   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10327       getTargetMachine().getCodeModel() == CodeModel::Small) {
10328     return MachineJumpTableInfo::EK_Custom32;
10329   }
10330   return TargetLowering::getJumpTableEncoding();
10331 }
10332 
10333 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10334     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10335     unsigned uid, MCContext &Ctx) const {
10336   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10337          getTargetMachine().getCodeModel() == CodeModel::Small);
10338   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10339 }
10340 
10341 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10342                                                      EVT VT) const {
10343   VT = VT.getScalarType();
10344 
10345   if (!VT.isSimple())
10346     return false;
10347 
10348   switch (VT.getSimpleVT().SimpleTy) {
10349   case MVT::f16:
10350     return Subtarget.hasStdExtZfh();
10351   case MVT::f32:
10352     return Subtarget.hasStdExtF();
10353   case MVT::f64:
10354     return Subtarget.hasStdExtD();
10355   default:
10356     break;
10357   }
10358 
10359   return false;
10360 }
10361 
10362 Register RISCVTargetLowering::getExceptionPointerRegister(
10363     const Constant *PersonalityFn) const {
10364   return RISCV::X10;
10365 }
10366 
10367 Register RISCVTargetLowering::getExceptionSelectorRegister(
10368     const Constant *PersonalityFn) const {
10369   return RISCV::X11;
10370 }
10371 
10372 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10373   // Return false to suppress the unnecessary extensions if the LibCall
10374   // arguments or return value is f32 type for LP64 ABI.
10375   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10376   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10377     return false;
10378 
10379   return true;
10380 }
10381 
10382 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10383   if (Subtarget.is64Bit() && Type == MVT::i32)
10384     return true;
10385 
10386   return IsSigned;
10387 }
10388 
10389 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10390                                                  SDValue C) const {
10391   // Check integral scalar types.
10392   if (VT.isScalarInteger()) {
10393     // Omit the optimization if the sub target has the M extension and the data
10394     // size exceeds XLen.
10395     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10396       return false;
10397     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10398       // Break the MUL to a SLLI and an ADD/SUB.
10399       const APInt &Imm = ConstNode->getAPIntValue();
10400       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10401           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10402         return true;
10403       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10404       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10405           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10406            (Imm - 8).isPowerOf2()))
10407         return true;
10408       // Omit the following optimization if the sub target has the M extension
10409       // and the data size >= XLen.
10410       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10411         return false;
10412       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10413       // a pair of LUI/ADDI.
10414       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10415         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10416         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10417             (1 - ImmS).isPowerOf2())
10418         return true;
10419       }
10420     }
10421   }
10422 
10423   return false;
10424 }
10425 
10426 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10427     const SDValue &AddNode, const SDValue &ConstNode) const {
10428   // Let the DAGCombiner decide for vectors.
10429   EVT VT = AddNode.getValueType();
10430   if (VT.isVector())
10431     return true;
10432 
10433   // Let the DAGCombiner decide for larger types.
10434   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10435     return true;
10436 
10437   // It is worse if c1 is simm12 while c1*c2 is not.
10438   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10439   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10440   const APInt &C1 = C1Node->getAPIntValue();
10441   const APInt &C2 = C2Node->getAPIntValue();
10442   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10443     return false;
10444 
10445   // Default to true and let the DAGCombiner decide.
10446   return true;
10447 }
10448 
10449 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10450     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10451     bool *Fast) const {
10452   if (!VT.isVector())
10453     return false;
10454 
10455   EVT ElemVT = VT.getVectorElementType();
10456   if (Alignment >= ElemVT.getStoreSize()) {
10457     if (Fast)
10458       *Fast = true;
10459     return true;
10460   }
10461 
10462   return false;
10463 }
10464 
10465 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10466     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10467     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10468   bool IsABIRegCopy = CC.hasValue();
10469   EVT ValueVT = Val.getValueType();
10470   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10471     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10472     // and cast to f32.
10473     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10474     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10475     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10476                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10477     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10478     Parts[0] = Val;
10479     return true;
10480   }
10481 
10482   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10483     LLVMContext &Context = *DAG.getContext();
10484     EVT ValueEltVT = ValueVT.getVectorElementType();
10485     EVT PartEltVT = PartVT.getVectorElementType();
10486     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10487     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10488     if (PartVTBitSize % ValueVTBitSize == 0) {
10489       assert(PartVTBitSize >= ValueVTBitSize);
10490       // If the element types are different, bitcast to the same element type of
10491       // PartVT first.
10492       // Give an example here, we want copy a <vscale x 1 x i8> value to
10493       // <vscale x 4 x i16>.
10494       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10495       // subvector, then we can bitcast to <vscale x 4 x i16>.
10496       if (ValueEltVT != PartEltVT) {
10497         if (PartVTBitSize > ValueVTBitSize) {
10498           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10499           assert(Count != 0 && "The number of element should not be zero.");
10500           EVT SameEltTypeVT =
10501               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10502           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10503                             DAG.getUNDEF(SameEltTypeVT), Val,
10504                             DAG.getVectorIdxConstant(0, DL));
10505         }
10506         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10507       } else {
10508         Val =
10509             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10510                         Val, DAG.getVectorIdxConstant(0, DL));
10511       }
10512       Parts[0] = Val;
10513       return true;
10514     }
10515   }
10516   return false;
10517 }
10518 
10519 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10520     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10521     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10522   bool IsABIRegCopy = CC.hasValue();
10523   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10524     SDValue Val = Parts[0];
10525 
10526     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10527     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10528     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10529     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10530     return Val;
10531   }
10532 
10533   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10534     LLVMContext &Context = *DAG.getContext();
10535     SDValue Val = Parts[0];
10536     EVT ValueEltVT = ValueVT.getVectorElementType();
10537     EVT PartEltVT = PartVT.getVectorElementType();
10538     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10539     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10540     if (PartVTBitSize % ValueVTBitSize == 0) {
10541       assert(PartVTBitSize >= ValueVTBitSize);
10542       EVT SameEltTypeVT = ValueVT;
10543       // If the element types are different, convert it to the same element type
10544       // of PartVT.
10545       // Give an example here, we want copy a <vscale x 1 x i8> value from
10546       // <vscale x 4 x i16>.
10547       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10548       // then we can extract <vscale x 1 x i8>.
10549       if (ValueEltVT != PartEltVT) {
10550         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10551         assert(Count != 0 && "The number of element should not be zero.");
10552         SameEltTypeVT =
10553             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10554         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10555       }
10556       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10557                         DAG.getVectorIdxConstant(0, DL));
10558       return Val;
10559     }
10560   }
10561   return SDValue();
10562 }
10563 
10564 SDValue
10565 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10566                                    SelectionDAG &DAG,
10567                                    SmallVectorImpl<SDNode *> &Created) const {
10568   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10569   if (isIntDivCheap(N->getValueType(0), Attr))
10570     return SDValue(N, 0); // Lower SDIV as SDIV
10571 
10572   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
10573          "Unexpected divisor!");
10574 
10575   // Conditional move is needed, so do the transformation iff Zbt is enabled.
10576   if (!Subtarget.hasStdExtZbt())
10577     return SDValue();
10578 
10579   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
10580   // Besides, more critical path instructions will be generated when dividing
10581   // by 2. So we keep using the original DAGs for these cases.
10582   unsigned Lg2 = Divisor.countTrailingZeros();
10583   if (Lg2 == 1 || Lg2 >= 12)
10584     return SDValue();
10585 
10586   // fold (sdiv X, pow2)
10587   EVT VT = N->getValueType(0);
10588   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
10589     return SDValue();
10590 
10591   SDLoc DL(N);
10592   SDValue N0 = N->getOperand(0);
10593   SDValue Zero = DAG.getConstant(0, DL, VT);
10594   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10595 
10596   // Add (N0 < 0) ? Pow2 - 1 : 0;
10597   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
10598   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10599   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
10600 
10601   Created.push_back(Cmp.getNode());
10602   Created.push_back(Add.getNode());
10603   Created.push_back(Sel.getNode());
10604 
10605   // Divide by pow2.
10606   SDValue SRA =
10607       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
10608 
10609   // If we're dividing by a positive value, we're done.  Otherwise, we must
10610   // negate the result.
10611   if (Divisor.isNonNegative())
10612     return SRA;
10613 
10614   Created.push_back(SRA.getNode());
10615   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10616 }
10617 
10618 #define GET_REGISTER_MATCHER
10619 #include "RISCVGenAsmMatcher.inc"
10620 
10621 Register
10622 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
10623                                        const MachineFunction &MF) const {
10624   Register Reg = MatchRegisterAltName(RegName);
10625   if (Reg == RISCV::NoRegister)
10626     Reg = MatchRegisterName(RegName);
10627   if (Reg == RISCV::NoRegister)
10628     report_fatal_error(
10629         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
10630   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
10631   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
10632     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
10633                              StringRef(RegName) + "\"."));
10634   return Reg;
10635 }
10636 
10637 namespace llvm {
10638 namespace RISCVVIntrinsicsTable {
10639 
10640 #define GET_RISCVVIntrinsicsTable_IMPL
10641 #include "RISCVGenSearchableTables.inc"
10642 
10643 } // namespace RISCVVIntrinsicsTable
10644 
10645 } // namespace llvm
10646