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       Subtarget.hasStdExtZbkb()) {
255     if (Subtarget.is64Bit()) {
256       setOperationAction(ISD::ROTL, MVT::i32, Custom);
257       setOperationAction(ISD::ROTR, MVT::i32, Custom);
258     }
259   } else {
260     setOperationAction(ISD::ROTL, XLenVT, Expand);
261     setOperationAction(ISD::ROTR, XLenVT, Expand);
262   }
263 
264   if (Subtarget.hasStdExtZbp()) {
265     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
266     // more combining.
267     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
268     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
269     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
270     // BSWAP i8 doesn't exist.
271     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
272     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
273 
274     if (Subtarget.is64Bit()) {
275       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
276       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
277     }
278   } else {
279     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
280     // pattern match it directly in isel.
281     setOperationAction(ISD::BSWAP, XLenVT,
282                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
283                            ? Legal
284                            : Expand);
285     // Zbkb can use rev8+brev8 to implement bitreverse.
286     setOperationAction(ISD::BITREVERSE, XLenVT,
287                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
288   }
289 
290   if (Subtarget.hasStdExtZbb()) {
291     setOperationAction(ISD::SMIN, XLenVT, Legal);
292     setOperationAction(ISD::SMAX, XLenVT, Legal);
293     setOperationAction(ISD::UMIN, XLenVT, Legal);
294     setOperationAction(ISD::UMAX, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit()) {
297       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
298       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
299       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
300       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
301     }
302   } else {
303     setOperationAction(ISD::CTTZ, XLenVT, Expand);
304     setOperationAction(ISD::CTLZ, XLenVT, Expand);
305     setOperationAction(ISD::CTPOP, XLenVT, Expand);
306   }
307 
308   if (Subtarget.hasStdExtZbt()) {
309     setOperationAction(ISD::FSHL, XLenVT, Custom);
310     setOperationAction(ISD::FSHR, XLenVT, Custom);
311     setOperationAction(ISD::SELECT, XLenVT, Legal);
312 
313     if (Subtarget.is64Bit()) {
314       setOperationAction(ISD::FSHL, MVT::i32, Custom);
315       setOperationAction(ISD::FSHR, MVT::i32, Custom);
316     }
317   } else {
318     setOperationAction(ISD::SELECT, XLenVT, Custom);
319   }
320 
321   static const ISD::CondCode FPCCToExpand[] = {
322       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
323       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
324       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
325 
326   static const ISD::NodeType FPOpToExpand[] = {
327       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
328       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
329 
330   if (Subtarget.hasStdExtZfh())
331     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
332 
333   if (Subtarget.hasStdExtZfh()) {
334     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
335     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
336     setOperationAction(ISD::LRINT, MVT::f16, Legal);
337     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
338     setOperationAction(ISD::LROUND, MVT::f16, Legal);
339     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
340     setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal);
341     setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal);
342     setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal);
343     setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal);
344     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
345     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
346     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
349     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
350     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
352     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal);
353     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal);
354     for (auto CC : FPCCToExpand)
355       setCondCodeAction(CC, MVT::f16, Expand);
356     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
357     setOperationAction(ISD::SELECT, MVT::f16, Custom);
358     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
359 
360     setOperationAction(ISD::FREM,       MVT::f16, Promote);
361     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
362     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
363     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
364     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
365     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
366     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
367     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
368     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
369     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
370     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
371     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
372     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
373     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
374     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
375     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
376     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
377     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
378 
379     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
380     // complete support for all operations in LegalizeDAG.
381 
382     // We need to custom promote this.
383     if (Subtarget.is64Bit())
384       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
385   }
386 
387   if (Subtarget.hasStdExtF()) {
388     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
389     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
390     setOperationAction(ISD::LRINT, MVT::f32, Legal);
391     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
392     setOperationAction(ISD::LROUND, MVT::f32, Legal);
393     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
394     setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal);
395     setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal);
396     setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal);
397     setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal);
398     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
399     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
400     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
401     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
402     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
404     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
405     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
406     for (auto CC : FPCCToExpand)
407       setCondCodeAction(CC, MVT::f32, Expand);
408     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
409     setOperationAction(ISD::SELECT, MVT::f32, Custom);
410     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f32, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
418     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
419 
420   if (Subtarget.hasStdExtD()) {
421     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
422     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
423     setOperationAction(ISD::LRINT, MVT::f64, Legal);
424     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
425     setOperationAction(ISD::LROUND, MVT::f64, Legal);
426     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
427     setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal);
428     setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal);
429     setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal);
431     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
432     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
433     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
435     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
436     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
437     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
438     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
439     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
440     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
441     for (auto CC : FPCCToExpand)
442       setCondCodeAction(CC, MVT::f64, Expand);
443     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
444     setOperationAction(ISD::SELECT, MVT::f64, Custom);
445     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
446     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
447     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
448     for (auto Op : FPOpToExpand)
449       setOperationAction(Op, MVT::f64, Expand);
450     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
451     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
452   }
453 
454   if (Subtarget.is64Bit()) {
455     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
456     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
457     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
458     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
459   }
460 
461   if (Subtarget.hasStdExtF()) {
462     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
463     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
464 
465     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
466     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
467     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
468     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
469 
470     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
471     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
472   }
473 
474   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
475   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
476   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
477   setOperationAction(ISD::JumpTable, XLenVT, Custom);
478 
479   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
480 
481   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
482   // Unfortunately this can't be determined just from the ISA naming string.
483   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
484                      Subtarget.is64Bit() ? Legal : Custom);
485 
486   setOperationAction(ISD::TRAP, MVT::Other, Legal);
487   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
488   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
489   if (Subtarget.is64Bit())
490     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
491 
492   if (Subtarget.hasStdExtA()) {
493     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
494     setMinCmpXchgSizeInBits(32);
495   } else {
496     setMaxAtomicSizeInBitsSupported(0);
497   }
498 
499   setBooleanContents(ZeroOrOneBooleanContent);
500 
501   if (Subtarget.hasVInstructions()) {
502     setBooleanVectorContents(ZeroOrOneBooleanContent);
503 
504     setOperationAction(ISD::VSCALE, XLenVT, Custom);
505 
506     // RVV intrinsics may have illegal operands.
507     // We also need to custom legalize vmv.x.s.
508     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
509     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
510     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
511     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
512     if (Subtarget.is64Bit()) {
513       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
514     } else {
515       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
516       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
517     }
518 
519     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
520     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
521 
522     static const unsigned IntegerVPOps[] = {
523         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
524         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
525         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
526         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
527         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
528         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
529         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
530         ISD::VP_MERGE,       ISD::VP_SELECT};
531 
532     static const unsigned FloatingPointVPOps[] = {
533         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
534         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
535         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,
536         ISD::VP_SELECT};
537 
538     if (!Subtarget.is64Bit()) {
539       // We must custom-lower certain vXi64 operations on RV32 due to the vector
540       // element type being illegal.
541       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
543 
544       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
545       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
546       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
547       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
548       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
549       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
550       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
551       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
552 
553       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
554       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
555       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
556       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
557       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
558       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
559       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
560       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
561     }
562 
563     for (MVT VT : BoolVecVTs) {
564       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
565 
566       // Mask VTs are custom-expanded into a series of standard nodes
567       setOperationAction(ISD::TRUNCATE, VT, Custom);
568       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
569       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
570       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
571 
572       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
573       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
574 
575       setOperationAction(ISD::SELECT, VT, Custom);
576       setOperationAction(ISD::SELECT_CC, VT, Expand);
577       setOperationAction(ISD::VSELECT, VT, Expand);
578       setOperationAction(ISD::VP_MERGE, VT, Expand);
579       setOperationAction(ISD::VP_SELECT, VT, Expand);
580 
581       setOperationAction(ISD::VP_AND, VT, Custom);
582       setOperationAction(ISD::VP_OR, VT, Custom);
583       setOperationAction(ISD::VP_XOR, VT, Custom);
584 
585       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
586       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
587       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
588 
589       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
590       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
591       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
592 
593       // RVV has native int->float & float->int conversions where the
594       // element type sizes are within one power-of-two of each other. Any
595       // wider distances between type sizes have to be lowered as sequences
596       // which progressively narrow the gap in stages.
597       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
598       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
599       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
600       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
601 
602       // Expand all extending loads to types larger than this, and truncating
603       // stores from types larger than this.
604       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
605         setTruncStoreAction(OtherVT, VT, Expand);
606         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
607         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
608         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
609       }
610     }
611 
612     for (MVT VT : IntVecVTs) {
613       if (VT.getVectorElementType() == MVT::i64 &&
614           !Subtarget.hasVInstructionsI64())
615         continue;
616 
617       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
618       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
619 
620       // Vectors implement MULHS/MULHU.
621       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
622       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
623 
624       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
625       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
626         setOperationAction(ISD::MULHU, VT, Expand);
627         setOperationAction(ISD::MULHS, VT, Expand);
628       }
629 
630       setOperationAction(ISD::SMIN, VT, Legal);
631       setOperationAction(ISD::SMAX, VT, Legal);
632       setOperationAction(ISD::UMIN, VT, Legal);
633       setOperationAction(ISD::UMAX, VT, Legal);
634 
635       setOperationAction(ISD::ROTL, VT, Expand);
636       setOperationAction(ISD::ROTR, VT, Expand);
637 
638       setOperationAction(ISD::CTTZ, VT, Expand);
639       setOperationAction(ISD::CTLZ, VT, Expand);
640       setOperationAction(ISD::CTPOP, VT, Expand);
641 
642       setOperationAction(ISD::BSWAP, VT, Expand);
643 
644       // Custom-lower extensions and truncations from/to mask types.
645       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
646       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
647       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
648 
649       // RVV has native int->float & float->int conversions where the
650       // element type sizes are within one power-of-two of each other. Any
651       // wider distances between type sizes have to be lowered as sequences
652       // which progressively narrow the gap in stages.
653       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
654       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
655       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
656       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
657 
658       setOperationAction(ISD::SADDSAT, VT, Legal);
659       setOperationAction(ISD::UADDSAT, VT, Legal);
660       setOperationAction(ISD::SSUBSAT, VT, Legal);
661       setOperationAction(ISD::USUBSAT, VT, Legal);
662 
663       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
664       // nodes which truncate by one power of two at a time.
665       setOperationAction(ISD::TRUNCATE, VT, Custom);
666 
667       // Custom-lower insert/extract operations to simplify patterns.
668       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
669       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
670 
671       // Custom-lower reduction operations to set up the corresponding custom
672       // nodes' operands.
673       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
674       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
675       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
676       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
677       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
678       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
679       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
680       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
681 
682       for (unsigned VPOpc : IntegerVPOps)
683         setOperationAction(VPOpc, VT, Custom);
684 
685       setOperationAction(ISD::LOAD, VT, Custom);
686       setOperationAction(ISD::STORE, VT, Custom);
687 
688       setOperationAction(ISD::MLOAD, VT, Custom);
689       setOperationAction(ISD::MSTORE, VT, Custom);
690       setOperationAction(ISD::MGATHER, VT, Custom);
691       setOperationAction(ISD::MSCATTER, VT, Custom);
692 
693       setOperationAction(ISD::VP_LOAD, VT, Custom);
694       setOperationAction(ISD::VP_STORE, VT, Custom);
695       setOperationAction(ISD::VP_GATHER, VT, Custom);
696       setOperationAction(ISD::VP_SCATTER, VT, Custom);
697 
698       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
699       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
700       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
701 
702       setOperationAction(ISD::SELECT, VT, Custom);
703       setOperationAction(ISD::SELECT_CC, VT, Expand);
704 
705       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
706       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
707 
708       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
709         setTruncStoreAction(VT, OtherVT, Expand);
710         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
711         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
712         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
713       }
714 
715       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
716       // type that can represent the value exactly.
717       if (VT.getVectorElementType() != MVT::i64) {
718         MVT FloatEltVT =
719             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
720         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
721         if (isTypeLegal(FloatVT)) {
722           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
723           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
724         }
725       }
726     }
727 
728     // Expand various CCs to best match the RVV ISA, which natively supports UNE
729     // but no other unordered comparisons, and supports all ordered comparisons
730     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
731     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
732     // and we pattern-match those back to the "original", swapping operands once
733     // more. This way we catch both operations and both "vf" and "fv" forms with
734     // fewer patterns.
735     static const ISD::CondCode VFPCCToExpand[] = {
736         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
737         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
738         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
739     };
740 
741     // Sets common operation actions on RVV floating-point vector types.
742     const auto SetCommonVFPActions = [&](MVT VT) {
743       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
744       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
745       // sizes are within one power-of-two of each other. Therefore conversions
746       // between vXf16 and vXf64 must be lowered as sequences which convert via
747       // vXf32.
748       setOperationAction(ISD::FP_ROUND, VT, Custom);
749       setOperationAction(ISD::FP_EXTEND, VT, Custom);
750       // Custom-lower insert/extract operations to simplify patterns.
751       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
752       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
753       // Expand various condition codes (explained above).
754       for (auto CC : VFPCCToExpand)
755         setCondCodeAction(CC, VT, Expand);
756 
757       setOperationAction(ISD::FMINNUM, VT, Legal);
758       setOperationAction(ISD::FMAXNUM, VT, Legal);
759 
760       setOperationAction(ISD::FTRUNC, VT, Custom);
761       setOperationAction(ISD::FCEIL, VT, Custom);
762       setOperationAction(ISD::FFLOOR, VT, Custom);
763 
764       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
765       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
766       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
767       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
768 
769       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
770 
771       setOperationAction(ISD::LOAD, VT, Custom);
772       setOperationAction(ISD::STORE, VT, Custom);
773 
774       setOperationAction(ISD::MLOAD, VT, Custom);
775       setOperationAction(ISD::MSTORE, VT, Custom);
776       setOperationAction(ISD::MGATHER, VT, Custom);
777       setOperationAction(ISD::MSCATTER, VT, Custom);
778 
779       setOperationAction(ISD::VP_LOAD, VT, Custom);
780       setOperationAction(ISD::VP_STORE, VT, Custom);
781       setOperationAction(ISD::VP_GATHER, VT, Custom);
782       setOperationAction(ISD::VP_SCATTER, VT, Custom);
783 
784       setOperationAction(ISD::SELECT, VT, Custom);
785       setOperationAction(ISD::SELECT_CC, VT, Expand);
786 
787       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
788       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
789       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
790 
791       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
792 
793       for (unsigned VPOpc : FloatingPointVPOps)
794         setOperationAction(VPOpc, VT, Custom);
795     };
796 
797     // Sets common extload/truncstore actions on RVV floating-point vector
798     // types.
799     const auto SetCommonVFPExtLoadTruncStoreActions =
800         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
801           for (auto SmallVT : SmallerVTs) {
802             setTruncStoreAction(VT, SmallVT, Expand);
803             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
804           }
805         };
806 
807     if (Subtarget.hasVInstructionsF16())
808       for (MVT VT : F16VecVTs)
809         SetCommonVFPActions(VT);
810 
811     for (MVT VT : F32VecVTs) {
812       if (Subtarget.hasVInstructionsF32())
813         SetCommonVFPActions(VT);
814       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
815     }
816 
817     for (MVT VT : F64VecVTs) {
818       if (Subtarget.hasVInstructionsF64())
819         SetCommonVFPActions(VT);
820       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
821       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
822     }
823 
824     if (Subtarget.useRVVForFixedLengthVectors()) {
825       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
826         if (!useRVVForFixedLengthVectorVT(VT))
827           continue;
828 
829         // By default everything must be expanded.
830         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
831           setOperationAction(Op, VT, Expand);
832         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
833           setTruncStoreAction(VT, OtherVT, Expand);
834           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
835           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
836           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
837         }
838 
839         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
840         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
841         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
842 
843         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
844         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
845 
846         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
847         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
848 
849         setOperationAction(ISD::LOAD, VT, Custom);
850         setOperationAction(ISD::STORE, VT, Custom);
851 
852         setOperationAction(ISD::SETCC, VT, Custom);
853 
854         setOperationAction(ISD::SELECT, VT, Custom);
855 
856         setOperationAction(ISD::TRUNCATE, VT, Custom);
857 
858         setOperationAction(ISD::BITCAST, VT, Custom);
859 
860         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
861         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
862         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
863 
864         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
865         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
866         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
867 
868         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
869         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
870         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
871         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
872 
873         // Operations below are different for between masks and other vectors.
874         if (VT.getVectorElementType() == MVT::i1) {
875           setOperationAction(ISD::VP_AND, VT, Custom);
876           setOperationAction(ISD::VP_OR, VT, Custom);
877           setOperationAction(ISD::VP_XOR, VT, Custom);
878           setOperationAction(ISD::AND, VT, Custom);
879           setOperationAction(ISD::OR, VT, Custom);
880           setOperationAction(ISD::XOR, VT, Custom);
881           continue;
882         }
883 
884         // Use SPLAT_VECTOR to prevent type legalization from destroying the
885         // splats when type legalizing i64 scalar on RV32.
886         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
887         // improvements first.
888         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
889           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
890           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
891         }
892 
893         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
894         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
895 
896         setOperationAction(ISD::MLOAD, VT, Custom);
897         setOperationAction(ISD::MSTORE, VT, Custom);
898         setOperationAction(ISD::MGATHER, VT, Custom);
899         setOperationAction(ISD::MSCATTER, VT, Custom);
900 
901         setOperationAction(ISD::VP_LOAD, VT, Custom);
902         setOperationAction(ISD::VP_STORE, VT, Custom);
903         setOperationAction(ISD::VP_GATHER, VT, Custom);
904         setOperationAction(ISD::VP_SCATTER, VT, Custom);
905 
906         setOperationAction(ISD::ADD, VT, Custom);
907         setOperationAction(ISD::MUL, VT, Custom);
908         setOperationAction(ISD::SUB, VT, Custom);
909         setOperationAction(ISD::AND, VT, Custom);
910         setOperationAction(ISD::OR, VT, Custom);
911         setOperationAction(ISD::XOR, VT, Custom);
912         setOperationAction(ISD::SDIV, VT, Custom);
913         setOperationAction(ISD::SREM, VT, Custom);
914         setOperationAction(ISD::UDIV, VT, Custom);
915         setOperationAction(ISD::UREM, VT, Custom);
916         setOperationAction(ISD::SHL, VT, Custom);
917         setOperationAction(ISD::SRA, VT, Custom);
918         setOperationAction(ISD::SRL, VT, Custom);
919 
920         setOperationAction(ISD::SMIN, VT, Custom);
921         setOperationAction(ISD::SMAX, VT, Custom);
922         setOperationAction(ISD::UMIN, VT, Custom);
923         setOperationAction(ISD::UMAX, VT, Custom);
924         setOperationAction(ISD::ABS,  VT, Custom);
925 
926         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
927         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
928           setOperationAction(ISD::MULHS, VT, Custom);
929           setOperationAction(ISD::MULHU, VT, Custom);
930         }
931 
932         setOperationAction(ISD::SADDSAT, VT, Custom);
933         setOperationAction(ISD::UADDSAT, VT, Custom);
934         setOperationAction(ISD::SSUBSAT, VT, Custom);
935         setOperationAction(ISD::USUBSAT, VT, Custom);
936 
937         setOperationAction(ISD::VSELECT, VT, Custom);
938         setOperationAction(ISD::SELECT_CC, VT, Expand);
939 
940         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
941         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
942         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
943 
944         // Custom-lower reduction operations to set up the corresponding custom
945         // nodes' operands.
946         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
947         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
948         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
949         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
950         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
951 
952         for (unsigned VPOpc : IntegerVPOps)
953           setOperationAction(VPOpc, VT, Custom);
954 
955         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
956         // type that can represent the value exactly.
957         if (VT.getVectorElementType() != MVT::i64) {
958           MVT FloatEltVT =
959               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
960           EVT FloatVT =
961               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
962           if (isTypeLegal(FloatVT)) {
963             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
964             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
965           }
966         }
967       }
968 
969       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
970         if (!useRVVForFixedLengthVectorVT(VT))
971           continue;
972 
973         // By default everything must be expanded.
974         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
975           setOperationAction(Op, VT, Expand);
976         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
977           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
978           setTruncStoreAction(VT, OtherVT, Expand);
979         }
980 
981         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
982         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
983         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
984 
985         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
986         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
987         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
988         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
989         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
990 
991         setOperationAction(ISD::LOAD, VT, Custom);
992         setOperationAction(ISD::STORE, VT, Custom);
993         setOperationAction(ISD::MLOAD, VT, Custom);
994         setOperationAction(ISD::MSTORE, VT, Custom);
995         setOperationAction(ISD::MGATHER, VT, Custom);
996         setOperationAction(ISD::MSCATTER, VT, Custom);
997 
998         setOperationAction(ISD::VP_LOAD, VT, Custom);
999         setOperationAction(ISD::VP_STORE, VT, Custom);
1000         setOperationAction(ISD::VP_GATHER, VT, Custom);
1001         setOperationAction(ISD::VP_SCATTER, VT, Custom);
1002 
1003         setOperationAction(ISD::FADD, VT, Custom);
1004         setOperationAction(ISD::FSUB, VT, Custom);
1005         setOperationAction(ISD::FMUL, VT, Custom);
1006         setOperationAction(ISD::FDIV, VT, Custom);
1007         setOperationAction(ISD::FNEG, VT, Custom);
1008         setOperationAction(ISD::FABS, VT, Custom);
1009         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1010         setOperationAction(ISD::FSQRT, VT, Custom);
1011         setOperationAction(ISD::FMA, VT, Custom);
1012         setOperationAction(ISD::FMINNUM, VT, Custom);
1013         setOperationAction(ISD::FMAXNUM, VT, Custom);
1014 
1015         setOperationAction(ISD::FP_ROUND, VT, Custom);
1016         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1017 
1018         setOperationAction(ISD::FTRUNC, VT, Custom);
1019         setOperationAction(ISD::FCEIL, VT, Custom);
1020         setOperationAction(ISD::FFLOOR, VT, Custom);
1021 
1022         for (auto CC : VFPCCToExpand)
1023           setCondCodeAction(CC, VT, Expand);
1024 
1025         setOperationAction(ISD::VSELECT, VT, Custom);
1026         setOperationAction(ISD::SELECT, VT, Custom);
1027         setOperationAction(ISD::SELECT_CC, VT, Expand);
1028 
1029         setOperationAction(ISD::BITCAST, VT, Custom);
1030 
1031         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1032         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1033         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1034         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1035 
1036         for (unsigned VPOpc : FloatingPointVPOps)
1037           setOperationAction(VPOpc, VT, Custom);
1038       }
1039 
1040       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1041       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1042       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1043       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1044       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1045       if (Subtarget.hasStdExtZfh())
1046         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1047       if (Subtarget.hasStdExtF())
1048         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1049       if (Subtarget.hasStdExtD())
1050         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1051     }
1052   }
1053 
1054   // Function alignments.
1055   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1056   setMinFunctionAlignment(FunctionAlignment);
1057   setPrefFunctionAlignment(FunctionAlignment);
1058 
1059   setMinimumJumpTableEntries(5);
1060 
1061   // Jumps are expensive, compared to logic
1062   setJumpIsExpensive();
1063 
1064   setTargetDAGCombine(ISD::ADD);
1065   setTargetDAGCombine(ISD::SUB);
1066   setTargetDAGCombine(ISD::AND);
1067   setTargetDAGCombine(ISD::OR);
1068   setTargetDAGCombine(ISD::XOR);
1069   setTargetDAGCombine(ISD::ANY_EXTEND);
1070   if (Subtarget.hasStdExtF()) {
1071     setTargetDAGCombine(ISD::ZERO_EXTEND);
1072     setTargetDAGCombine(ISD::FP_TO_SINT);
1073     setTargetDAGCombine(ISD::FP_TO_UINT);
1074     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1075     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1076   }
1077   if (Subtarget.hasVInstructions()) {
1078     setTargetDAGCombine(ISD::FCOPYSIGN);
1079     setTargetDAGCombine(ISD::MGATHER);
1080     setTargetDAGCombine(ISD::MSCATTER);
1081     setTargetDAGCombine(ISD::VP_GATHER);
1082     setTargetDAGCombine(ISD::VP_SCATTER);
1083     setTargetDAGCombine(ISD::SRA);
1084     setTargetDAGCombine(ISD::SRL);
1085     setTargetDAGCombine(ISD::SHL);
1086     setTargetDAGCombine(ISD::STORE);
1087   }
1088 
1089   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1090   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1091 }
1092 
1093 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1094                                             LLVMContext &Context,
1095                                             EVT VT) const {
1096   if (!VT.isVector())
1097     return getPointerTy(DL);
1098   if (Subtarget.hasVInstructions() &&
1099       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1100     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1101   return VT.changeVectorElementTypeToInteger();
1102 }
1103 
1104 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1105   return Subtarget.getXLenVT();
1106 }
1107 
1108 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1109                                              const CallInst &I,
1110                                              MachineFunction &MF,
1111                                              unsigned Intrinsic) const {
1112   auto &DL = I.getModule()->getDataLayout();
1113   switch (Intrinsic) {
1114   default:
1115     return false;
1116   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1117   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1118   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1119   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1120   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1121   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1122   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1123   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1124   case Intrinsic::riscv_masked_cmpxchg_i32:
1125     Info.opc = ISD::INTRINSIC_W_CHAIN;
1126     Info.memVT = MVT::i32;
1127     Info.ptrVal = I.getArgOperand(0);
1128     Info.offset = 0;
1129     Info.align = Align(4);
1130     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1131                  MachineMemOperand::MOVolatile;
1132     return true;
1133   case Intrinsic::riscv_masked_strided_load:
1134     Info.opc = ISD::INTRINSIC_W_CHAIN;
1135     Info.ptrVal = I.getArgOperand(1);
1136     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1137     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1138     Info.size = MemoryLocation::UnknownSize;
1139     Info.flags |= MachineMemOperand::MOLoad;
1140     return true;
1141   case Intrinsic::riscv_masked_strided_store:
1142     Info.opc = ISD::INTRINSIC_VOID;
1143     Info.ptrVal = I.getArgOperand(1);
1144     Info.memVT =
1145         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1146     Info.align = Align(
1147         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1148         8);
1149     Info.size = MemoryLocation::UnknownSize;
1150     Info.flags |= MachineMemOperand::MOStore;
1151     return true;
1152   }
1153 }
1154 
1155 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1156                                                 const AddrMode &AM, Type *Ty,
1157                                                 unsigned AS,
1158                                                 Instruction *I) const {
1159   // No global is ever allowed as a base.
1160   if (AM.BaseGV)
1161     return false;
1162 
1163   // Require a 12-bit signed offset.
1164   if (!isInt<12>(AM.BaseOffs))
1165     return false;
1166 
1167   switch (AM.Scale) {
1168   case 0: // "r+i" or just "i", depending on HasBaseReg.
1169     break;
1170   case 1:
1171     if (!AM.HasBaseReg) // allow "r+i".
1172       break;
1173     return false; // disallow "r+r" or "r+r+i".
1174   default:
1175     return false;
1176   }
1177 
1178   return true;
1179 }
1180 
1181 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1182   return isInt<12>(Imm);
1183 }
1184 
1185 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1186   return isInt<12>(Imm);
1187 }
1188 
1189 // On RV32, 64-bit integers are split into their high and low parts and held
1190 // in two different registers, so the trunc is free since the low register can
1191 // just be used.
1192 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1193   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1194     return false;
1195   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1196   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1197   return (SrcBits == 64 && DestBits == 32);
1198 }
1199 
1200 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1201   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1202       !SrcVT.isInteger() || !DstVT.isInteger())
1203     return false;
1204   unsigned SrcBits = SrcVT.getSizeInBits();
1205   unsigned DestBits = DstVT.getSizeInBits();
1206   return (SrcBits == 64 && DestBits == 32);
1207 }
1208 
1209 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1210   // Zexts are free if they can be combined with a load.
1211   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1212   // poorly with type legalization of compares preferring sext.
1213   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1214     EVT MemVT = LD->getMemoryVT();
1215     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1216         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1217          LD->getExtensionType() == ISD::ZEXTLOAD))
1218       return true;
1219   }
1220 
1221   return TargetLowering::isZExtFree(Val, VT2);
1222 }
1223 
1224 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1225   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1226 }
1227 
1228 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1229   return Subtarget.hasStdExtZbb();
1230 }
1231 
1232 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1233   return Subtarget.hasStdExtZbb();
1234 }
1235 
1236 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1237   EVT VT = Y.getValueType();
1238 
1239   // FIXME: Support vectors once we have tests.
1240   if (VT.isVector())
1241     return false;
1242 
1243   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1244           Subtarget.hasStdExtZbkb()) &&
1245          !isa<ConstantSDNode>(Y);
1246 }
1247 
1248 /// Check if sinking \p I's operands to I's basic block is profitable, because
1249 /// the operands can be folded into a target instruction, e.g.
1250 /// splats of scalars can fold into vector instructions.
1251 bool RISCVTargetLowering::shouldSinkOperands(
1252     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1253   using namespace llvm::PatternMatch;
1254 
1255   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1256     return false;
1257 
1258   auto IsSinker = [&](Instruction *I, int Operand) {
1259     switch (I->getOpcode()) {
1260     case Instruction::Add:
1261     case Instruction::Sub:
1262     case Instruction::Mul:
1263     case Instruction::And:
1264     case Instruction::Or:
1265     case Instruction::Xor:
1266     case Instruction::FAdd:
1267     case Instruction::FSub:
1268     case Instruction::FMul:
1269     case Instruction::FDiv:
1270     case Instruction::ICmp:
1271     case Instruction::FCmp:
1272       return true;
1273     case Instruction::Shl:
1274     case Instruction::LShr:
1275     case Instruction::AShr:
1276     case Instruction::UDiv:
1277     case Instruction::SDiv:
1278     case Instruction::URem:
1279     case Instruction::SRem:
1280       return Operand == 1;
1281     case Instruction::Call:
1282       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1283         switch (II->getIntrinsicID()) {
1284         case Intrinsic::fma:
1285           return Operand == 0 || Operand == 1;
1286         // FIXME: Our patterns can only match vx/vf instructions when the splat
1287         // it on the RHS, because TableGen doesn't recognize our VP operations
1288         // as commutative.
1289         case Intrinsic::vp_add:
1290         case Intrinsic::vp_mul:
1291         case Intrinsic::vp_and:
1292         case Intrinsic::vp_or:
1293         case Intrinsic::vp_xor:
1294         case Intrinsic::vp_fadd:
1295         case Intrinsic::vp_fmul:
1296         case Intrinsic::vp_shl:
1297         case Intrinsic::vp_lshr:
1298         case Intrinsic::vp_ashr:
1299         case Intrinsic::vp_udiv:
1300         case Intrinsic::vp_sdiv:
1301         case Intrinsic::vp_urem:
1302         case Intrinsic::vp_srem:
1303           return Operand == 1;
1304         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1305         // explicit patterns for both LHS and RHS (as 'vr' versions).
1306         case Intrinsic::vp_sub:
1307         case Intrinsic::vp_fsub:
1308         case Intrinsic::vp_fdiv:
1309           return Operand == 0 || Operand == 1;
1310         default:
1311           return false;
1312         }
1313       }
1314       return false;
1315     default:
1316       return false;
1317     }
1318   };
1319 
1320   for (auto OpIdx : enumerate(I->operands())) {
1321     if (!IsSinker(I, OpIdx.index()))
1322       continue;
1323 
1324     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1325     // Make sure we are not already sinking this operand
1326     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1327       continue;
1328 
1329     // We are looking for a splat that can be sunk.
1330     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1331                              m_Undef(), m_ZeroMask())))
1332       continue;
1333 
1334     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1335     // and vector registers
1336     for (Use &U : Op->uses()) {
1337       Instruction *Insn = cast<Instruction>(U.getUser());
1338       if (!IsSinker(Insn, U.getOperandNo()))
1339         return false;
1340     }
1341 
1342     Ops.push_back(&Op->getOperandUse(0));
1343     Ops.push_back(&OpIdx.value());
1344   }
1345   return true;
1346 }
1347 
1348 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1349                                        bool ForCodeSize) const {
1350   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1351   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1352     return false;
1353   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1354     return false;
1355   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1356     return false;
1357   return Imm.isZero();
1358 }
1359 
1360 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1361   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1362          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1363          (VT == MVT::f64 && Subtarget.hasStdExtD());
1364 }
1365 
1366 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1367                                                       CallingConv::ID CC,
1368                                                       EVT VT) const {
1369   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1370   // We might still end up using a GPR but that will be decided based on ABI.
1371   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1372   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1373     return MVT::f32;
1374 
1375   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1376 }
1377 
1378 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1379                                                            CallingConv::ID CC,
1380                                                            EVT VT) const {
1381   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1382   // We might still end up using a GPR but that will be decided based on ABI.
1383   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1384   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1385     return 1;
1386 
1387   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1388 }
1389 
1390 // Changes the condition code and swaps operands if necessary, so the SetCC
1391 // operation matches one of the comparisons supported directly by branches
1392 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1393 // with 1/-1.
1394 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1395                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1396   // Convert X > -1 to X >= 0.
1397   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1398     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1399     CC = ISD::SETGE;
1400     return;
1401   }
1402   // Convert X < 1 to 0 >= X.
1403   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1404     RHS = LHS;
1405     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1406     CC = ISD::SETGE;
1407     return;
1408   }
1409 
1410   switch (CC) {
1411   default:
1412     break;
1413   case ISD::SETGT:
1414   case ISD::SETLE:
1415   case ISD::SETUGT:
1416   case ISD::SETULE:
1417     CC = ISD::getSetCCSwappedOperands(CC);
1418     std::swap(LHS, RHS);
1419     break;
1420   }
1421 }
1422 
1423 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1424   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1425   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1426   if (VT.getVectorElementType() == MVT::i1)
1427     KnownSize *= 8;
1428 
1429   switch (KnownSize) {
1430   default:
1431     llvm_unreachable("Invalid LMUL.");
1432   case 8:
1433     return RISCVII::VLMUL::LMUL_F8;
1434   case 16:
1435     return RISCVII::VLMUL::LMUL_F4;
1436   case 32:
1437     return RISCVII::VLMUL::LMUL_F2;
1438   case 64:
1439     return RISCVII::VLMUL::LMUL_1;
1440   case 128:
1441     return RISCVII::VLMUL::LMUL_2;
1442   case 256:
1443     return RISCVII::VLMUL::LMUL_4;
1444   case 512:
1445     return RISCVII::VLMUL::LMUL_8;
1446   }
1447 }
1448 
1449 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1450   switch (LMul) {
1451   default:
1452     llvm_unreachable("Invalid LMUL.");
1453   case RISCVII::VLMUL::LMUL_F8:
1454   case RISCVII::VLMUL::LMUL_F4:
1455   case RISCVII::VLMUL::LMUL_F2:
1456   case RISCVII::VLMUL::LMUL_1:
1457     return RISCV::VRRegClassID;
1458   case RISCVII::VLMUL::LMUL_2:
1459     return RISCV::VRM2RegClassID;
1460   case RISCVII::VLMUL::LMUL_4:
1461     return RISCV::VRM4RegClassID;
1462   case RISCVII::VLMUL::LMUL_8:
1463     return RISCV::VRM8RegClassID;
1464   }
1465 }
1466 
1467 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1468   RISCVII::VLMUL LMUL = getLMUL(VT);
1469   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1470       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1471       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1472       LMUL == RISCVII::VLMUL::LMUL_1) {
1473     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1474                   "Unexpected subreg numbering");
1475     return RISCV::sub_vrm1_0 + Index;
1476   }
1477   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1478     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1479                   "Unexpected subreg numbering");
1480     return RISCV::sub_vrm2_0 + Index;
1481   }
1482   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1483     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1484                   "Unexpected subreg numbering");
1485     return RISCV::sub_vrm4_0 + Index;
1486   }
1487   llvm_unreachable("Invalid vector type.");
1488 }
1489 
1490 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1491   if (VT.getVectorElementType() == MVT::i1)
1492     return RISCV::VRRegClassID;
1493   return getRegClassIDForLMUL(getLMUL(VT));
1494 }
1495 
1496 // Attempt to decompose a subvector insert/extract between VecVT and
1497 // SubVecVT via subregister indices. Returns the subregister index that
1498 // can perform the subvector insert/extract with the given element index, as
1499 // well as the index corresponding to any leftover subvectors that must be
1500 // further inserted/extracted within the register class for SubVecVT.
1501 std::pair<unsigned, unsigned>
1502 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1503     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1504     const RISCVRegisterInfo *TRI) {
1505   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1506                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1507                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1508                 "Register classes not ordered");
1509   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1510   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1511   // Try to compose a subregister index that takes us from the incoming
1512   // LMUL>1 register class down to the outgoing one. At each step we half
1513   // the LMUL:
1514   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1515   // Note that this is not guaranteed to find a subregister index, such as
1516   // when we are extracting from one VR type to another.
1517   unsigned SubRegIdx = RISCV::NoSubRegister;
1518   for (const unsigned RCID :
1519        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1520     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1521       VecVT = VecVT.getHalfNumVectorElementsVT();
1522       bool IsHi =
1523           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1524       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1525                                             getSubregIndexByMVT(VecVT, IsHi));
1526       if (IsHi)
1527         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1528     }
1529   return {SubRegIdx, InsertExtractIdx};
1530 }
1531 
1532 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1533 // stores for those types.
1534 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1535   return !Subtarget.useRVVForFixedLengthVectors() ||
1536          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1537 }
1538 
1539 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1540   if (ScalarTy->isPointerTy())
1541     return true;
1542 
1543   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1544       ScalarTy->isIntegerTy(32))
1545     return true;
1546 
1547   if (ScalarTy->isIntegerTy(64))
1548     return Subtarget.hasVInstructionsI64();
1549 
1550   if (ScalarTy->isHalfTy())
1551     return Subtarget.hasVInstructionsF16();
1552   if (ScalarTy->isFloatTy())
1553     return Subtarget.hasVInstructionsF32();
1554   if (ScalarTy->isDoubleTy())
1555     return Subtarget.hasVInstructionsF64();
1556 
1557   return false;
1558 }
1559 
1560 static SDValue getVLOperand(SDValue Op) {
1561   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1562           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1563          "Unexpected opcode");
1564   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1565   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1566   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1567       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1568   if (!II)
1569     return SDValue();
1570   return Op.getOperand(II->VLOperand + 1 + HasChain);
1571 }
1572 
1573 static bool useRVVForFixedLengthVectorVT(MVT VT,
1574                                          const RISCVSubtarget &Subtarget) {
1575   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1576   if (!Subtarget.useRVVForFixedLengthVectors())
1577     return false;
1578 
1579   // We only support a set of vector types with a consistent maximum fixed size
1580   // across all supported vector element types to avoid legalization issues.
1581   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1582   // fixed-length vector type we support is 1024 bytes.
1583   if (VT.getFixedSizeInBits() > 1024 * 8)
1584     return false;
1585 
1586   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1587 
1588   MVT EltVT = VT.getVectorElementType();
1589 
1590   // Don't use RVV for vectors we cannot scalarize if required.
1591   switch (EltVT.SimpleTy) {
1592   // i1 is supported but has different rules.
1593   default:
1594     return false;
1595   case MVT::i1:
1596     // Masks can only use a single register.
1597     if (VT.getVectorNumElements() > MinVLen)
1598       return false;
1599     MinVLen /= 8;
1600     break;
1601   case MVT::i8:
1602   case MVT::i16:
1603   case MVT::i32:
1604     break;
1605   case MVT::i64:
1606     if (!Subtarget.hasVInstructionsI64())
1607       return false;
1608     break;
1609   case MVT::f16:
1610     if (!Subtarget.hasVInstructionsF16())
1611       return false;
1612     break;
1613   case MVT::f32:
1614     if (!Subtarget.hasVInstructionsF32())
1615       return false;
1616     break;
1617   case MVT::f64:
1618     if (!Subtarget.hasVInstructionsF64())
1619       return false;
1620     break;
1621   }
1622 
1623   // Reject elements larger than ELEN.
1624   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1625     return false;
1626 
1627   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1628   // Don't use RVV for types that don't fit.
1629   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1630     return false;
1631 
1632   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1633   // the base fixed length RVV support in place.
1634   if (!VT.isPow2VectorType())
1635     return false;
1636 
1637   return true;
1638 }
1639 
1640 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1641   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1642 }
1643 
1644 // Return the largest legal scalable vector type that matches VT's element type.
1645 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1646                                             const RISCVSubtarget &Subtarget) {
1647   // This may be called before legal types are setup.
1648   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1649           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1650          "Expected legal fixed length vector!");
1651 
1652   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1653   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1654 
1655   MVT EltVT = VT.getVectorElementType();
1656   switch (EltVT.SimpleTy) {
1657   default:
1658     llvm_unreachable("unexpected element type for RVV container");
1659   case MVT::i1:
1660   case MVT::i8:
1661   case MVT::i16:
1662   case MVT::i32:
1663   case MVT::i64:
1664   case MVT::f16:
1665   case MVT::f32:
1666   case MVT::f64: {
1667     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1668     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1669     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1670     unsigned NumElts =
1671         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1672     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1673     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1674     return MVT::getScalableVectorVT(EltVT, NumElts);
1675   }
1676   }
1677 }
1678 
1679 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1680                                             const RISCVSubtarget &Subtarget) {
1681   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1682                                           Subtarget);
1683 }
1684 
1685 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1686   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1687 }
1688 
1689 // Grow V to consume an entire RVV register.
1690 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1691                                        const RISCVSubtarget &Subtarget) {
1692   assert(VT.isScalableVector() &&
1693          "Expected to convert into a scalable vector!");
1694   assert(V.getValueType().isFixedLengthVector() &&
1695          "Expected a fixed length vector operand!");
1696   SDLoc DL(V);
1697   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1698   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1699 }
1700 
1701 // Shrink V so it's just big enough to maintain a VT's worth of data.
1702 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1703                                          const RISCVSubtarget &Subtarget) {
1704   assert(VT.isFixedLengthVector() &&
1705          "Expected to convert into a fixed length vector!");
1706   assert(V.getValueType().isScalableVector() &&
1707          "Expected a scalable vector operand!");
1708   SDLoc DL(V);
1709   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1710   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1711 }
1712 
1713 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1714 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1715 // the vector type that it is contained in.
1716 static std::pair<SDValue, SDValue>
1717 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1718                 const RISCVSubtarget &Subtarget) {
1719   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1720   MVT XLenVT = Subtarget.getXLenVT();
1721   SDValue VL = VecVT.isFixedLengthVector()
1722                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1723                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1724   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1725   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1726   return {Mask, VL};
1727 }
1728 
1729 // As above but assuming the given type is a scalable vector type.
1730 static std::pair<SDValue, SDValue>
1731 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1732                         const RISCVSubtarget &Subtarget) {
1733   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1734   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1735 }
1736 
1737 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1738 // of either is (currently) supported. This can get us into an infinite loop
1739 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1740 // as a ..., etc.
1741 // Until either (or both) of these can reliably lower any node, reporting that
1742 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1743 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1744 // which is not desirable.
1745 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1746     EVT VT, unsigned DefinedValues) const {
1747   return false;
1748 }
1749 
1750 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1751   // Only splats are currently supported.
1752   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1753     return true;
1754 
1755   return false;
1756 }
1757 
1758 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1759                                   const RISCVSubtarget &Subtarget) {
1760   // RISCV FP-to-int conversions saturate to the destination register size, but
1761   // don't produce 0 for nan. We can use a conversion instruction and fix the
1762   // nan case with a compare and a select.
1763   SDValue Src = Op.getOperand(0);
1764 
1765   EVT DstVT = Op.getValueType();
1766   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1767 
1768   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1769   unsigned Opc;
1770   if (SatVT == DstVT)
1771     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1772   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1773     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1774   else
1775     return SDValue();
1776   // FIXME: Support other SatVTs by clamping before or after the conversion.
1777 
1778   SDLoc DL(Op);
1779   SDValue FpToInt = DAG.getNode(
1780       Opc, DL, DstVT, Src,
1781       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1782 
1783   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1784   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1785 }
1786 
1787 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1788 // and back. Taking care to avoid converting values that are nan or already
1789 // correct.
1790 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1791 // have FRM dependencies modeled yet.
1792 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1793   MVT VT = Op.getSimpleValueType();
1794   assert(VT.isVector() && "Unexpected type");
1795 
1796   SDLoc DL(Op);
1797 
1798   // Freeze the source since we are increasing the number of uses.
1799   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1800 
1801   // Truncate to integer and convert back to FP.
1802   MVT IntVT = VT.changeVectorElementTypeToInteger();
1803   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1804   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1805 
1806   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1807 
1808   if (Op.getOpcode() == ISD::FCEIL) {
1809     // If the truncated value is the greater than or equal to the original
1810     // value, we've computed the ceil. Otherwise, we went the wrong way and
1811     // need to increase by 1.
1812     // FIXME: This should use a masked operation. Handle here or in isel?
1813     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1814                                  DAG.getConstantFP(1.0, DL, VT));
1815     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1816     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1817   } else if (Op.getOpcode() == ISD::FFLOOR) {
1818     // If the truncated value is the less than or equal to the original value,
1819     // we've computed the floor. Otherwise, we went the wrong way and need to
1820     // decrease by 1.
1821     // FIXME: This should use a masked operation. Handle here or in isel?
1822     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1823                                  DAG.getConstantFP(1.0, DL, VT));
1824     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1825     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1826   }
1827 
1828   // Restore the original sign so that -0.0 is preserved.
1829   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1830 
1831   // Determine the largest integer that can be represented exactly. This and
1832   // values larger than it don't have any fractional bits so don't need to
1833   // be converted.
1834   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1835   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1836   APFloat MaxVal = APFloat(FltSem);
1837   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1838                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1839   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1840 
1841   // If abs(Src) was larger than MaxVal or nan, keep it.
1842   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1843   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1844   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1845 }
1846 
1847 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1848                                  const RISCVSubtarget &Subtarget) {
1849   MVT VT = Op.getSimpleValueType();
1850   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1851 
1852   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1853 
1854   SDLoc DL(Op);
1855   SDValue Mask, VL;
1856   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1857 
1858   unsigned Opc =
1859       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1860   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1861   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1862 }
1863 
1864 struct VIDSequence {
1865   int64_t StepNumerator;
1866   unsigned StepDenominator;
1867   int64_t Addend;
1868 };
1869 
1870 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1871 // to the (non-zero) step S and start value X. This can be then lowered as the
1872 // RVV sequence (VID * S) + X, for example.
1873 // The step S is represented as an integer numerator divided by a positive
1874 // denominator. Note that the implementation currently only identifies
1875 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1876 // cannot detect 2/3, for example.
1877 // Note that this method will also match potentially unappealing index
1878 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1879 // determine whether this is worth generating code for.
1880 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1881   unsigned NumElts = Op.getNumOperands();
1882   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1883   if (!Op.getValueType().isInteger())
1884     return None;
1885 
1886   Optional<unsigned> SeqStepDenom;
1887   Optional<int64_t> SeqStepNum, SeqAddend;
1888   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1889   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1890   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1891     // Assume undef elements match the sequence; we just have to be careful
1892     // when interpolating across them.
1893     if (Op.getOperand(Idx).isUndef())
1894       continue;
1895     // The BUILD_VECTOR must be all constants.
1896     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1897       return None;
1898 
1899     uint64_t Val = Op.getConstantOperandVal(Idx) &
1900                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1901 
1902     if (PrevElt) {
1903       // Calculate the step since the last non-undef element, and ensure
1904       // it's consistent across the entire sequence.
1905       unsigned IdxDiff = Idx - PrevElt->second;
1906       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1907 
1908       // A zero-value value difference means that we're somewhere in the middle
1909       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1910       // step change before evaluating the sequence.
1911       if (ValDiff != 0) {
1912         int64_t Remainder = ValDiff % IdxDiff;
1913         // Normalize the step if it's greater than 1.
1914         if (Remainder != ValDiff) {
1915           // The difference must cleanly divide the element span.
1916           if (Remainder != 0)
1917             return None;
1918           ValDiff /= IdxDiff;
1919           IdxDiff = 1;
1920         }
1921 
1922         if (!SeqStepNum)
1923           SeqStepNum = ValDiff;
1924         else if (ValDiff != SeqStepNum)
1925           return None;
1926 
1927         if (!SeqStepDenom)
1928           SeqStepDenom = IdxDiff;
1929         else if (IdxDiff != *SeqStepDenom)
1930           return None;
1931       }
1932     }
1933 
1934     // Record and/or check any addend.
1935     if (SeqStepNum && SeqStepDenom) {
1936       uint64_t ExpectedVal =
1937           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1938       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1939       if (!SeqAddend)
1940         SeqAddend = Addend;
1941       else if (SeqAddend != Addend)
1942         return None;
1943     }
1944 
1945     // Record this non-undef element for later.
1946     if (!PrevElt || PrevElt->first != Val)
1947       PrevElt = std::make_pair(Val, Idx);
1948   }
1949   // We need to have logged both a step and an addend for this to count as
1950   // a legal index sequence.
1951   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1952     return None;
1953 
1954   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1955 }
1956 
1957 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1958                                  const RISCVSubtarget &Subtarget) {
1959   MVT VT = Op.getSimpleValueType();
1960   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1961 
1962   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1963 
1964   SDLoc DL(Op);
1965   SDValue Mask, VL;
1966   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1967 
1968   MVT XLenVT = Subtarget.getXLenVT();
1969   unsigned NumElts = Op.getNumOperands();
1970 
1971   if (VT.getVectorElementType() == MVT::i1) {
1972     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1973       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1974       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1975     }
1976 
1977     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1978       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1979       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1980     }
1981 
1982     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1983     // scalar integer chunks whose bit-width depends on the number of mask
1984     // bits and XLEN.
1985     // First, determine the most appropriate scalar integer type to use. This
1986     // is at most XLenVT, but may be shrunk to a smaller vector element type
1987     // according to the size of the final vector - use i8 chunks rather than
1988     // XLenVT if we're producing a v8i1. This results in more consistent
1989     // codegen across RV32 and RV64.
1990     unsigned NumViaIntegerBits =
1991         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1992     NumViaIntegerBits = std::min(NumViaIntegerBits,
1993                                  Subtarget.getMaxELENForFixedLengthVectors());
1994     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1995       // If we have to use more than one INSERT_VECTOR_ELT then this
1996       // optimization is likely to increase code size; avoid peforming it in
1997       // such a case. We can use a load from a constant pool in this case.
1998       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1999         return SDValue();
2000       // Now we can create our integer vector type. Note that it may be larger
2001       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2002       MVT IntegerViaVecVT =
2003           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2004                            divideCeil(NumElts, NumViaIntegerBits));
2005 
2006       uint64_t Bits = 0;
2007       unsigned BitPos = 0, IntegerEltIdx = 0;
2008       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2009 
2010       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2011         // Once we accumulate enough bits to fill our scalar type, insert into
2012         // our vector and clear our accumulated data.
2013         if (I != 0 && I % NumViaIntegerBits == 0) {
2014           if (NumViaIntegerBits <= 32)
2015             Bits = SignExtend64(Bits, 32);
2016           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2017           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2018                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2019           Bits = 0;
2020           BitPos = 0;
2021           IntegerEltIdx++;
2022         }
2023         SDValue V = Op.getOperand(I);
2024         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2025         Bits |= ((uint64_t)BitValue << BitPos);
2026       }
2027 
2028       // Insert the (remaining) scalar value into position in our integer
2029       // vector type.
2030       if (NumViaIntegerBits <= 32)
2031         Bits = SignExtend64(Bits, 32);
2032       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2033       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2034                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2035 
2036       if (NumElts < NumViaIntegerBits) {
2037         // If we're producing a smaller vector than our minimum legal integer
2038         // type, bitcast to the equivalent (known-legal) mask type, and extract
2039         // our final mask.
2040         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2041         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2042         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2043                           DAG.getConstant(0, DL, XLenVT));
2044       } else {
2045         // Else we must have produced an integer type with the same size as the
2046         // mask type; bitcast for the final result.
2047         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2048         Vec = DAG.getBitcast(VT, Vec);
2049       }
2050 
2051       return Vec;
2052     }
2053 
2054     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2055     // vector type, we have a legal equivalently-sized i8 type, so we can use
2056     // that.
2057     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2058     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2059 
2060     SDValue WideVec;
2061     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2062       // For a splat, perform a scalar truncate before creating the wider
2063       // vector.
2064       assert(Splat.getValueType() == XLenVT &&
2065              "Unexpected type for i1 splat value");
2066       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2067                           DAG.getConstant(1, DL, XLenVT));
2068       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2069     } else {
2070       SmallVector<SDValue, 8> Ops(Op->op_values());
2071       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2072       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2073       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2074     }
2075 
2076     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2077   }
2078 
2079   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2080     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2081                                         : RISCVISD::VMV_V_X_VL;
2082     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2083     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2084   }
2085 
2086   // Try and match index sequences, which we can lower to the vid instruction
2087   // with optional modifications. An all-undef vector is matched by
2088   // getSplatValue, above.
2089   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2090     int64_t StepNumerator = SimpleVID->StepNumerator;
2091     unsigned StepDenominator = SimpleVID->StepDenominator;
2092     int64_t Addend = SimpleVID->Addend;
2093 
2094     assert(StepNumerator != 0 && "Invalid step");
2095     bool Negate = false;
2096     int64_t SplatStepVal = StepNumerator;
2097     unsigned StepOpcode = ISD::MUL;
2098     if (StepNumerator != 1) {
2099       if (isPowerOf2_64(std::abs(StepNumerator))) {
2100         Negate = StepNumerator < 0;
2101         StepOpcode = ISD::SHL;
2102         SplatStepVal = Log2_64(std::abs(StepNumerator));
2103       }
2104     }
2105 
2106     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2107     // threshold since it's the immediate value many RVV instructions accept.
2108     // There is no vmul.vi instruction so ensure multiply constant can fit in
2109     // a single addi instruction.
2110     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2111          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2112         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2113       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2114       // Convert right out of the scalable type so we can use standard ISD
2115       // nodes for the rest of the computation. If we used scalable types with
2116       // these, we'd lose the fixed-length vector info and generate worse
2117       // vsetvli code.
2118       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2119       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2120           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2121         SDValue SplatStep = DAG.getSplatVector(
2122             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2123         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2124       }
2125       if (StepDenominator != 1) {
2126         SDValue SplatStep = DAG.getSplatVector(
2127             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2128         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2129       }
2130       if (Addend != 0 || Negate) {
2131         SDValue SplatAddend =
2132             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2133         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2134       }
2135       return VID;
2136     }
2137   }
2138 
2139   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2140   // when re-interpreted as a vector with a larger element type. For example,
2141   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2142   // could be instead splat as
2143   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2144   // TODO: This optimization could also work on non-constant splats, but it
2145   // would require bit-manipulation instructions to construct the splat value.
2146   SmallVector<SDValue> Sequence;
2147   unsigned EltBitSize = VT.getScalarSizeInBits();
2148   const auto *BV = cast<BuildVectorSDNode>(Op);
2149   if (VT.isInteger() && EltBitSize < 64 &&
2150       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2151       BV->getRepeatedSequence(Sequence) &&
2152       (Sequence.size() * EltBitSize) <= 64) {
2153     unsigned SeqLen = Sequence.size();
2154     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2155     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2156     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2157             ViaIntVT == MVT::i64) &&
2158            "Unexpected sequence type");
2159 
2160     unsigned EltIdx = 0;
2161     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2162     uint64_t SplatValue = 0;
2163     // Construct the amalgamated value which can be splatted as this larger
2164     // vector type.
2165     for (const auto &SeqV : Sequence) {
2166       if (!SeqV.isUndef())
2167         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2168                        << (EltIdx * EltBitSize));
2169       EltIdx++;
2170     }
2171 
2172     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2173     // achieve better constant materializion.
2174     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2175       SplatValue = SignExtend64(SplatValue, 32);
2176 
2177     // Since we can't introduce illegal i64 types at this stage, we can only
2178     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2179     // way we can use RVV instructions to splat.
2180     assert((ViaIntVT.bitsLE(XLenVT) ||
2181             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2182            "Unexpected bitcast sequence");
2183     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2184       SDValue ViaVL =
2185           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2186       MVT ViaContainerVT =
2187           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2188       SDValue Splat =
2189           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2190                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2191       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2192       return DAG.getBitcast(VT, Splat);
2193     }
2194   }
2195 
2196   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2197   // which constitute a large proportion of the elements. In such cases we can
2198   // splat a vector with the dominant element and make up the shortfall with
2199   // INSERT_VECTOR_ELTs.
2200   // Note that this includes vectors of 2 elements by association. The
2201   // upper-most element is the "dominant" one, allowing us to use a splat to
2202   // "insert" the upper element, and an insert of the lower element at position
2203   // 0, which improves codegen.
2204   SDValue DominantValue;
2205   unsigned MostCommonCount = 0;
2206   DenseMap<SDValue, unsigned> ValueCounts;
2207   unsigned NumUndefElts =
2208       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2209 
2210   // Track the number of scalar loads we know we'd be inserting, estimated as
2211   // any non-zero floating-point constant. Other kinds of element are either
2212   // already in registers or are materialized on demand. The threshold at which
2213   // a vector load is more desirable than several scalar materializion and
2214   // vector-insertion instructions is not known.
2215   unsigned NumScalarLoads = 0;
2216 
2217   for (SDValue V : Op->op_values()) {
2218     if (V.isUndef())
2219       continue;
2220 
2221     ValueCounts.insert(std::make_pair(V, 0));
2222     unsigned &Count = ValueCounts[V];
2223 
2224     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2225       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2226 
2227     // Is this value dominant? In case of a tie, prefer the highest element as
2228     // it's cheaper to insert near the beginning of a vector than it is at the
2229     // end.
2230     if (++Count >= MostCommonCount) {
2231       DominantValue = V;
2232       MostCommonCount = Count;
2233     }
2234   }
2235 
2236   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2237   unsigned NumDefElts = NumElts - NumUndefElts;
2238   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2239 
2240   // Don't perform this optimization when optimizing for size, since
2241   // materializing elements and inserting them tends to cause code bloat.
2242   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2243       ((MostCommonCount > DominantValueCountThreshold) ||
2244        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2245     // Start by splatting the most common element.
2246     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2247 
2248     DenseSet<SDValue> Processed{DominantValue};
2249     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2250     for (const auto &OpIdx : enumerate(Op->ops())) {
2251       const SDValue &V = OpIdx.value();
2252       if (V.isUndef() || !Processed.insert(V).second)
2253         continue;
2254       if (ValueCounts[V] == 1) {
2255         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2256                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2257       } else {
2258         // Blend in all instances of this value using a VSELECT, using a
2259         // mask where each bit signals whether that element is the one
2260         // we're after.
2261         SmallVector<SDValue> Ops;
2262         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2263           return DAG.getConstant(V == V1, DL, XLenVT);
2264         });
2265         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2266                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2267                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2268       }
2269     }
2270 
2271     return Vec;
2272   }
2273 
2274   return SDValue();
2275 }
2276 
2277 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2278                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2279   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2280     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2281     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2282     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2283     // node in order to try and match RVV vector/scalar instructions.
2284     if ((LoC >> 31) == HiC)
2285       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2286 
2287     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2288     // vmv.v.x whose EEW = 32 to lower it.
2289     auto *Const = dyn_cast<ConstantSDNode>(VL);
2290     if (LoC == HiC && Const && Const->isAllOnesValue() &&
2291         Const->getOpcode() != ISD::TargetConstant) {
2292       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2293       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2294       // access the subtarget here now.
2295       auto InterVec = DAG.getNode(
2296           RISCVISD::VMV_V_X_VL, DL, InterVT, Lo,
2297           DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32));
2298       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2299     }
2300   }
2301 
2302   // Fall back to a stack store and stride x0 vector load.
2303   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2304 }
2305 
2306 // Called by type legalization to handle splat of i64 on RV32.
2307 // FIXME: We can optimize this when the type has sign or zero bits in one
2308 // of the halves.
2309 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2310                                    SDValue VL, SelectionDAG &DAG) {
2311   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2312   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2313                            DAG.getConstant(0, DL, MVT::i32));
2314   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2315                            DAG.getConstant(1, DL, MVT::i32));
2316   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2317 }
2318 
2319 // This function lowers a splat of a scalar operand Splat with the vector
2320 // length VL. It ensures the final sequence is type legal, which is useful when
2321 // lowering a splat after type legalization.
2322 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2323                                 SelectionDAG &DAG,
2324                                 const RISCVSubtarget &Subtarget) {
2325   if (VT.isFloatingPoint()) {
2326     // If VL is 1, we could use vfmv.s.f.
2327     if (isOneConstant(VL))
2328       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2329                          Scalar, VL);
2330     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2331   }
2332 
2333   MVT XLenVT = Subtarget.getXLenVT();
2334 
2335   // Simplest case is that the operand needs to be promoted to XLenVT.
2336   if (Scalar.getValueType().bitsLE(XLenVT)) {
2337     // If the operand is a constant, sign extend to increase our chances
2338     // of being able to use a .vi instruction. ANY_EXTEND would become a
2339     // a zero extend and the simm5 check in isel would fail.
2340     // FIXME: Should we ignore the upper bits in isel instead?
2341     unsigned ExtOpc =
2342         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2343     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2344     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2345     // If VL is 1 and the scalar value won't benefit from immediate, we could
2346     // use vmv.s.x.
2347     if (isOneConstant(VL) &&
2348         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2349       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2350                          VL);
2351     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2352   }
2353 
2354   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2355          "Unexpected scalar for splat lowering!");
2356 
2357   if (isOneConstant(VL) && isNullConstant(Scalar))
2358     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2359                        DAG.getConstant(0, DL, XLenVT), VL);
2360 
2361   // Otherwise use the more complicated splatting algorithm.
2362   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2363 }
2364 
2365 // Is the mask a slidedown that shifts in undefs.
2366 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2367   int Size = Mask.size();
2368 
2369   // Elements shifted in should be undef.
2370   auto CheckUndefs = [&](int Shift) {
2371     for (int i = Size - Shift; i != Size; ++i)
2372       if (Mask[i] >= 0)
2373         return false;
2374     return true;
2375   };
2376 
2377   // Elements should be shifted or undef.
2378   auto MatchShift = [&](int Shift) {
2379     for (int i = 0; i != Size - Shift; ++i)
2380        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2381          return false;
2382     return true;
2383   };
2384 
2385   // Try all possible shifts.
2386   for (int Shift = 1; Shift != Size; ++Shift)
2387     if (CheckUndefs(Shift) && MatchShift(Shift))
2388       return Shift;
2389 
2390   // No match.
2391   return -1;
2392 }
2393 
2394 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2395                                 const RISCVSubtarget &Subtarget) {
2396   // We need to be able to widen elements to the next larger integer type.
2397   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2398     return false;
2399 
2400   int Size = Mask.size();
2401   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2402 
2403   int Srcs[] = {-1, -1};
2404   for (int i = 0; i != Size; ++i) {
2405     // Ignore undef elements.
2406     if (Mask[i] < 0)
2407       continue;
2408 
2409     // Is this an even or odd element.
2410     int Pol = i % 2;
2411 
2412     // Ensure we consistently use the same source for this element polarity.
2413     int Src = Mask[i] / Size;
2414     if (Srcs[Pol] < 0)
2415       Srcs[Pol] = Src;
2416     if (Srcs[Pol] != Src)
2417       return false;
2418 
2419     // Make sure the element within the source is appropriate for this element
2420     // in the destination.
2421     int Elt = Mask[i] % Size;
2422     if (Elt != i / 2)
2423       return false;
2424   }
2425 
2426   // We need to find a source for each polarity and they can't be the same.
2427   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2428     return false;
2429 
2430   // Swap the sources if the second source was in the even polarity.
2431   SwapSources = Srcs[0] > Srcs[1];
2432 
2433   return true;
2434 }
2435 
2436 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2437                                    const RISCVSubtarget &Subtarget) {
2438   SDValue V1 = Op.getOperand(0);
2439   SDValue V2 = Op.getOperand(1);
2440   SDLoc DL(Op);
2441   MVT XLenVT = Subtarget.getXLenVT();
2442   MVT VT = Op.getSimpleValueType();
2443   unsigned NumElts = VT.getVectorNumElements();
2444   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2445 
2446   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2447 
2448   SDValue TrueMask, VL;
2449   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2450 
2451   if (SVN->isSplat()) {
2452     const int Lane = SVN->getSplatIndex();
2453     if (Lane >= 0) {
2454       MVT SVT = VT.getVectorElementType();
2455 
2456       // Turn splatted vector load into a strided load with an X0 stride.
2457       SDValue V = V1;
2458       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2459       // with undef.
2460       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2461       int Offset = Lane;
2462       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2463         int OpElements =
2464             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2465         V = V.getOperand(Offset / OpElements);
2466         Offset %= OpElements;
2467       }
2468 
2469       // We need to ensure the load isn't atomic or volatile.
2470       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2471         auto *Ld = cast<LoadSDNode>(V);
2472         Offset *= SVT.getStoreSize();
2473         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2474                                                    TypeSize::Fixed(Offset), DL);
2475 
2476         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2477         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2478           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2479           SDValue IntID =
2480               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2481           SDValue Ops[] = {Ld->getChain(),
2482                            IntID,
2483                            DAG.getUNDEF(ContainerVT),
2484                            NewAddr,
2485                            DAG.getRegister(RISCV::X0, XLenVT),
2486                            VL};
2487           SDValue NewLoad = DAG.getMemIntrinsicNode(
2488               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2489               DAG.getMachineFunction().getMachineMemOperand(
2490                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2491           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2492           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2493         }
2494 
2495         // Otherwise use a scalar load and splat. This will give the best
2496         // opportunity to fold a splat into the operation. ISel can turn it into
2497         // the x0 strided load if we aren't able to fold away the select.
2498         if (SVT.isFloatingPoint())
2499           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2500                           Ld->getPointerInfo().getWithOffset(Offset),
2501                           Ld->getOriginalAlign(),
2502                           Ld->getMemOperand()->getFlags());
2503         else
2504           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2505                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2506                              Ld->getOriginalAlign(),
2507                              Ld->getMemOperand()->getFlags());
2508         DAG.makeEquivalentMemoryOrdering(Ld, V);
2509 
2510         unsigned Opc =
2511             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2512         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2513         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2514       }
2515 
2516       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2517       assert(Lane < (int)NumElts && "Unexpected lane!");
2518       SDValue Gather =
2519           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2520                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2521       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2522     }
2523   }
2524 
2525   ArrayRef<int> Mask = SVN->getMask();
2526 
2527   // Try to match as a slidedown.
2528   int SlideAmt = matchShuffleAsSlideDown(Mask);
2529   if (SlideAmt >= 0) {
2530     // TODO: Should we reduce the VL to account for the upper undef elements?
2531     // Requires additional vsetvlis, but might be faster to execute.
2532     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2533     SDValue SlideDown =
2534         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2535                     DAG.getUNDEF(ContainerVT), V1,
2536                     DAG.getConstant(SlideAmt, DL, XLenVT),
2537                     TrueMask, VL);
2538     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2539   }
2540 
2541   // Detect an interleave shuffle and lower to
2542   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2543   bool SwapSources;
2544   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2545     // Swap sources if needed.
2546     if (SwapSources)
2547       std::swap(V1, V2);
2548 
2549     // Extract the lower half of the vectors.
2550     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2551     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2552                      DAG.getConstant(0, DL, XLenVT));
2553     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2554                      DAG.getConstant(0, DL, XLenVT));
2555 
2556     // Double the element width and halve the number of elements in an int type.
2557     unsigned EltBits = VT.getScalarSizeInBits();
2558     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2559     MVT WideIntVT =
2560         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2561     // Convert this to a scalable vector. We need to base this on the
2562     // destination size to ensure there's always a type with a smaller LMUL.
2563     MVT WideIntContainerVT =
2564         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2565 
2566     // Convert sources to scalable vectors with the same element count as the
2567     // larger type.
2568     MVT HalfContainerVT = MVT::getVectorVT(
2569         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2570     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2571     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2572 
2573     // Cast sources to integer.
2574     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2575     MVT IntHalfVT =
2576         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2577     V1 = DAG.getBitcast(IntHalfVT, V1);
2578     V2 = DAG.getBitcast(IntHalfVT, V2);
2579 
2580     // Freeze V2 since we use it twice and we need to be sure that the add and
2581     // multiply see the same value.
2582     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2583 
2584     // Recreate TrueMask using the widened type's element count.
2585     MVT MaskVT =
2586         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2587     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2588 
2589     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2590     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2591                               V2, TrueMask, VL);
2592     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2593     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2594                                      DAG.getAllOnesConstant(DL, XLenVT));
2595     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2596                                    V2, Multiplier, TrueMask, VL);
2597     // Add the new copies to our previous addition giving us 2^eltbits copies of
2598     // V2. This is equivalent to shifting V2 left by eltbits. This should
2599     // combine with the vwmulu.vv above to form vwmaccu.vv.
2600     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2601                       TrueMask, VL);
2602     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2603     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2604     // vector VT.
2605     ContainerVT =
2606         MVT::getVectorVT(VT.getVectorElementType(),
2607                          WideIntContainerVT.getVectorElementCount() * 2);
2608     Add = DAG.getBitcast(ContainerVT, Add);
2609     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2610   }
2611 
2612   // Detect shuffles which can be re-expressed as vector selects; these are
2613   // shuffles in which each element in the destination is taken from an element
2614   // at the corresponding index in either source vectors.
2615   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2616     int MaskIndex = MaskIdx.value();
2617     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2618   });
2619 
2620   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2621 
2622   SmallVector<SDValue> MaskVals;
2623   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2624   // merged with a second vrgather.
2625   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2626 
2627   // By default we preserve the original operand order, and use a mask to
2628   // select LHS as true and RHS as false. However, since RVV vector selects may
2629   // feature splats but only on the LHS, we may choose to invert our mask and
2630   // instead select between RHS and LHS.
2631   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2632   bool InvertMask = IsSelect == SwapOps;
2633 
2634   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2635   // half.
2636   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2637 
2638   // Now construct the mask that will be used by the vselect or blended
2639   // vrgather operation. For vrgathers, construct the appropriate indices into
2640   // each vector.
2641   for (int MaskIndex : Mask) {
2642     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2643     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2644     if (!IsSelect) {
2645       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2646       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2647                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2648                                      : DAG.getUNDEF(XLenVT));
2649       GatherIndicesRHS.push_back(
2650           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2651                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2652       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2653         ++LHSIndexCounts[MaskIndex];
2654       if (!IsLHSOrUndefIndex)
2655         ++RHSIndexCounts[MaskIndex - NumElts];
2656     }
2657   }
2658 
2659   if (SwapOps) {
2660     std::swap(V1, V2);
2661     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2662   }
2663 
2664   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2665   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2666   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2667 
2668   if (IsSelect)
2669     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2670 
2671   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2672     // On such a large vector we're unable to use i8 as the index type.
2673     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2674     // may involve vector splitting if we're already at LMUL=8, or our
2675     // user-supplied maximum fixed-length LMUL.
2676     return SDValue();
2677   }
2678 
2679   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2680   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2681   MVT IndexVT = VT.changeTypeToInteger();
2682   // Since we can't introduce illegal index types at this stage, use i16 and
2683   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2684   // than XLenVT.
2685   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2686     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2687     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2688   }
2689 
2690   MVT IndexContainerVT =
2691       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2692 
2693   SDValue Gather;
2694   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2695   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2696   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2697     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2698   } else {
2699     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2700     // If only one index is used, we can use a "splat" vrgather.
2701     // TODO: We can splat the most-common index and fix-up any stragglers, if
2702     // that's beneficial.
2703     if (LHSIndexCounts.size() == 1) {
2704       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2705       Gather =
2706           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2707                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2708     } else {
2709       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2710       LHSIndices =
2711           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2712 
2713       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2714                            TrueMask, VL);
2715     }
2716   }
2717 
2718   // If a second vector operand is used by this shuffle, blend it in with an
2719   // additional vrgather.
2720   if (!V2.isUndef()) {
2721     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2722     // If only one index is used, we can use a "splat" vrgather.
2723     // TODO: We can splat the most-common index and fix-up any stragglers, if
2724     // that's beneficial.
2725     if (RHSIndexCounts.size() == 1) {
2726       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2727       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2728                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2729     } else {
2730       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2731       RHSIndices =
2732           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2733       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2734                        VL);
2735     }
2736 
2737     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2738     SelectMask =
2739         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2740 
2741     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2742                          Gather, VL);
2743   }
2744 
2745   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2746 }
2747 
2748 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2749                                      SDLoc DL, SelectionDAG &DAG,
2750                                      const RISCVSubtarget &Subtarget) {
2751   if (VT.isScalableVector())
2752     return DAG.getFPExtendOrRound(Op, DL, VT);
2753   assert(VT.isFixedLengthVector() &&
2754          "Unexpected value type for RVV FP extend/round lowering");
2755   SDValue Mask, VL;
2756   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2757   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2758                         ? RISCVISD::FP_EXTEND_VL
2759                         : RISCVISD::FP_ROUND_VL;
2760   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2761 }
2762 
2763 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2764 // the exponent.
2765 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2766   MVT VT = Op.getSimpleValueType();
2767   unsigned EltSize = VT.getScalarSizeInBits();
2768   SDValue Src = Op.getOperand(0);
2769   SDLoc DL(Op);
2770 
2771   // We need a FP type that can represent the value.
2772   // TODO: Use f16 for i8 when possible?
2773   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2774   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2775 
2776   // Legal types should have been checked in the RISCVTargetLowering
2777   // constructor.
2778   // TODO: Splitting may make sense in some cases.
2779   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2780          "Expected legal float type!");
2781 
2782   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2783   // The trailing zero count is equal to log2 of this single bit value.
2784   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2785     SDValue Neg =
2786         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2787     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2788   }
2789 
2790   // We have a legal FP type, convert to it.
2791   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2792   // Bitcast to integer and shift the exponent to the LSB.
2793   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2794   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2795   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2796   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2797                               DAG.getConstant(ShiftAmt, DL, IntVT));
2798   // Truncate back to original type to allow vnsrl.
2799   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2800   // The exponent contains log2 of the value in biased form.
2801   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2802 
2803   // For trailing zeros, we just need to subtract the bias.
2804   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2805     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2806                        DAG.getConstant(ExponentBias, DL, VT));
2807 
2808   // For leading zeros, we need to remove the bias and convert from log2 to
2809   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2810   unsigned Adjust = ExponentBias + (EltSize - 1);
2811   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2812 }
2813 
2814 // While RVV has alignment restrictions, we should always be able to load as a
2815 // legal equivalently-sized byte-typed vector instead. This method is
2816 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2817 // the load is already correctly-aligned, it returns SDValue().
2818 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2819                                                     SelectionDAG &DAG) const {
2820   auto *Load = cast<LoadSDNode>(Op);
2821   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2822 
2823   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2824                                      Load->getMemoryVT(),
2825                                      *Load->getMemOperand()))
2826     return SDValue();
2827 
2828   SDLoc DL(Op);
2829   MVT VT = Op.getSimpleValueType();
2830   unsigned EltSizeBits = VT.getScalarSizeInBits();
2831   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2832          "Unexpected unaligned RVV load type");
2833   MVT NewVT =
2834       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2835   assert(NewVT.isValid() &&
2836          "Expecting equally-sized RVV vector types to be legal");
2837   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2838                           Load->getPointerInfo(), Load->getOriginalAlign(),
2839                           Load->getMemOperand()->getFlags());
2840   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2841 }
2842 
2843 // While RVV has alignment restrictions, we should always be able to store as a
2844 // legal equivalently-sized byte-typed vector instead. This method is
2845 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2846 // returns SDValue() if the store is already correctly aligned.
2847 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2848                                                      SelectionDAG &DAG) const {
2849   auto *Store = cast<StoreSDNode>(Op);
2850   assert(Store && Store->getValue().getValueType().isVector() &&
2851          "Expected vector store");
2852 
2853   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2854                                      Store->getMemoryVT(),
2855                                      *Store->getMemOperand()))
2856     return SDValue();
2857 
2858   SDLoc DL(Op);
2859   SDValue StoredVal = Store->getValue();
2860   MVT VT = StoredVal.getSimpleValueType();
2861   unsigned EltSizeBits = VT.getScalarSizeInBits();
2862   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2863          "Unexpected unaligned RVV store type");
2864   MVT NewVT =
2865       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2866   assert(NewVT.isValid() &&
2867          "Expecting equally-sized RVV vector types to be legal");
2868   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2869   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2870                       Store->getPointerInfo(), Store->getOriginalAlign(),
2871                       Store->getMemOperand()->getFlags());
2872 }
2873 
2874 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2875                                             SelectionDAG &DAG) const {
2876   switch (Op.getOpcode()) {
2877   default:
2878     report_fatal_error("unimplemented operand");
2879   case ISD::GlobalAddress:
2880     return lowerGlobalAddress(Op, DAG);
2881   case ISD::BlockAddress:
2882     return lowerBlockAddress(Op, DAG);
2883   case ISD::ConstantPool:
2884     return lowerConstantPool(Op, DAG);
2885   case ISD::JumpTable:
2886     return lowerJumpTable(Op, DAG);
2887   case ISD::GlobalTLSAddress:
2888     return lowerGlobalTLSAddress(Op, DAG);
2889   case ISD::SELECT:
2890     return lowerSELECT(Op, DAG);
2891   case ISD::BRCOND:
2892     return lowerBRCOND(Op, DAG);
2893   case ISD::VASTART:
2894     return lowerVASTART(Op, DAG);
2895   case ISD::FRAMEADDR:
2896     return lowerFRAMEADDR(Op, DAG);
2897   case ISD::RETURNADDR:
2898     return lowerRETURNADDR(Op, DAG);
2899   case ISD::SHL_PARTS:
2900     return lowerShiftLeftParts(Op, DAG);
2901   case ISD::SRA_PARTS:
2902     return lowerShiftRightParts(Op, DAG, true);
2903   case ISD::SRL_PARTS:
2904     return lowerShiftRightParts(Op, DAG, false);
2905   case ISD::BITCAST: {
2906     SDLoc DL(Op);
2907     EVT VT = Op.getValueType();
2908     SDValue Op0 = Op.getOperand(0);
2909     EVT Op0VT = Op0.getValueType();
2910     MVT XLenVT = Subtarget.getXLenVT();
2911     if (VT.isFixedLengthVector()) {
2912       // We can handle fixed length vector bitcasts with a simple replacement
2913       // in isel.
2914       if (Op0VT.isFixedLengthVector())
2915         return Op;
2916       // When bitcasting from scalar to fixed-length vector, insert the scalar
2917       // into a one-element vector of the result type, and perform a vector
2918       // bitcast.
2919       if (!Op0VT.isVector()) {
2920         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2921         if (!isTypeLegal(BVT))
2922           return SDValue();
2923         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2924                                               DAG.getUNDEF(BVT), Op0,
2925                                               DAG.getConstant(0, DL, XLenVT)));
2926       }
2927       return SDValue();
2928     }
2929     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2930     // thus: bitcast the vector to a one-element vector type whose element type
2931     // is the same as the result type, and extract the first element.
2932     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2933       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2934       if (!isTypeLegal(BVT))
2935         return SDValue();
2936       SDValue BVec = DAG.getBitcast(BVT, Op0);
2937       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2938                          DAG.getConstant(0, DL, XLenVT));
2939     }
2940     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2941       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2942       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2943       return FPConv;
2944     }
2945     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2946         Subtarget.hasStdExtF()) {
2947       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2948       SDValue FPConv =
2949           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2950       return FPConv;
2951     }
2952     return SDValue();
2953   }
2954   case ISD::INTRINSIC_WO_CHAIN:
2955     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2956   case ISD::INTRINSIC_W_CHAIN:
2957     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2958   case ISD::INTRINSIC_VOID:
2959     return LowerINTRINSIC_VOID(Op, DAG);
2960   case ISD::BSWAP:
2961   case ISD::BITREVERSE: {
2962     MVT VT = Op.getSimpleValueType();
2963     SDLoc DL(Op);
2964     if (Subtarget.hasStdExtZbp()) {
2965       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2966       // Start with the maximum immediate value which is the bitwidth - 1.
2967       unsigned Imm = VT.getSizeInBits() - 1;
2968       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2969       if (Op.getOpcode() == ISD::BSWAP)
2970         Imm &= ~0x7U;
2971       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2972                          DAG.getConstant(Imm, DL, VT));
2973     }
2974     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
2975     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
2976     // Expand bitreverse to a bswap(rev8) followed by brev8.
2977     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
2978     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
2979     // as brev8 by an isel pattern.
2980     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
2981                        DAG.getConstant(7, DL, VT));
2982   }
2983   case ISD::FSHL:
2984   case ISD::FSHR: {
2985     MVT VT = Op.getSimpleValueType();
2986     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2987     SDLoc DL(Op);
2988     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2989     // use log(XLen) bits. Mask the shift amount accordingly to prevent
2990     // accidentally setting the extra bit.
2991     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2992     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2993                                 DAG.getConstant(ShAmtWidth, DL, VT));
2994     // fshl and fshr concatenate their operands in the same order. fsr and fsl
2995     // instruction use different orders. fshl will return its first operand for
2996     // shift of zero, fshr will return its second operand. fsl and fsr both
2997     // return rs1 so the ISD nodes need to have different operand orders.
2998     // Shift amount is in rs2.
2999     SDValue Op0 = Op.getOperand(0);
3000     SDValue Op1 = Op.getOperand(1);
3001     unsigned Opc = RISCVISD::FSL;
3002     if (Op.getOpcode() == ISD::FSHR) {
3003       std::swap(Op0, Op1);
3004       Opc = RISCVISD::FSR;
3005     }
3006     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3007   }
3008   case ISD::TRUNCATE: {
3009     SDLoc DL(Op);
3010     MVT VT = Op.getSimpleValueType();
3011     // Only custom-lower vector truncates
3012     if (!VT.isVector())
3013       return Op;
3014 
3015     // Truncates to mask types are handled differently
3016     if (VT.getVectorElementType() == MVT::i1)
3017       return lowerVectorMaskTrunc(Op, DAG);
3018 
3019     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3020     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3021     // truncate by one power of two at a time.
3022     MVT DstEltVT = VT.getVectorElementType();
3023 
3024     SDValue Src = Op.getOperand(0);
3025     MVT SrcVT = Src.getSimpleValueType();
3026     MVT SrcEltVT = SrcVT.getVectorElementType();
3027 
3028     assert(DstEltVT.bitsLT(SrcEltVT) &&
3029            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3030            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3031            "Unexpected vector truncate lowering");
3032 
3033     MVT ContainerVT = SrcVT;
3034     if (SrcVT.isFixedLengthVector()) {
3035       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3036       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3037     }
3038 
3039     SDValue Result = Src;
3040     SDValue Mask, VL;
3041     std::tie(Mask, VL) =
3042         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3043     LLVMContext &Context = *DAG.getContext();
3044     const ElementCount Count = ContainerVT.getVectorElementCount();
3045     do {
3046       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3047       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3048       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3049                            Mask, VL);
3050     } while (SrcEltVT != DstEltVT);
3051 
3052     if (SrcVT.isFixedLengthVector())
3053       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3054 
3055     return Result;
3056   }
3057   case ISD::ANY_EXTEND:
3058   case ISD::ZERO_EXTEND:
3059     if (Op.getOperand(0).getValueType().isVector() &&
3060         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3061       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3062     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3063   case ISD::SIGN_EXTEND:
3064     if (Op.getOperand(0).getValueType().isVector() &&
3065         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3066       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3067     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3068   case ISD::SPLAT_VECTOR_PARTS:
3069     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3070   case ISD::INSERT_VECTOR_ELT:
3071     return lowerINSERT_VECTOR_ELT(Op, DAG);
3072   case ISD::EXTRACT_VECTOR_ELT:
3073     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3074   case ISD::VSCALE: {
3075     MVT VT = Op.getSimpleValueType();
3076     SDLoc DL(Op);
3077     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3078     // We define our scalable vector types for lmul=1 to use a 64 bit known
3079     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3080     // vscale as VLENB / 8.
3081     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3082     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3083       report_fatal_error("Support for VLEN==32 is incomplete.");
3084     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3085       // We assume VLENB is a multiple of 8. We manually choose the best shift
3086       // here because SimplifyDemandedBits isn't always able to simplify it.
3087       uint64_t Val = Op.getConstantOperandVal(0);
3088       if (isPowerOf2_64(Val)) {
3089         uint64_t Log2 = Log2_64(Val);
3090         if (Log2 < 3)
3091           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3092                              DAG.getConstant(3 - Log2, DL, VT));
3093         if (Log2 > 3)
3094           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3095                              DAG.getConstant(Log2 - 3, DL, VT));
3096         return VLENB;
3097       }
3098       // If the multiplier is a multiple of 8, scale it down to avoid needing
3099       // to shift the VLENB value.
3100       if ((Val % 8) == 0)
3101         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3102                            DAG.getConstant(Val / 8, DL, VT));
3103     }
3104 
3105     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3106                                  DAG.getConstant(3, DL, VT));
3107     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3108   }
3109   case ISD::FPOWI: {
3110     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3111     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3112     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3113         Op.getOperand(1).getValueType() == MVT::i32) {
3114       SDLoc DL(Op);
3115       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3116       SDValue Powi =
3117           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3118       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3119                          DAG.getIntPtrConstant(0, DL));
3120     }
3121     return SDValue();
3122   }
3123   case ISD::FP_EXTEND: {
3124     // RVV can only do fp_extend to types double the size as the source. We
3125     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3126     // via f32.
3127     SDLoc DL(Op);
3128     MVT VT = Op.getSimpleValueType();
3129     SDValue Src = Op.getOperand(0);
3130     MVT SrcVT = Src.getSimpleValueType();
3131 
3132     // Prepare any fixed-length vector operands.
3133     MVT ContainerVT = VT;
3134     if (SrcVT.isFixedLengthVector()) {
3135       ContainerVT = getContainerForFixedLengthVector(VT);
3136       MVT SrcContainerVT =
3137           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3138       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3139     }
3140 
3141     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3142         SrcVT.getVectorElementType() != MVT::f16) {
3143       // For scalable vectors, we only need to close the gap between
3144       // vXf16->vXf64.
3145       if (!VT.isFixedLengthVector())
3146         return Op;
3147       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3148       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3149       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3150     }
3151 
3152     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3153     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3154     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3155         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3156 
3157     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3158                                            DL, DAG, Subtarget);
3159     if (VT.isFixedLengthVector())
3160       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3161     return Extend;
3162   }
3163   case ISD::FP_ROUND: {
3164     // RVV can only do fp_round to types half the size as the source. We
3165     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3166     // conversion instruction.
3167     SDLoc DL(Op);
3168     MVT VT = Op.getSimpleValueType();
3169     SDValue Src = Op.getOperand(0);
3170     MVT SrcVT = Src.getSimpleValueType();
3171 
3172     // Prepare any fixed-length vector operands.
3173     MVT ContainerVT = VT;
3174     if (VT.isFixedLengthVector()) {
3175       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3176       ContainerVT =
3177           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3178       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3179     }
3180 
3181     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3182         SrcVT.getVectorElementType() != MVT::f64) {
3183       // For scalable vectors, we only need to close the gap between
3184       // vXf64<->vXf16.
3185       if (!VT.isFixedLengthVector())
3186         return Op;
3187       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3188       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3189       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3190     }
3191 
3192     SDValue Mask, VL;
3193     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3194 
3195     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3196     SDValue IntermediateRound =
3197         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3198     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3199                                           DL, DAG, Subtarget);
3200 
3201     if (VT.isFixedLengthVector())
3202       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3203     return Round;
3204   }
3205   case ISD::FP_TO_SINT:
3206   case ISD::FP_TO_UINT:
3207   case ISD::SINT_TO_FP:
3208   case ISD::UINT_TO_FP: {
3209     // RVV can only do fp<->int conversions to types half/double the size as
3210     // the source. We custom-lower any conversions that do two hops into
3211     // sequences.
3212     MVT VT = Op.getSimpleValueType();
3213     if (!VT.isVector())
3214       return Op;
3215     SDLoc DL(Op);
3216     SDValue Src = Op.getOperand(0);
3217     MVT EltVT = VT.getVectorElementType();
3218     MVT SrcVT = Src.getSimpleValueType();
3219     MVT SrcEltVT = SrcVT.getVectorElementType();
3220     unsigned EltSize = EltVT.getSizeInBits();
3221     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3222     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3223            "Unexpected vector element types");
3224 
3225     bool IsInt2FP = SrcEltVT.isInteger();
3226     // Widening conversions
3227     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3228       if (IsInt2FP) {
3229         // Do a regular integer sign/zero extension then convert to float.
3230         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3231                                       VT.getVectorElementCount());
3232         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3233                                  ? ISD::ZERO_EXTEND
3234                                  : ISD::SIGN_EXTEND;
3235         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3236         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3237       }
3238       // FP2Int
3239       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3240       // Do one doubling fp_extend then complete the operation by converting
3241       // to int.
3242       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3243       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3244       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3245     }
3246 
3247     // Narrowing conversions
3248     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3249       if (IsInt2FP) {
3250         // One narrowing int_to_fp, then an fp_round.
3251         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3252         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3253         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3254         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3255       }
3256       // FP2Int
3257       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3258       // representable by the integer, the result is poison.
3259       MVT IVecVT =
3260           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3261                            VT.getVectorElementCount());
3262       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3263       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3264     }
3265 
3266     // Scalable vectors can exit here. Patterns will handle equally-sized
3267     // conversions halving/doubling ones.
3268     if (!VT.isFixedLengthVector())
3269       return Op;
3270 
3271     // For fixed-length vectors we lower to a custom "VL" node.
3272     unsigned RVVOpc = 0;
3273     switch (Op.getOpcode()) {
3274     default:
3275       llvm_unreachable("Impossible opcode");
3276     case ISD::FP_TO_SINT:
3277       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3278       break;
3279     case ISD::FP_TO_UINT:
3280       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3281       break;
3282     case ISD::SINT_TO_FP:
3283       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3284       break;
3285     case ISD::UINT_TO_FP:
3286       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3287       break;
3288     }
3289 
3290     MVT ContainerVT, SrcContainerVT;
3291     // Derive the reference container type from the larger vector type.
3292     if (SrcEltSize > EltSize) {
3293       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3294       ContainerVT =
3295           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3296     } else {
3297       ContainerVT = getContainerForFixedLengthVector(VT);
3298       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3299     }
3300 
3301     SDValue Mask, VL;
3302     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3303 
3304     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3305     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3306     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3307   }
3308   case ISD::FP_TO_SINT_SAT:
3309   case ISD::FP_TO_UINT_SAT:
3310     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3311   case ISD::FTRUNC:
3312   case ISD::FCEIL:
3313   case ISD::FFLOOR:
3314     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3315   case ISD::VECREDUCE_ADD:
3316   case ISD::VECREDUCE_UMAX:
3317   case ISD::VECREDUCE_SMAX:
3318   case ISD::VECREDUCE_UMIN:
3319   case ISD::VECREDUCE_SMIN:
3320     return lowerVECREDUCE(Op, DAG);
3321   case ISD::VECREDUCE_AND:
3322   case ISD::VECREDUCE_OR:
3323   case ISD::VECREDUCE_XOR:
3324     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3325       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3326     return lowerVECREDUCE(Op, DAG);
3327   case ISD::VECREDUCE_FADD:
3328   case ISD::VECREDUCE_SEQ_FADD:
3329   case ISD::VECREDUCE_FMIN:
3330   case ISD::VECREDUCE_FMAX:
3331     return lowerFPVECREDUCE(Op, DAG);
3332   case ISD::VP_REDUCE_ADD:
3333   case ISD::VP_REDUCE_UMAX:
3334   case ISD::VP_REDUCE_SMAX:
3335   case ISD::VP_REDUCE_UMIN:
3336   case ISD::VP_REDUCE_SMIN:
3337   case ISD::VP_REDUCE_FADD:
3338   case ISD::VP_REDUCE_SEQ_FADD:
3339   case ISD::VP_REDUCE_FMIN:
3340   case ISD::VP_REDUCE_FMAX:
3341     return lowerVPREDUCE(Op, DAG);
3342   case ISD::VP_REDUCE_AND:
3343   case ISD::VP_REDUCE_OR:
3344   case ISD::VP_REDUCE_XOR:
3345     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3346       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3347     return lowerVPREDUCE(Op, DAG);
3348   case ISD::INSERT_SUBVECTOR:
3349     return lowerINSERT_SUBVECTOR(Op, DAG);
3350   case ISD::EXTRACT_SUBVECTOR:
3351     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3352   case ISD::STEP_VECTOR:
3353     return lowerSTEP_VECTOR(Op, DAG);
3354   case ISD::VECTOR_REVERSE:
3355     return lowerVECTOR_REVERSE(Op, DAG);
3356   case ISD::BUILD_VECTOR:
3357     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3358   case ISD::SPLAT_VECTOR:
3359     if (Op.getValueType().getVectorElementType() == MVT::i1)
3360       return lowerVectorMaskSplat(Op, DAG);
3361     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3362   case ISD::VECTOR_SHUFFLE:
3363     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3364   case ISD::CONCAT_VECTORS: {
3365     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3366     // better than going through the stack, as the default expansion does.
3367     SDLoc DL(Op);
3368     MVT VT = Op.getSimpleValueType();
3369     unsigned NumOpElts =
3370         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3371     SDValue Vec = DAG.getUNDEF(VT);
3372     for (const auto &OpIdx : enumerate(Op->ops())) {
3373       SDValue SubVec = OpIdx.value();
3374       // Don't insert undef subvectors.
3375       if (SubVec.isUndef())
3376         continue;
3377       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3378                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3379     }
3380     return Vec;
3381   }
3382   case ISD::LOAD:
3383     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3384       return V;
3385     if (Op.getValueType().isFixedLengthVector())
3386       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3387     return Op;
3388   case ISD::STORE:
3389     if (auto V = expandUnalignedRVVStore(Op, DAG))
3390       return V;
3391     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3392       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3393     return Op;
3394   case ISD::MLOAD:
3395   case ISD::VP_LOAD:
3396     return lowerMaskedLoad(Op, DAG);
3397   case ISD::MSTORE:
3398   case ISD::VP_STORE:
3399     return lowerMaskedStore(Op, DAG);
3400   case ISD::SETCC:
3401     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3402   case ISD::ADD:
3403     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3404   case ISD::SUB:
3405     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3406   case ISD::MUL:
3407     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3408   case ISD::MULHS:
3409     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3410   case ISD::MULHU:
3411     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3412   case ISD::AND:
3413     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3414                                               RISCVISD::AND_VL);
3415   case ISD::OR:
3416     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3417                                               RISCVISD::OR_VL);
3418   case ISD::XOR:
3419     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3420                                               RISCVISD::XOR_VL);
3421   case ISD::SDIV:
3422     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3423   case ISD::SREM:
3424     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3425   case ISD::UDIV:
3426     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3427   case ISD::UREM:
3428     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3429   case ISD::SHL:
3430   case ISD::SRA:
3431   case ISD::SRL:
3432     if (Op.getSimpleValueType().isFixedLengthVector())
3433       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3434     // This can be called for an i32 shift amount that needs to be promoted.
3435     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3436            "Unexpected custom legalisation");
3437     return SDValue();
3438   case ISD::SADDSAT:
3439     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3440   case ISD::UADDSAT:
3441     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3442   case ISD::SSUBSAT:
3443     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3444   case ISD::USUBSAT:
3445     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3446   case ISD::FADD:
3447     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3448   case ISD::FSUB:
3449     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3450   case ISD::FMUL:
3451     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3452   case ISD::FDIV:
3453     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3454   case ISD::FNEG:
3455     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3456   case ISD::FABS:
3457     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3458   case ISD::FSQRT:
3459     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3460   case ISD::FMA:
3461     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3462   case ISD::SMIN:
3463     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3464   case ISD::SMAX:
3465     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3466   case ISD::UMIN:
3467     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3468   case ISD::UMAX:
3469     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3470   case ISD::FMINNUM:
3471     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3472   case ISD::FMAXNUM:
3473     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3474   case ISD::ABS:
3475     return lowerABS(Op, DAG);
3476   case ISD::CTLZ_ZERO_UNDEF:
3477   case ISD::CTTZ_ZERO_UNDEF:
3478     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3479   case ISD::VSELECT:
3480     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3481   case ISD::FCOPYSIGN:
3482     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3483   case ISD::MGATHER:
3484   case ISD::VP_GATHER:
3485     return lowerMaskedGather(Op, DAG);
3486   case ISD::MSCATTER:
3487   case ISD::VP_SCATTER:
3488     return lowerMaskedScatter(Op, DAG);
3489   case ISD::FLT_ROUNDS_:
3490     return lowerGET_ROUNDING(Op, DAG);
3491   case ISD::SET_ROUNDING:
3492     return lowerSET_ROUNDING(Op, DAG);
3493   case ISD::VP_SELECT:
3494     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3495   case ISD::VP_MERGE:
3496     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3497   case ISD::VP_ADD:
3498     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3499   case ISD::VP_SUB:
3500     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3501   case ISD::VP_MUL:
3502     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3503   case ISD::VP_SDIV:
3504     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3505   case ISD::VP_UDIV:
3506     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3507   case ISD::VP_SREM:
3508     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3509   case ISD::VP_UREM:
3510     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3511   case ISD::VP_AND:
3512     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3513   case ISD::VP_OR:
3514     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3515   case ISD::VP_XOR:
3516     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3517   case ISD::VP_ASHR:
3518     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3519   case ISD::VP_LSHR:
3520     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3521   case ISD::VP_SHL:
3522     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3523   case ISD::VP_FADD:
3524     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3525   case ISD::VP_FSUB:
3526     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3527   case ISD::VP_FMUL:
3528     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3529   case ISD::VP_FDIV:
3530     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3531   }
3532 }
3533 
3534 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3535                              SelectionDAG &DAG, unsigned Flags) {
3536   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3537 }
3538 
3539 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3540                              SelectionDAG &DAG, unsigned Flags) {
3541   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3542                                    Flags);
3543 }
3544 
3545 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3546                              SelectionDAG &DAG, unsigned Flags) {
3547   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3548                                    N->getOffset(), Flags);
3549 }
3550 
3551 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3552                              SelectionDAG &DAG, unsigned Flags) {
3553   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3554 }
3555 
3556 template <class NodeTy>
3557 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3558                                      bool IsLocal) const {
3559   SDLoc DL(N);
3560   EVT Ty = getPointerTy(DAG.getDataLayout());
3561 
3562   if (isPositionIndependent()) {
3563     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3564     if (IsLocal)
3565       // Use PC-relative addressing to access the symbol. This generates the
3566       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3567       // %pcrel_lo(auipc)).
3568       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3569 
3570     // Use PC-relative addressing to access the GOT for this symbol, then load
3571     // the address from the GOT. This generates the pattern (PseudoLA sym),
3572     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3573     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3574   }
3575 
3576   switch (getTargetMachine().getCodeModel()) {
3577   default:
3578     report_fatal_error("Unsupported code model for lowering");
3579   case CodeModel::Small: {
3580     // Generate a sequence for accessing addresses within the first 2 GiB of
3581     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3582     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3583     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3584     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3585     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3586   }
3587   case CodeModel::Medium: {
3588     // Generate a sequence for accessing addresses within any 2GiB range within
3589     // the address space. This generates the pattern (PseudoLLA sym), which
3590     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3591     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3592     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3593   }
3594   }
3595 }
3596 
3597 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3598                                                 SelectionDAG &DAG) const {
3599   SDLoc DL(Op);
3600   EVT Ty = Op.getValueType();
3601   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3602   int64_t Offset = N->getOffset();
3603   MVT XLenVT = Subtarget.getXLenVT();
3604 
3605   const GlobalValue *GV = N->getGlobal();
3606   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3607   SDValue Addr = getAddr(N, DAG, IsLocal);
3608 
3609   // In order to maximise the opportunity for common subexpression elimination,
3610   // emit a separate ADD node for the global address offset instead of folding
3611   // it in the global address node. Later peephole optimisations may choose to
3612   // fold it back in when profitable.
3613   if (Offset != 0)
3614     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3615                        DAG.getConstant(Offset, DL, XLenVT));
3616   return Addr;
3617 }
3618 
3619 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3620                                                SelectionDAG &DAG) const {
3621   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3622 
3623   return getAddr(N, DAG);
3624 }
3625 
3626 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3627                                                SelectionDAG &DAG) const {
3628   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3629 
3630   return getAddr(N, DAG);
3631 }
3632 
3633 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3634                                             SelectionDAG &DAG) const {
3635   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3636 
3637   return getAddr(N, DAG);
3638 }
3639 
3640 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3641                                               SelectionDAG &DAG,
3642                                               bool UseGOT) const {
3643   SDLoc DL(N);
3644   EVT Ty = getPointerTy(DAG.getDataLayout());
3645   const GlobalValue *GV = N->getGlobal();
3646   MVT XLenVT = Subtarget.getXLenVT();
3647 
3648   if (UseGOT) {
3649     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3650     // load the address from the GOT and add the thread pointer. This generates
3651     // the pattern (PseudoLA_TLS_IE sym), which expands to
3652     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3653     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3654     SDValue Load =
3655         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3656 
3657     // Add the thread pointer.
3658     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3659     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3660   }
3661 
3662   // Generate a sequence for accessing the address relative to the thread
3663   // pointer, with the appropriate adjustment for the thread pointer offset.
3664   // This generates the pattern
3665   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3666   SDValue AddrHi =
3667       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3668   SDValue AddrAdd =
3669       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3670   SDValue AddrLo =
3671       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3672 
3673   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3674   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3675   SDValue MNAdd = SDValue(
3676       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3677       0);
3678   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3679 }
3680 
3681 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3682                                                SelectionDAG &DAG) const {
3683   SDLoc DL(N);
3684   EVT Ty = getPointerTy(DAG.getDataLayout());
3685   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3686   const GlobalValue *GV = N->getGlobal();
3687 
3688   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3689   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3690   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3691   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3692   SDValue Load =
3693       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3694 
3695   // Prepare argument list to generate call.
3696   ArgListTy Args;
3697   ArgListEntry Entry;
3698   Entry.Node = Load;
3699   Entry.Ty = CallTy;
3700   Args.push_back(Entry);
3701 
3702   // Setup call to __tls_get_addr.
3703   TargetLowering::CallLoweringInfo CLI(DAG);
3704   CLI.setDebugLoc(DL)
3705       .setChain(DAG.getEntryNode())
3706       .setLibCallee(CallingConv::C, CallTy,
3707                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3708                     std::move(Args));
3709 
3710   return LowerCallTo(CLI).first;
3711 }
3712 
3713 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3714                                                    SelectionDAG &DAG) const {
3715   SDLoc DL(Op);
3716   EVT Ty = Op.getValueType();
3717   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3718   int64_t Offset = N->getOffset();
3719   MVT XLenVT = Subtarget.getXLenVT();
3720 
3721   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3722 
3723   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3724       CallingConv::GHC)
3725     report_fatal_error("In GHC calling convention TLS is not supported");
3726 
3727   SDValue Addr;
3728   switch (Model) {
3729   case TLSModel::LocalExec:
3730     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3731     break;
3732   case TLSModel::InitialExec:
3733     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3734     break;
3735   case TLSModel::LocalDynamic:
3736   case TLSModel::GeneralDynamic:
3737     Addr = getDynamicTLSAddr(N, DAG);
3738     break;
3739   }
3740 
3741   // In order to maximise the opportunity for common subexpression elimination,
3742   // emit a separate ADD node for the global address offset instead of folding
3743   // it in the global address node. Later peephole optimisations may choose to
3744   // fold it back in when profitable.
3745   if (Offset != 0)
3746     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3747                        DAG.getConstant(Offset, DL, XLenVT));
3748   return Addr;
3749 }
3750 
3751 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3752   SDValue CondV = Op.getOperand(0);
3753   SDValue TrueV = Op.getOperand(1);
3754   SDValue FalseV = Op.getOperand(2);
3755   SDLoc DL(Op);
3756   MVT VT = Op.getSimpleValueType();
3757   MVT XLenVT = Subtarget.getXLenVT();
3758 
3759   // Lower vector SELECTs to VSELECTs by splatting the condition.
3760   if (VT.isVector()) {
3761     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3762     SDValue CondSplat = VT.isScalableVector()
3763                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3764                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3765     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3766   }
3767 
3768   // If the result type is XLenVT and CondV is the output of a SETCC node
3769   // which also operated on XLenVT inputs, then merge the SETCC node into the
3770   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3771   // compare+branch instructions. i.e.:
3772   // (select (setcc lhs, rhs, cc), truev, falsev)
3773   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3774   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3775       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3776     SDValue LHS = CondV.getOperand(0);
3777     SDValue RHS = CondV.getOperand(1);
3778     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3779     ISD::CondCode CCVal = CC->get();
3780 
3781     // Special case for a select of 2 constants that have a diffence of 1.
3782     // Normally this is done by DAGCombine, but if the select is introduced by
3783     // type legalization or op legalization, we miss it. Restricting to SETLT
3784     // case for now because that is what signed saturating add/sub need.
3785     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3786     // but we would probably want to swap the true/false values if the condition
3787     // is SETGE/SETLE to avoid an XORI.
3788     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3789         CCVal == ISD::SETLT) {
3790       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3791       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3792       if (TrueVal - 1 == FalseVal)
3793         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3794       if (TrueVal + 1 == FalseVal)
3795         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3796     }
3797 
3798     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3799 
3800     SDValue TargetCC = DAG.getCondCode(CCVal);
3801     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3802     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3803   }
3804 
3805   // Otherwise:
3806   // (select condv, truev, falsev)
3807   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3808   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3809   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3810 
3811   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3812 
3813   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3814 }
3815 
3816 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3817   SDValue CondV = Op.getOperand(1);
3818   SDLoc DL(Op);
3819   MVT XLenVT = Subtarget.getXLenVT();
3820 
3821   if (CondV.getOpcode() == ISD::SETCC &&
3822       CondV.getOperand(0).getValueType() == XLenVT) {
3823     SDValue LHS = CondV.getOperand(0);
3824     SDValue RHS = CondV.getOperand(1);
3825     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3826 
3827     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3828 
3829     SDValue TargetCC = DAG.getCondCode(CCVal);
3830     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3831                        LHS, RHS, TargetCC, Op.getOperand(2));
3832   }
3833 
3834   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3835                      CondV, DAG.getConstant(0, DL, XLenVT),
3836                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3837 }
3838 
3839 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3840   MachineFunction &MF = DAG.getMachineFunction();
3841   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3842 
3843   SDLoc DL(Op);
3844   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3845                                  getPointerTy(MF.getDataLayout()));
3846 
3847   // vastart just stores the address of the VarArgsFrameIndex slot into the
3848   // memory location argument.
3849   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3850   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3851                       MachinePointerInfo(SV));
3852 }
3853 
3854 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3855                                             SelectionDAG &DAG) const {
3856   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3857   MachineFunction &MF = DAG.getMachineFunction();
3858   MachineFrameInfo &MFI = MF.getFrameInfo();
3859   MFI.setFrameAddressIsTaken(true);
3860   Register FrameReg = RI.getFrameRegister(MF);
3861   int XLenInBytes = Subtarget.getXLen() / 8;
3862 
3863   EVT VT = Op.getValueType();
3864   SDLoc DL(Op);
3865   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3866   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3867   while (Depth--) {
3868     int Offset = -(XLenInBytes * 2);
3869     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3870                               DAG.getIntPtrConstant(Offset, DL));
3871     FrameAddr =
3872         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3873   }
3874   return FrameAddr;
3875 }
3876 
3877 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3878                                              SelectionDAG &DAG) const {
3879   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3880   MachineFunction &MF = DAG.getMachineFunction();
3881   MachineFrameInfo &MFI = MF.getFrameInfo();
3882   MFI.setReturnAddressIsTaken(true);
3883   MVT XLenVT = Subtarget.getXLenVT();
3884   int XLenInBytes = Subtarget.getXLen() / 8;
3885 
3886   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3887     return SDValue();
3888 
3889   EVT VT = Op.getValueType();
3890   SDLoc DL(Op);
3891   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3892   if (Depth) {
3893     int Off = -XLenInBytes;
3894     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3895     SDValue Offset = DAG.getConstant(Off, DL, VT);
3896     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3897                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3898                        MachinePointerInfo());
3899   }
3900 
3901   // Return the value of the return address register, marking it an implicit
3902   // live-in.
3903   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3904   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3905 }
3906 
3907 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3908                                                  SelectionDAG &DAG) const {
3909   SDLoc DL(Op);
3910   SDValue Lo = Op.getOperand(0);
3911   SDValue Hi = Op.getOperand(1);
3912   SDValue Shamt = Op.getOperand(2);
3913   EVT VT = Lo.getValueType();
3914 
3915   // if Shamt-XLEN < 0: // Shamt < XLEN
3916   //   Lo = Lo << Shamt
3917   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3918   // else:
3919   //   Lo = 0
3920   //   Hi = Lo << (Shamt-XLEN)
3921 
3922   SDValue Zero = DAG.getConstant(0, DL, VT);
3923   SDValue One = DAG.getConstant(1, DL, VT);
3924   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3925   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3926   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3927   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3928 
3929   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3930   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3931   SDValue ShiftRightLo =
3932       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3933   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3934   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3935   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3936 
3937   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3938 
3939   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3940   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3941 
3942   SDValue Parts[2] = {Lo, Hi};
3943   return DAG.getMergeValues(Parts, DL);
3944 }
3945 
3946 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3947                                                   bool IsSRA) const {
3948   SDLoc DL(Op);
3949   SDValue Lo = Op.getOperand(0);
3950   SDValue Hi = Op.getOperand(1);
3951   SDValue Shamt = Op.getOperand(2);
3952   EVT VT = Lo.getValueType();
3953 
3954   // SRA expansion:
3955   //   if Shamt-XLEN < 0: // Shamt < XLEN
3956   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3957   //     Hi = Hi >>s Shamt
3958   //   else:
3959   //     Lo = Hi >>s (Shamt-XLEN);
3960   //     Hi = Hi >>s (XLEN-1)
3961   //
3962   // SRL expansion:
3963   //   if Shamt-XLEN < 0: // Shamt < XLEN
3964   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3965   //     Hi = Hi >>u Shamt
3966   //   else:
3967   //     Lo = Hi >>u (Shamt-XLEN);
3968   //     Hi = 0;
3969 
3970   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3971 
3972   SDValue Zero = DAG.getConstant(0, DL, VT);
3973   SDValue One = DAG.getConstant(1, DL, VT);
3974   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3975   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3976   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3977   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3978 
3979   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3980   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3981   SDValue ShiftLeftHi =
3982       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3983   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3984   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3985   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3986   SDValue HiFalse =
3987       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3988 
3989   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3990 
3991   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3992   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3993 
3994   SDValue Parts[2] = {Lo, Hi};
3995   return DAG.getMergeValues(Parts, DL);
3996 }
3997 
3998 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3999 // legal equivalently-sized i8 type, so we can use that as a go-between.
4000 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4001                                                   SelectionDAG &DAG) const {
4002   SDLoc DL(Op);
4003   MVT VT = Op.getSimpleValueType();
4004   SDValue SplatVal = Op.getOperand(0);
4005   // All-zeros or all-ones splats are handled specially.
4006   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4007     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4008     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4009   }
4010   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4011     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4012     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4013   }
4014   MVT XLenVT = Subtarget.getXLenVT();
4015   assert(SplatVal.getValueType() == XLenVT &&
4016          "Unexpected type for i1 splat value");
4017   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4018   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4019                          DAG.getConstant(1, DL, XLenVT));
4020   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4021   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4022   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4023 }
4024 
4025 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4026 // illegal (currently only vXi64 RV32).
4027 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4028 // them to SPLAT_VECTOR_I64
4029 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4030                                                      SelectionDAG &DAG) const {
4031   SDLoc DL(Op);
4032   MVT VecVT = Op.getSimpleValueType();
4033   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4034          "Unexpected SPLAT_VECTOR_PARTS lowering");
4035 
4036   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4037   SDValue Lo = Op.getOperand(0);
4038   SDValue Hi = Op.getOperand(1);
4039 
4040   if (VecVT.isFixedLengthVector()) {
4041     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4042     SDLoc DL(Op);
4043     SDValue Mask, VL;
4044     std::tie(Mask, VL) =
4045         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4046 
4047     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
4048     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4049   }
4050 
4051   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4052     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4053     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4054     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4055     // node in order to try and match RVV vector/scalar instructions.
4056     if ((LoC >> 31) == HiC)
4057       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4058   }
4059 
4060   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4061   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4062       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4063       Hi.getConstantOperandVal(1) == 31)
4064     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4065 
4066   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4067   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4068                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i32));
4069 }
4070 
4071 // Custom-lower extensions from mask vectors by using a vselect either with 1
4072 // for zero/any-extension or -1 for sign-extension:
4073 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4074 // Note that any-extension is lowered identically to zero-extension.
4075 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4076                                                 int64_t ExtTrueVal) const {
4077   SDLoc DL(Op);
4078   MVT VecVT = Op.getSimpleValueType();
4079   SDValue Src = Op.getOperand(0);
4080   // Only custom-lower extensions from mask types
4081   assert(Src.getValueType().isVector() &&
4082          Src.getValueType().getVectorElementType() == MVT::i1);
4083 
4084   MVT XLenVT = Subtarget.getXLenVT();
4085   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4086   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4087 
4088   if (VecVT.isScalableVector()) {
4089     // Be careful not to introduce illegal scalar types at this stage, and be
4090     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4091     // illegal and must be expanded. Since we know that the constants are
4092     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
4093     bool IsRV32E64 =
4094         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4095 
4096     if (!IsRV32E64) {
4097       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4098       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4099     } else {
4100       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
4101       SplatTrueVal =
4102           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
4103     }
4104 
4105     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4106   }
4107 
4108   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4109   MVT I1ContainerVT =
4110       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4111 
4112   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4113 
4114   SDValue Mask, VL;
4115   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4116 
4117   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4118   SplatTrueVal =
4119       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4120   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4121                                SplatTrueVal, SplatZero, VL);
4122 
4123   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4124 }
4125 
4126 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4127     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4128   MVT ExtVT = Op.getSimpleValueType();
4129   // Only custom-lower extensions from fixed-length vector types.
4130   if (!ExtVT.isFixedLengthVector())
4131     return Op;
4132   MVT VT = Op.getOperand(0).getSimpleValueType();
4133   // Grab the canonical container type for the extended type. Infer the smaller
4134   // type from that to ensure the same number of vector elements, as we know
4135   // the LMUL will be sufficient to hold the smaller type.
4136   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4137   // Get the extended container type manually to ensure the same number of
4138   // vector elements between source and dest.
4139   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4140                                      ContainerExtVT.getVectorElementCount());
4141 
4142   SDValue Op1 =
4143       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4144 
4145   SDLoc DL(Op);
4146   SDValue Mask, VL;
4147   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4148 
4149   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4150 
4151   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4152 }
4153 
4154 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4155 // setcc operation:
4156 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4157 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4158                                                   SelectionDAG &DAG) const {
4159   SDLoc DL(Op);
4160   EVT MaskVT = Op.getValueType();
4161   // Only expect to custom-lower truncations to mask types
4162   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4163          "Unexpected type for vector mask lowering");
4164   SDValue Src = Op.getOperand(0);
4165   MVT VecVT = Src.getSimpleValueType();
4166 
4167   // If this is a fixed vector, we need to convert it to a scalable vector.
4168   MVT ContainerVT = VecVT;
4169   if (VecVT.isFixedLengthVector()) {
4170     ContainerVT = getContainerForFixedLengthVector(VecVT);
4171     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4172   }
4173 
4174   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4175   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4176 
4177   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4178   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4179 
4180   if (VecVT.isScalableVector()) {
4181     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4182     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4183   }
4184 
4185   SDValue Mask, VL;
4186   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4187 
4188   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4189   SDValue Trunc =
4190       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4191   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4192                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4193   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4194 }
4195 
4196 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4197 // first position of a vector, and that vector is slid up to the insert index.
4198 // By limiting the active vector length to index+1 and merging with the
4199 // original vector (with an undisturbed tail policy for elements >= VL), we
4200 // achieve the desired result of leaving all elements untouched except the one
4201 // at VL-1, which is replaced with the desired value.
4202 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4203                                                     SelectionDAG &DAG) const {
4204   SDLoc DL(Op);
4205   MVT VecVT = Op.getSimpleValueType();
4206   SDValue Vec = Op.getOperand(0);
4207   SDValue Val = Op.getOperand(1);
4208   SDValue Idx = Op.getOperand(2);
4209 
4210   if (VecVT.getVectorElementType() == MVT::i1) {
4211     // FIXME: For now we just promote to an i8 vector and insert into that,
4212     // but this is probably not optimal.
4213     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4214     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4215     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4216     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4217   }
4218 
4219   MVT ContainerVT = VecVT;
4220   // If the operand is a fixed-length vector, convert to a scalable one.
4221   if (VecVT.isFixedLengthVector()) {
4222     ContainerVT = getContainerForFixedLengthVector(VecVT);
4223     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4224   }
4225 
4226   MVT XLenVT = Subtarget.getXLenVT();
4227 
4228   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4229   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4230   // Even i64-element vectors on RV32 can be lowered without scalar
4231   // legalization if the most-significant 32 bits of the value are not affected
4232   // by the sign-extension of the lower 32 bits.
4233   // TODO: We could also catch sign extensions of a 32-bit value.
4234   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4235     const auto *CVal = cast<ConstantSDNode>(Val);
4236     if (isInt<32>(CVal->getSExtValue())) {
4237       IsLegalInsert = true;
4238       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4239     }
4240   }
4241 
4242   SDValue Mask, VL;
4243   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4244 
4245   SDValue ValInVec;
4246 
4247   if (IsLegalInsert) {
4248     unsigned Opc =
4249         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4250     if (isNullConstant(Idx)) {
4251       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4252       if (!VecVT.isFixedLengthVector())
4253         return Vec;
4254       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4255     }
4256     ValInVec =
4257         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4258   } else {
4259     // On RV32, i64-element vectors must be specially handled to place the
4260     // value at element 0, by using two vslide1up instructions in sequence on
4261     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4262     // this.
4263     SDValue One = DAG.getConstant(1, DL, XLenVT);
4264     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4265     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4266     MVT I32ContainerVT =
4267         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4268     SDValue I32Mask =
4269         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4270     // Limit the active VL to two.
4271     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4272     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4273     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4274     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4275                            InsertI64VL);
4276     // First slide in the hi value, then the lo in underneath it.
4277     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4278                            ValHi, I32Mask, InsertI64VL);
4279     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4280                            ValLo, I32Mask, InsertI64VL);
4281     // Bitcast back to the right container type.
4282     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4283   }
4284 
4285   // Now that the value is in a vector, slide it into position.
4286   SDValue InsertVL =
4287       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4288   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4289                                 ValInVec, Idx, Mask, InsertVL);
4290   if (!VecVT.isFixedLengthVector())
4291     return Slideup;
4292   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4293 }
4294 
4295 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4296 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4297 // types this is done using VMV_X_S to allow us to glean information about the
4298 // sign bits of the result.
4299 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4300                                                      SelectionDAG &DAG) const {
4301   SDLoc DL(Op);
4302   SDValue Idx = Op.getOperand(1);
4303   SDValue Vec = Op.getOperand(0);
4304   EVT EltVT = Op.getValueType();
4305   MVT VecVT = Vec.getSimpleValueType();
4306   MVT XLenVT = Subtarget.getXLenVT();
4307 
4308   if (VecVT.getVectorElementType() == MVT::i1) {
4309     if (VecVT.isFixedLengthVector()) {
4310       unsigned NumElts = VecVT.getVectorNumElements();
4311       if (NumElts >= 8) {
4312         MVT WideEltVT;
4313         unsigned WidenVecLen;
4314         SDValue ExtractElementIdx;
4315         SDValue ExtractBitIdx;
4316         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4317         MVT LargestEltVT = MVT::getIntegerVT(
4318             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4319         if (NumElts <= LargestEltVT.getSizeInBits()) {
4320           assert(isPowerOf2_32(NumElts) &&
4321                  "the number of elements should be power of 2");
4322           WideEltVT = MVT::getIntegerVT(NumElts);
4323           WidenVecLen = 1;
4324           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4325           ExtractBitIdx = Idx;
4326         } else {
4327           WideEltVT = LargestEltVT;
4328           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4329           // extract element index = index / element width
4330           ExtractElementIdx = DAG.getNode(
4331               ISD::SRL, DL, XLenVT, Idx,
4332               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4333           // mask bit index = index % element width
4334           ExtractBitIdx = DAG.getNode(
4335               ISD::AND, DL, XLenVT, Idx,
4336               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4337         }
4338         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4339         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4340         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4341                                          Vec, ExtractElementIdx);
4342         // Extract the bit from GPR.
4343         SDValue ShiftRight =
4344             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4345         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4346                            DAG.getConstant(1, DL, XLenVT));
4347       }
4348     }
4349     // Otherwise, promote to an i8 vector and extract from that.
4350     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4351     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4352     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4353   }
4354 
4355   // If this is a fixed vector, we need to convert it to a scalable vector.
4356   MVT ContainerVT = VecVT;
4357   if (VecVT.isFixedLengthVector()) {
4358     ContainerVT = getContainerForFixedLengthVector(VecVT);
4359     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4360   }
4361 
4362   // If the index is 0, the vector is already in the right position.
4363   if (!isNullConstant(Idx)) {
4364     // Use a VL of 1 to avoid processing more elements than we need.
4365     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4366     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4367     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4368     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4369                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4370   }
4371 
4372   if (!EltVT.isInteger()) {
4373     // Floating-point extracts are handled in TableGen.
4374     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4375                        DAG.getConstant(0, DL, XLenVT));
4376   }
4377 
4378   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4379   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4380 }
4381 
4382 // Some RVV intrinsics may claim that they want an integer operand to be
4383 // promoted or expanded.
4384 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4385                                           const RISCVSubtarget &Subtarget) {
4386   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4387           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4388          "Unexpected opcode");
4389 
4390   if (!Subtarget.hasVInstructions())
4391     return SDValue();
4392 
4393   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4394   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4395   SDLoc DL(Op);
4396 
4397   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4398       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4399   if (!II || !II->hasSplatOperand())
4400     return SDValue();
4401 
4402   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4403   assert(SplatOp < Op.getNumOperands());
4404 
4405   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4406   SDValue &ScalarOp = Operands[SplatOp];
4407   MVT OpVT = ScalarOp.getSimpleValueType();
4408   MVT XLenVT = Subtarget.getXLenVT();
4409 
4410   // If this isn't a scalar, or its type is XLenVT we're done.
4411   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4412     return SDValue();
4413 
4414   // Simplest case is that the operand needs to be promoted to XLenVT.
4415   if (OpVT.bitsLT(XLenVT)) {
4416     // If the operand is a constant, sign extend to increase our chances
4417     // of being able to use a .vi instruction. ANY_EXTEND would become a
4418     // a zero extend and the simm5 check in isel would fail.
4419     // FIXME: Should we ignore the upper bits in isel instead?
4420     unsigned ExtOpc =
4421         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4422     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4423     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4424   }
4425 
4426   // Use the previous operand to get the vXi64 VT. The result might be a mask
4427   // VT for compares. Using the previous operand assumes that the previous
4428   // operand will never have a smaller element size than a scalar operand and
4429   // that a widening operation never uses SEW=64.
4430   // NOTE: If this fails the below assert, we can probably just find the
4431   // element count from any operand or result and use it to construct the VT.
4432   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4433   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4434 
4435   // The more complex case is when the scalar is larger than XLenVT.
4436   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4437          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4438 
4439   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4440   // on the instruction to sign-extend since SEW>XLEN.
4441   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4442     if (isInt<32>(CVal->getSExtValue())) {
4443       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4444       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4445     }
4446   }
4447 
4448   // We need to convert the scalar to a splat vector.
4449   // FIXME: Can we implicitly truncate the scalar if it is known to
4450   // be sign extended?
4451   SDValue VL = getVLOperand(Op);
4452   assert(VL.getValueType() == XLenVT);
4453   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4454   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4455 }
4456 
4457 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4458                                                      SelectionDAG &DAG) const {
4459   unsigned IntNo = Op.getConstantOperandVal(0);
4460   SDLoc DL(Op);
4461   MVT XLenVT = Subtarget.getXLenVT();
4462 
4463   switch (IntNo) {
4464   default:
4465     break; // Don't custom lower most intrinsics.
4466   case Intrinsic::thread_pointer: {
4467     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4468     return DAG.getRegister(RISCV::X4, PtrVT);
4469   }
4470   case Intrinsic::riscv_orc_b:
4471   case Intrinsic::riscv_brev8: {
4472     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4473     unsigned Opc =
4474         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4475     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4476                        DAG.getConstant(7, DL, XLenVT));
4477   }
4478   case Intrinsic::riscv_grev:
4479   case Intrinsic::riscv_gorc: {
4480     unsigned Opc =
4481         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4482     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4483   }
4484   case Intrinsic::riscv_zip:
4485   case Intrinsic::riscv_unzip: {
4486     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4487     // For i32 the immdiate is 15. For i64 the immediate is 31.
4488     unsigned Opc =
4489         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4490     unsigned BitWidth = Op.getValueSizeInBits();
4491     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4492     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4493                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4494   }
4495   case Intrinsic::riscv_shfl:
4496   case Intrinsic::riscv_unshfl: {
4497     unsigned Opc =
4498         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4499     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4500   }
4501   case Intrinsic::riscv_bcompress:
4502   case Intrinsic::riscv_bdecompress: {
4503     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4504                                                        : RISCVISD::BDECOMPRESS;
4505     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4506   }
4507   case Intrinsic::riscv_bfp:
4508     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4509                        Op.getOperand(2));
4510   case Intrinsic::riscv_fsl:
4511     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4512                        Op.getOperand(2), Op.getOperand(3));
4513   case Intrinsic::riscv_fsr:
4514     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4515                        Op.getOperand(2), Op.getOperand(3));
4516   case Intrinsic::riscv_vmv_x_s:
4517     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4518     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4519                        Op.getOperand(1));
4520   case Intrinsic::riscv_vmv_v_x:
4521     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4522                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4523   case Intrinsic::riscv_vfmv_v_f:
4524     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4525                        Op.getOperand(1), Op.getOperand(2));
4526   case Intrinsic::riscv_vmv_s_x: {
4527     SDValue Scalar = Op.getOperand(2);
4528 
4529     if (Scalar.getValueType().bitsLE(XLenVT)) {
4530       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4531       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4532                          Op.getOperand(1), Scalar, Op.getOperand(3));
4533     }
4534 
4535     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4536 
4537     // This is an i64 value that lives in two scalar registers. We have to
4538     // insert this in a convoluted way. First we build vXi64 splat containing
4539     // the/ two values that we assemble using some bit math. Next we'll use
4540     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4541     // to merge element 0 from our splat into the source vector.
4542     // FIXME: This is probably not the best way to do this, but it is
4543     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4544     // point.
4545     //   sw lo, (a0)
4546     //   sw hi, 4(a0)
4547     //   vlse vX, (a0)
4548     //
4549     //   vid.v      vVid
4550     //   vmseq.vx   mMask, vVid, 0
4551     //   vmerge.vvm vDest, vSrc, vVal, mMask
4552     MVT VT = Op.getSimpleValueType();
4553     SDValue Vec = Op.getOperand(1);
4554     SDValue VL = getVLOperand(Op);
4555 
4556     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4557     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4558                                       DAG.getConstant(0, DL, MVT::i32), VL);
4559 
4560     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4561     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4562     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4563     SDValue SelectCond =
4564         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4565                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4566     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4567                        Vec, VL);
4568   }
4569   case Intrinsic::riscv_vslide1up:
4570   case Intrinsic::riscv_vslide1down:
4571   case Intrinsic::riscv_vslide1up_mask:
4572   case Intrinsic::riscv_vslide1down_mask: {
4573     // We need to special case these when the scalar is larger than XLen.
4574     unsigned NumOps = Op.getNumOperands();
4575     bool IsMasked = NumOps == 7;
4576     unsigned OpOffset = IsMasked ? 1 : 0;
4577     SDValue Scalar = Op.getOperand(2 + OpOffset);
4578     if (Scalar.getValueType().bitsLE(XLenVT))
4579       break;
4580 
4581     // Splatting a sign extended constant is fine.
4582     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4583       if (isInt<32>(CVal->getSExtValue()))
4584         break;
4585 
4586     MVT VT = Op.getSimpleValueType();
4587     assert(VT.getVectorElementType() == MVT::i64 &&
4588            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4589 
4590     // Convert the vector source to the equivalent nxvXi32 vector.
4591     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4592     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4593 
4594     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4595                                    DAG.getConstant(0, DL, XLenVT));
4596     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4597                                    DAG.getConstant(1, DL, XLenVT));
4598 
4599     // Double the VL since we halved SEW.
4600     SDValue VL = getVLOperand(Op);
4601     SDValue I32VL =
4602         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4603 
4604     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4605     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4606 
4607     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4608     // instructions.
4609     if (IntNo == Intrinsic::riscv_vslide1up ||
4610         IntNo == Intrinsic::riscv_vslide1up_mask) {
4611       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4612                         I32Mask, I32VL);
4613       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4614                         I32Mask, I32VL);
4615     } else {
4616       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4617                         I32Mask, I32VL);
4618       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4619                         I32Mask, I32VL);
4620     }
4621 
4622     // Convert back to nxvXi64.
4623     Vec = DAG.getBitcast(VT, Vec);
4624 
4625     if (!IsMasked)
4626       return Vec;
4627 
4628     // Apply mask after the operation.
4629     SDValue Mask = Op.getOperand(NumOps - 3);
4630     SDValue MaskedOff = Op.getOperand(1);
4631     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4632   }
4633   }
4634 
4635   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4636 }
4637 
4638 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4639                                                     SelectionDAG &DAG) const {
4640   unsigned IntNo = Op.getConstantOperandVal(1);
4641   switch (IntNo) {
4642   default:
4643     break;
4644   case Intrinsic::riscv_masked_strided_load: {
4645     SDLoc DL(Op);
4646     MVT XLenVT = Subtarget.getXLenVT();
4647 
4648     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4649     // the selection of the masked intrinsics doesn't do this for us.
4650     SDValue Mask = Op.getOperand(5);
4651     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4652 
4653     MVT VT = Op->getSimpleValueType(0);
4654     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4655 
4656     SDValue PassThru = Op.getOperand(2);
4657     if (!IsUnmasked) {
4658       MVT MaskVT =
4659           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4660       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4661       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4662     }
4663 
4664     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4665 
4666     SDValue IntID = DAG.getTargetConstant(
4667         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4668         XLenVT);
4669 
4670     auto *Load = cast<MemIntrinsicSDNode>(Op);
4671     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4672     if (IsUnmasked)
4673       Ops.push_back(DAG.getUNDEF(ContainerVT));
4674     else
4675       Ops.push_back(PassThru);
4676     Ops.push_back(Op.getOperand(3)); // Ptr
4677     Ops.push_back(Op.getOperand(4)); // Stride
4678     if (!IsUnmasked)
4679       Ops.push_back(Mask);
4680     Ops.push_back(VL);
4681     if (!IsUnmasked) {
4682       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4683       Ops.push_back(Policy);
4684     }
4685 
4686     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4687     SDValue Result =
4688         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4689                                 Load->getMemoryVT(), Load->getMemOperand());
4690     SDValue Chain = Result.getValue(1);
4691     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4692     return DAG.getMergeValues({Result, Chain}, DL);
4693   }
4694   }
4695 
4696   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4697 }
4698 
4699 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4700                                                  SelectionDAG &DAG) const {
4701   unsigned IntNo = Op.getConstantOperandVal(1);
4702   switch (IntNo) {
4703   default:
4704     break;
4705   case Intrinsic::riscv_masked_strided_store: {
4706     SDLoc DL(Op);
4707     MVT XLenVT = Subtarget.getXLenVT();
4708 
4709     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4710     // the selection of the masked intrinsics doesn't do this for us.
4711     SDValue Mask = Op.getOperand(5);
4712     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4713 
4714     SDValue Val = Op.getOperand(2);
4715     MVT VT = Val.getSimpleValueType();
4716     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4717 
4718     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4719     if (!IsUnmasked) {
4720       MVT MaskVT =
4721           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4722       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4723     }
4724 
4725     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4726 
4727     SDValue IntID = DAG.getTargetConstant(
4728         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4729         XLenVT);
4730 
4731     auto *Store = cast<MemIntrinsicSDNode>(Op);
4732     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4733     Ops.push_back(Val);
4734     Ops.push_back(Op.getOperand(3)); // Ptr
4735     Ops.push_back(Op.getOperand(4)); // Stride
4736     if (!IsUnmasked)
4737       Ops.push_back(Mask);
4738     Ops.push_back(VL);
4739 
4740     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4741                                    Ops, Store->getMemoryVT(),
4742                                    Store->getMemOperand());
4743   }
4744   }
4745 
4746   return SDValue();
4747 }
4748 
4749 static MVT getLMUL1VT(MVT VT) {
4750   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4751          "Unexpected vector MVT");
4752   return MVT::getScalableVectorVT(
4753       VT.getVectorElementType(),
4754       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4755 }
4756 
4757 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4758   switch (ISDOpcode) {
4759   default:
4760     llvm_unreachable("Unhandled reduction");
4761   case ISD::VECREDUCE_ADD:
4762     return RISCVISD::VECREDUCE_ADD_VL;
4763   case ISD::VECREDUCE_UMAX:
4764     return RISCVISD::VECREDUCE_UMAX_VL;
4765   case ISD::VECREDUCE_SMAX:
4766     return RISCVISD::VECREDUCE_SMAX_VL;
4767   case ISD::VECREDUCE_UMIN:
4768     return RISCVISD::VECREDUCE_UMIN_VL;
4769   case ISD::VECREDUCE_SMIN:
4770     return RISCVISD::VECREDUCE_SMIN_VL;
4771   case ISD::VECREDUCE_AND:
4772     return RISCVISD::VECREDUCE_AND_VL;
4773   case ISD::VECREDUCE_OR:
4774     return RISCVISD::VECREDUCE_OR_VL;
4775   case ISD::VECREDUCE_XOR:
4776     return RISCVISD::VECREDUCE_XOR_VL;
4777   }
4778 }
4779 
4780 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4781                                                          SelectionDAG &DAG,
4782                                                          bool IsVP) const {
4783   SDLoc DL(Op);
4784   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4785   MVT VecVT = Vec.getSimpleValueType();
4786   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4787           Op.getOpcode() == ISD::VECREDUCE_OR ||
4788           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4789           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4790           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4791           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4792          "Unexpected reduction lowering");
4793 
4794   MVT XLenVT = Subtarget.getXLenVT();
4795   assert(Op.getValueType() == XLenVT &&
4796          "Expected reduction output to be legalized to XLenVT");
4797 
4798   MVT ContainerVT = VecVT;
4799   if (VecVT.isFixedLengthVector()) {
4800     ContainerVT = getContainerForFixedLengthVector(VecVT);
4801     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4802   }
4803 
4804   SDValue Mask, VL;
4805   if (IsVP) {
4806     Mask = Op.getOperand(2);
4807     VL = Op.getOperand(3);
4808   } else {
4809     std::tie(Mask, VL) =
4810         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4811   }
4812 
4813   unsigned BaseOpc;
4814   ISD::CondCode CC;
4815   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4816 
4817   switch (Op.getOpcode()) {
4818   default:
4819     llvm_unreachable("Unhandled reduction");
4820   case ISD::VECREDUCE_AND:
4821   case ISD::VP_REDUCE_AND: {
4822     // vcpop ~x == 0
4823     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4824     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4825     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4826     CC = ISD::SETEQ;
4827     BaseOpc = ISD::AND;
4828     break;
4829   }
4830   case ISD::VECREDUCE_OR:
4831   case ISD::VP_REDUCE_OR:
4832     // vcpop x != 0
4833     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4834     CC = ISD::SETNE;
4835     BaseOpc = ISD::OR;
4836     break;
4837   case ISD::VECREDUCE_XOR:
4838   case ISD::VP_REDUCE_XOR: {
4839     // ((vcpop x) & 1) != 0
4840     SDValue One = DAG.getConstant(1, DL, XLenVT);
4841     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4842     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4843     CC = ISD::SETNE;
4844     BaseOpc = ISD::XOR;
4845     break;
4846   }
4847   }
4848 
4849   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4850 
4851   if (!IsVP)
4852     return SetCC;
4853 
4854   // Now include the start value in the operation.
4855   // Note that we must return the start value when no elements are operated
4856   // upon. The vcpop instructions we've emitted in each case above will return
4857   // 0 for an inactive vector, and so we've already received the neutral value:
4858   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4859   // can simply include the start value.
4860   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4861 }
4862 
4863 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4864                                             SelectionDAG &DAG) const {
4865   SDLoc DL(Op);
4866   SDValue Vec = Op.getOperand(0);
4867   EVT VecEVT = Vec.getValueType();
4868 
4869   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4870 
4871   // Due to ordering in legalize types we may have a vector type that needs to
4872   // be split. Do that manually so we can get down to a legal type.
4873   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4874          TargetLowering::TypeSplitVector) {
4875     SDValue Lo, Hi;
4876     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4877     VecEVT = Lo.getValueType();
4878     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4879   }
4880 
4881   // TODO: The type may need to be widened rather than split. Or widened before
4882   // it can be split.
4883   if (!isTypeLegal(VecEVT))
4884     return SDValue();
4885 
4886   MVT VecVT = VecEVT.getSimpleVT();
4887   MVT VecEltVT = VecVT.getVectorElementType();
4888   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4889 
4890   MVT ContainerVT = VecVT;
4891   if (VecVT.isFixedLengthVector()) {
4892     ContainerVT = getContainerForFixedLengthVector(VecVT);
4893     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4894   }
4895 
4896   MVT M1VT = getLMUL1VT(ContainerVT);
4897   MVT XLenVT = Subtarget.getXLenVT();
4898 
4899   SDValue Mask, VL;
4900   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4901 
4902   SDValue NeutralElem =
4903       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4904   SDValue IdentitySplat = lowerScalarSplat(
4905       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4906   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4907                                   IdentitySplat, Mask, VL);
4908   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4909                              DAG.getConstant(0, DL, XLenVT));
4910   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4911 }
4912 
4913 // Given a reduction op, this function returns the matching reduction opcode,
4914 // the vector SDValue and the scalar SDValue required to lower this to a
4915 // RISCVISD node.
4916 static std::tuple<unsigned, SDValue, SDValue>
4917 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4918   SDLoc DL(Op);
4919   auto Flags = Op->getFlags();
4920   unsigned Opcode = Op.getOpcode();
4921   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4922   switch (Opcode) {
4923   default:
4924     llvm_unreachable("Unhandled reduction");
4925   case ISD::VECREDUCE_FADD: {
4926     // Use positive zero if we can. It is cheaper to materialize.
4927     SDValue Zero =
4928         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4929     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4930   }
4931   case ISD::VECREDUCE_SEQ_FADD:
4932     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4933                            Op.getOperand(0));
4934   case ISD::VECREDUCE_FMIN:
4935     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4936                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4937   case ISD::VECREDUCE_FMAX:
4938     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4939                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4940   }
4941 }
4942 
4943 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4944                                               SelectionDAG &DAG) const {
4945   SDLoc DL(Op);
4946   MVT VecEltVT = Op.getSimpleValueType();
4947 
4948   unsigned RVVOpcode;
4949   SDValue VectorVal, ScalarVal;
4950   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4951       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4952   MVT VecVT = VectorVal.getSimpleValueType();
4953 
4954   MVT ContainerVT = VecVT;
4955   if (VecVT.isFixedLengthVector()) {
4956     ContainerVT = getContainerForFixedLengthVector(VecVT);
4957     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4958   }
4959 
4960   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4961   MVT XLenVT = Subtarget.getXLenVT();
4962 
4963   SDValue Mask, VL;
4964   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4965 
4966   SDValue ScalarSplat = lowerScalarSplat(
4967       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4968   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4969                                   VectorVal, ScalarSplat, Mask, VL);
4970   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4971                      DAG.getConstant(0, DL, XLenVT));
4972 }
4973 
4974 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4975   switch (ISDOpcode) {
4976   default:
4977     llvm_unreachable("Unhandled reduction");
4978   case ISD::VP_REDUCE_ADD:
4979     return RISCVISD::VECREDUCE_ADD_VL;
4980   case ISD::VP_REDUCE_UMAX:
4981     return RISCVISD::VECREDUCE_UMAX_VL;
4982   case ISD::VP_REDUCE_SMAX:
4983     return RISCVISD::VECREDUCE_SMAX_VL;
4984   case ISD::VP_REDUCE_UMIN:
4985     return RISCVISD::VECREDUCE_UMIN_VL;
4986   case ISD::VP_REDUCE_SMIN:
4987     return RISCVISD::VECREDUCE_SMIN_VL;
4988   case ISD::VP_REDUCE_AND:
4989     return RISCVISD::VECREDUCE_AND_VL;
4990   case ISD::VP_REDUCE_OR:
4991     return RISCVISD::VECREDUCE_OR_VL;
4992   case ISD::VP_REDUCE_XOR:
4993     return RISCVISD::VECREDUCE_XOR_VL;
4994   case ISD::VP_REDUCE_FADD:
4995     return RISCVISD::VECREDUCE_FADD_VL;
4996   case ISD::VP_REDUCE_SEQ_FADD:
4997     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4998   case ISD::VP_REDUCE_FMAX:
4999     return RISCVISD::VECREDUCE_FMAX_VL;
5000   case ISD::VP_REDUCE_FMIN:
5001     return RISCVISD::VECREDUCE_FMIN_VL;
5002   }
5003 }
5004 
5005 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5006                                            SelectionDAG &DAG) const {
5007   SDLoc DL(Op);
5008   SDValue Vec = Op.getOperand(1);
5009   EVT VecEVT = Vec.getValueType();
5010 
5011   // TODO: The type may need to be widened rather than split. Or widened before
5012   // it can be split.
5013   if (!isTypeLegal(VecEVT))
5014     return SDValue();
5015 
5016   MVT VecVT = VecEVT.getSimpleVT();
5017   MVT VecEltVT = VecVT.getVectorElementType();
5018   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5019 
5020   MVT ContainerVT = VecVT;
5021   if (VecVT.isFixedLengthVector()) {
5022     ContainerVT = getContainerForFixedLengthVector(VecVT);
5023     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5024   }
5025 
5026   SDValue VL = Op.getOperand(3);
5027   SDValue Mask = Op.getOperand(2);
5028 
5029   MVT M1VT = getLMUL1VT(ContainerVT);
5030   MVT XLenVT = Subtarget.getXLenVT();
5031   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5032 
5033   SDValue StartSplat =
5034       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
5035                        DL, DAG, Subtarget);
5036   SDValue Reduction =
5037       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5038   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5039                              DAG.getConstant(0, DL, XLenVT));
5040   if (!VecVT.isInteger())
5041     return Elt0;
5042   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5043 }
5044 
5045 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5046                                                    SelectionDAG &DAG) const {
5047   SDValue Vec = Op.getOperand(0);
5048   SDValue SubVec = Op.getOperand(1);
5049   MVT VecVT = Vec.getSimpleValueType();
5050   MVT SubVecVT = SubVec.getSimpleValueType();
5051 
5052   SDLoc DL(Op);
5053   MVT XLenVT = Subtarget.getXLenVT();
5054   unsigned OrigIdx = Op.getConstantOperandVal(2);
5055   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5056 
5057   // We don't have the ability to slide mask vectors up indexed by their i1
5058   // elements; the smallest we can do is i8. Often we are able to bitcast to
5059   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5060   // into a scalable one, we might not necessarily have enough scalable
5061   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5062   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5063       (OrigIdx != 0 || !Vec.isUndef())) {
5064     if (VecVT.getVectorMinNumElements() >= 8 &&
5065         SubVecVT.getVectorMinNumElements() >= 8) {
5066       assert(OrigIdx % 8 == 0 && "Invalid index");
5067       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5068              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5069              "Unexpected mask vector lowering");
5070       OrigIdx /= 8;
5071       SubVecVT =
5072           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5073                            SubVecVT.isScalableVector());
5074       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5075                                VecVT.isScalableVector());
5076       Vec = DAG.getBitcast(VecVT, Vec);
5077       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5078     } else {
5079       // We can't slide this mask vector up indexed by its i1 elements.
5080       // This poses a problem when we wish to insert a scalable vector which
5081       // can't be re-expressed as a larger type. Just choose the slow path and
5082       // extend to a larger type, then truncate back down.
5083       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5084       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5085       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5086       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5087       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5088                         Op.getOperand(2));
5089       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5090       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5091     }
5092   }
5093 
5094   // If the subvector vector is a fixed-length type, we cannot use subregister
5095   // manipulation to simplify the codegen; we don't know which register of a
5096   // LMUL group contains the specific subvector as we only know the minimum
5097   // register size. Therefore we must slide the vector group up the full
5098   // amount.
5099   if (SubVecVT.isFixedLengthVector()) {
5100     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5101       return Op;
5102     MVT ContainerVT = VecVT;
5103     if (VecVT.isFixedLengthVector()) {
5104       ContainerVT = getContainerForFixedLengthVector(VecVT);
5105       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5106     }
5107     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5108                          DAG.getUNDEF(ContainerVT), SubVec,
5109                          DAG.getConstant(0, DL, XLenVT));
5110     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5111       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5112       return DAG.getBitcast(Op.getValueType(), SubVec);
5113     }
5114     SDValue Mask =
5115         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5116     // Set the vector length to only the number of elements we care about. Note
5117     // that for slideup this includes the offset.
5118     SDValue VL =
5119         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5120     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5121     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5122                                   SubVec, SlideupAmt, Mask, VL);
5123     if (VecVT.isFixedLengthVector())
5124       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5125     return DAG.getBitcast(Op.getValueType(), Slideup);
5126   }
5127 
5128   unsigned SubRegIdx, RemIdx;
5129   std::tie(SubRegIdx, RemIdx) =
5130       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5131           VecVT, SubVecVT, OrigIdx, TRI);
5132 
5133   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5134   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5135                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5136                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5137 
5138   // 1. If the Idx has been completely eliminated and this subvector's size is
5139   // a vector register or a multiple thereof, or the surrounding elements are
5140   // undef, then this is a subvector insert which naturally aligns to a vector
5141   // register. These can easily be handled using subregister manipulation.
5142   // 2. If the subvector is smaller than a vector register, then the insertion
5143   // must preserve the undisturbed elements of the register. We do this by
5144   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5145   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5146   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5147   // LMUL=1 type back into the larger vector (resolving to another subregister
5148   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5149   // to avoid allocating a large register group to hold our subvector.
5150   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5151     return Op;
5152 
5153   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5154   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5155   // (in our case undisturbed). This means we can set up a subvector insertion
5156   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5157   // size of the subvector.
5158   MVT InterSubVT = VecVT;
5159   SDValue AlignedExtract = Vec;
5160   unsigned AlignedIdx = OrigIdx - RemIdx;
5161   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5162     InterSubVT = getLMUL1VT(VecVT);
5163     // Extract a subvector equal to the nearest full vector register type. This
5164     // should resolve to a EXTRACT_SUBREG instruction.
5165     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5166                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5167   }
5168 
5169   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5170   // For scalable vectors this must be further multiplied by vscale.
5171   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5172 
5173   SDValue Mask, VL;
5174   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5175 
5176   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5177   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5178   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5179   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5180 
5181   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5182                        DAG.getUNDEF(InterSubVT), SubVec,
5183                        DAG.getConstant(0, DL, XLenVT));
5184 
5185   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5186                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5187 
5188   // If required, insert this subvector back into the correct vector register.
5189   // This should resolve to an INSERT_SUBREG instruction.
5190   if (VecVT.bitsGT(InterSubVT))
5191     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5192                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5193 
5194   // We might have bitcast from a mask type: cast back to the original type if
5195   // required.
5196   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5197 }
5198 
5199 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5200                                                     SelectionDAG &DAG) const {
5201   SDValue Vec = Op.getOperand(0);
5202   MVT SubVecVT = Op.getSimpleValueType();
5203   MVT VecVT = Vec.getSimpleValueType();
5204 
5205   SDLoc DL(Op);
5206   MVT XLenVT = Subtarget.getXLenVT();
5207   unsigned OrigIdx = Op.getConstantOperandVal(1);
5208   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5209 
5210   // We don't have the ability to slide mask vectors down indexed by their i1
5211   // elements; the smallest we can do is i8. Often we are able to bitcast to
5212   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5213   // from a scalable one, we might not necessarily have enough scalable
5214   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5215   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5216     if (VecVT.getVectorMinNumElements() >= 8 &&
5217         SubVecVT.getVectorMinNumElements() >= 8) {
5218       assert(OrigIdx % 8 == 0 && "Invalid index");
5219       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5220              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5221              "Unexpected mask vector lowering");
5222       OrigIdx /= 8;
5223       SubVecVT =
5224           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5225                            SubVecVT.isScalableVector());
5226       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5227                                VecVT.isScalableVector());
5228       Vec = DAG.getBitcast(VecVT, Vec);
5229     } else {
5230       // We can't slide this mask vector down, indexed by its i1 elements.
5231       // This poses a problem when we wish to extract a scalable vector which
5232       // can't be re-expressed as a larger type. Just choose the slow path and
5233       // extend to a larger type, then truncate back down.
5234       // TODO: We could probably improve this when extracting certain fixed
5235       // from fixed, where we can extract as i8 and shift the correct element
5236       // right to reach the desired subvector?
5237       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5238       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5239       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5240       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5241                         Op.getOperand(1));
5242       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5243       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5244     }
5245   }
5246 
5247   // If the subvector vector is a fixed-length type, we cannot use subregister
5248   // manipulation to simplify the codegen; we don't know which register of a
5249   // LMUL group contains the specific subvector as we only know the minimum
5250   // register size. Therefore we must slide the vector group down the full
5251   // amount.
5252   if (SubVecVT.isFixedLengthVector()) {
5253     // With an index of 0 this is a cast-like subvector, which can be performed
5254     // with subregister operations.
5255     if (OrigIdx == 0)
5256       return Op;
5257     MVT ContainerVT = VecVT;
5258     if (VecVT.isFixedLengthVector()) {
5259       ContainerVT = getContainerForFixedLengthVector(VecVT);
5260       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5261     }
5262     SDValue Mask =
5263         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5264     // Set the vector length to only the number of elements we care about. This
5265     // avoids sliding down elements we're going to discard straight away.
5266     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5267     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5268     SDValue Slidedown =
5269         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5270                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5271     // Now we can use a cast-like subvector extract to get the result.
5272     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5273                             DAG.getConstant(0, DL, XLenVT));
5274     return DAG.getBitcast(Op.getValueType(), Slidedown);
5275   }
5276 
5277   unsigned SubRegIdx, RemIdx;
5278   std::tie(SubRegIdx, RemIdx) =
5279       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5280           VecVT, SubVecVT, OrigIdx, TRI);
5281 
5282   // If the Idx has been completely eliminated then this is a subvector extract
5283   // which naturally aligns to a vector register. These can easily be handled
5284   // using subregister manipulation.
5285   if (RemIdx == 0)
5286     return Op;
5287 
5288   // Else we must shift our vector register directly to extract the subvector.
5289   // Do this using VSLIDEDOWN.
5290 
5291   // If the vector type is an LMUL-group type, extract a subvector equal to the
5292   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5293   // instruction.
5294   MVT InterSubVT = VecVT;
5295   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5296     InterSubVT = getLMUL1VT(VecVT);
5297     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5298                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5299   }
5300 
5301   // Slide this vector register down by the desired number of elements in order
5302   // to place the desired subvector starting at element 0.
5303   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5304   // For scalable vectors this must be further multiplied by vscale.
5305   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5306 
5307   SDValue Mask, VL;
5308   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5309   SDValue Slidedown =
5310       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5311                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5312 
5313   // Now the vector is in the right position, extract our final subvector. This
5314   // should resolve to a COPY.
5315   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5316                           DAG.getConstant(0, DL, XLenVT));
5317 
5318   // We might have bitcast from a mask type: cast back to the original type if
5319   // required.
5320   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5321 }
5322 
5323 // Lower step_vector to the vid instruction. Any non-identity step value must
5324 // be accounted for my manual expansion.
5325 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5326                                               SelectionDAG &DAG) const {
5327   SDLoc DL(Op);
5328   MVT VT = Op.getSimpleValueType();
5329   MVT XLenVT = Subtarget.getXLenVT();
5330   SDValue Mask, VL;
5331   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5332   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5333   uint64_t StepValImm = Op.getConstantOperandVal(0);
5334   if (StepValImm != 1) {
5335     if (isPowerOf2_64(StepValImm)) {
5336       SDValue StepVal =
5337           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5338                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5339       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5340     } else {
5341       SDValue StepVal = lowerScalarSplat(
5342           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5343           DL, DAG, Subtarget);
5344       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5345     }
5346   }
5347   return StepVec;
5348 }
5349 
5350 // Implement vector_reverse using vrgather.vv with indices determined by
5351 // subtracting the id of each element from (VLMAX-1). This will convert
5352 // the indices like so:
5353 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5354 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5355 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5356                                                  SelectionDAG &DAG) const {
5357   SDLoc DL(Op);
5358   MVT VecVT = Op.getSimpleValueType();
5359   unsigned EltSize = VecVT.getScalarSizeInBits();
5360   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5361 
5362   unsigned MaxVLMAX = 0;
5363   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5364   if (VectorBitsMax != 0)
5365     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5366 
5367   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5368   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5369 
5370   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5371   // to use vrgatherei16.vv.
5372   // TODO: It's also possible to use vrgatherei16.vv for other types to
5373   // decrease register width for the index calculation.
5374   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5375     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5376     // Reverse each half, then reassemble them in reverse order.
5377     // NOTE: It's also possible that after splitting that VLMAX no longer
5378     // requires vrgatherei16.vv.
5379     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5380       SDValue Lo, Hi;
5381       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5382       EVT LoVT, HiVT;
5383       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5384       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5385       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5386       // Reassemble the low and high pieces reversed.
5387       // FIXME: This is a CONCAT_VECTORS.
5388       SDValue Res =
5389           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5390                       DAG.getIntPtrConstant(0, DL));
5391       return DAG.getNode(
5392           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5393           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5394     }
5395 
5396     // Just promote the int type to i16 which will double the LMUL.
5397     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5398     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5399   }
5400 
5401   MVT XLenVT = Subtarget.getXLenVT();
5402   SDValue Mask, VL;
5403   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5404 
5405   // Calculate VLMAX-1 for the desired SEW.
5406   unsigned MinElts = VecVT.getVectorMinNumElements();
5407   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5408                               DAG.getConstant(MinElts, DL, XLenVT));
5409   SDValue VLMinus1 =
5410       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5411 
5412   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5413   bool IsRV32E64 =
5414       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5415   SDValue SplatVL;
5416   if (!IsRV32E64)
5417     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5418   else
5419     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5420 
5421   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5422   SDValue Indices =
5423       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5424 
5425   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5426 }
5427 
5428 SDValue
5429 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5430                                                      SelectionDAG &DAG) const {
5431   SDLoc DL(Op);
5432   auto *Load = cast<LoadSDNode>(Op);
5433 
5434   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5435                                         Load->getMemoryVT(),
5436                                         *Load->getMemOperand()) &&
5437          "Expecting a correctly-aligned load");
5438 
5439   MVT VT = Op.getSimpleValueType();
5440   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5441 
5442   SDValue VL =
5443       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5444 
5445   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5446   SDValue NewLoad = DAG.getMemIntrinsicNode(
5447       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5448       Load->getMemoryVT(), Load->getMemOperand());
5449 
5450   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5451   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5452 }
5453 
5454 SDValue
5455 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5456                                                       SelectionDAG &DAG) const {
5457   SDLoc DL(Op);
5458   auto *Store = cast<StoreSDNode>(Op);
5459 
5460   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5461                                         Store->getMemoryVT(),
5462                                         *Store->getMemOperand()) &&
5463          "Expecting a correctly-aligned store");
5464 
5465   SDValue StoreVal = Store->getValue();
5466   MVT VT = StoreVal.getSimpleValueType();
5467 
5468   // If the size less than a byte, we need to pad with zeros to make a byte.
5469   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5470     VT = MVT::v8i1;
5471     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5472                            DAG.getConstant(0, DL, VT), StoreVal,
5473                            DAG.getIntPtrConstant(0, DL));
5474   }
5475 
5476   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5477 
5478   SDValue VL =
5479       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5480 
5481   SDValue NewValue =
5482       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5483   return DAG.getMemIntrinsicNode(
5484       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5485       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5486       Store->getMemoryVT(), Store->getMemOperand());
5487 }
5488 
5489 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5490                                              SelectionDAG &DAG) const {
5491   SDLoc DL(Op);
5492   MVT VT = Op.getSimpleValueType();
5493 
5494   const auto *MemSD = cast<MemSDNode>(Op);
5495   EVT MemVT = MemSD->getMemoryVT();
5496   MachineMemOperand *MMO = MemSD->getMemOperand();
5497   SDValue Chain = MemSD->getChain();
5498   SDValue BasePtr = MemSD->getBasePtr();
5499 
5500   SDValue Mask, PassThru, VL;
5501   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5502     Mask = VPLoad->getMask();
5503     PassThru = DAG.getUNDEF(VT);
5504     VL = VPLoad->getVectorLength();
5505   } else {
5506     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5507     Mask = MLoad->getMask();
5508     PassThru = MLoad->getPassThru();
5509   }
5510 
5511   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5512 
5513   MVT XLenVT = Subtarget.getXLenVT();
5514 
5515   MVT ContainerVT = VT;
5516   if (VT.isFixedLengthVector()) {
5517     ContainerVT = getContainerForFixedLengthVector(VT);
5518     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5519     if (!IsUnmasked) {
5520       MVT MaskVT =
5521           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5522       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5523     }
5524   }
5525 
5526   if (!VL)
5527     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5528 
5529   unsigned IntID =
5530       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5531   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5532   if (IsUnmasked)
5533     Ops.push_back(DAG.getUNDEF(ContainerVT));
5534   else
5535     Ops.push_back(PassThru);
5536   Ops.push_back(BasePtr);
5537   if (!IsUnmasked)
5538     Ops.push_back(Mask);
5539   Ops.push_back(VL);
5540   if (!IsUnmasked)
5541     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5542 
5543   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5544 
5545   SDValue Result =
5546       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5547   Chain = Result.getValue(1);
5548 
5549   if (VT.isFixedLengthVector())
5550     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5551 
5552   return DAG.getMergeValues({Result, Chain}, DL);
5553 }
5554 
5555 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5556                                               SelectionDAG &DAG) const {
5557   SDLoc DL(Op);
5558 
5559   const auto *MemSD = cast<MemSDNode>(Op);
5560   EVT MemVT = MemSD->getMemoryVT();
5561   MachineMemOperand *MMO = MemSD->getMemOperand();
5562   SDValue Chain = MemSD->getChain();
5563   SDValue BasePtr = MemSD->getBasePtr();
5564   SDValue Val, Mask, VL;
5565 
5566   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5567     Val = VPStore->getValue();
5568     Mask = VPStore->getMask();
5569     VL = VPStore->getVectorLength();
5570   } else {
5571     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5572     Val = MStore->getValue();
5573     Mask = MStore->getMask();
5574   }
5575 
5576   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5577 
5578   MVT VT = Val.getSimpleValueType();
5579   MVT XLenVT = Subtarget.getXLenVT();
5580 
5581   MVT ContainerVT = VT;
5582   if (VT.isFixedLengthVector()) {
5583     ContainerVT = getContainerForFixedLengthVector(VT);
5584 
5585     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5586     if (!IsUnmasked) {
5587       MVT MaskVT =
5588           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5589       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5590     }
5591   }
5592 
5593   if (!VL)
5594     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5595 
5596   unsigned IntID =
5597       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5598   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5599   Ops.push_back(Val);
5600   Ops.push_back(BasePtr);
5601   if (!IsUnmasked)
5602     Ops.push_back(Mask);
5603   Ops.push_back(VL);
5604 
5605   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5606                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5607 }
5608 
5609 SDValue
5610 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5611                                                       SelectionDAG &DAG) const {
5612   MVT InVT = Op.getOperand(0).getSimpleValueType();
5613   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5614 
5615   MVT VT = Op.getSimpleValueType();
5616 
5617   SDValue Op1 =
5618       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5619   SDValue Op2 =
5620       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5621 
5622   SDLoc DL(Op);
5623   SDValue VL =
5624       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5625 
5626   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5627   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5628 
5629   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5630                             Op.getOperand(2), Mask, VL);
5631 
5632   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5633 }
5634 
5635 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5636     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5637   MVT VT = Op.getSimpleValueType();
5638 
5639   if (VT.getVectorElementType() == MVT::i1)
5640     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5641 
5642   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5643 }
5644 
5645 SDValue
5646 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5647                                                       SelectionDAG &DAG) const {
5648   unsigned Opc;
5649   switch (Op.getOpcode()) {
5650   default: llvm_unreachable("Unexpected opcode!");
5651   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5652   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5653   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5654   }
5655 
5656   return lowerToScalableOp(Op, DAG, Opc);
5657 }
5658 
5659 // Lower vector ABS to smax(X, sub(0, X)).
5660 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5661   SDLoc DL(Op);
5662   MVT VT = Op.getSimpleValueType();
5663   SDValue X = Op.getOperand(0);
5664 
5665   assert(VT.isFixedLengthVector() && "Unexpected type");
5666 
5667   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5668   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5669 
5670   SDValue Mask, VL;
5671   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5672 
5673   SDValue SplatZero =
5674       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5675                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5676   SDValue NegX =
5677       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5678   SDValue Max =
5679       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5680 
5681   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5682 }
5683 
5684 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5685     SDValue Op, SelectionDAG &DAG) const {
5686   SDLoc DL(Op);
5687   MVT VT = Op.getSimpleValueType();
5688   SDValue Mag = Op.getOperand(0);
5689   SDValue Sign = Op.getOperand(1);
5690   assert(Mag.getValueType() == Sign.getValueType() &&
5691          "Can only handle COPYSIGN with matching types.");
5692 
5693   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5694   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5695   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5696 
5697   SDValue Mask, VL;
5698   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5699 
5700   SDValue CopySign =
5701       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5702 
5703   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5704 }
5705 
5706 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5707     SDValue Op, SelectionDAG &DAG) const {
5708   MVT VT = Op.getSimpleValueType();
5709   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5710 
5711   MVT I1ContainerVT =
5712       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5713 
5714   SDValue CC =
5715       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5716   SDValue Op1 =
5717       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5718   SDValue Op2 =
5719       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5720 
5721   SDLoc DL(Op);
5722   SDValue Mask, VL;
5723   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5724 
5725   SDValue Select =
5726       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5727 
5728   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5729 }
5730 
5731 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5732                                                unsigned NewOpc,
5733                                                bool HasMask) const {
5734   MVT VT = Op.getSimpleValueType();
5735   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5736 
5737   // Create list of operands by converting existing ones to scalable types.
5738   SmallVector<SDValue, 6> Ops;
5739   for (const SDValue &V : Op->op_values()) {
5740     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5741 
5742     // Pass through non-vector operands.
5743     if (!V.getValueType().isVector()) {
5744       Ops.push_back(V);
5745       continue;
5746     }
5747 
5748     // "cast" fixed length vector to a scalable vector.
5749     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5750            "Only fixed length vectors are supported!");
5751     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5752   }
5753 
5754   SDLoc DL(Op);
5755   SDValue Mask, VL;
5756   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5757   if (HasMask)
5758     Ops.push_back(Mask);
5759   Ops.push_back(VL);
5760 
5761   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5762   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5763 }
5764 
5765 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5766 // * Operands of each node are assumed to be in the same order.
5767 // * The EVL operand is promoted from i32 to i64 on RV64.
5768 // * Fixed-length vectors are converted to their scalable-vector container
5769 //   types.
5770 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5771                                        unsigned RISCVISDOpc) const {
5772   SDLoc DL(Op);
5773   MVT VT = Op.getSimpleValueType();
5774   SmallVector<SDValue, 4> Ops;
5775 
5776   for (const auto &OpIdx : enumerate(Op->ops())) {
5777     SDValue V = OpIdx.value();
5778     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5779     // Pass through operands which aren't fixed-length vectors.
5780     if (!V.getValueType().isFixedLengthVector()) {
5781       Ops.push_back(V);
5782       continue;
5783     }
5784     // "cast" fixed length vector to a scalable vector.
5785     MVT OpVT = V.getSimpleValueType();
5786     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5787     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5788            "Only fixed length vectors are supported!");
5789     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5790   }
5791 
5792   if (!VT.isFixedLengthVector())
5793     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5794 
5795   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5796 
5797   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5798 
5799   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5800 }
5801 
5802 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5803                                             unsigned MaskOpc,
5804                                             unsigned VecOpc) const {
5805   MVT VT = Op.getSimpleValueType();
5806   if (VT.getVectorElementType() != MVT::i1)
5807     return lowerVPOp(Op, DAG, VecOpc);
5808 
5809   // It is safe to drop mask parameter as masked-off elements are undef.
5810   SDValue Op1 = Op->getOperand(0);
5811   SDValue Op2 = Op->getOperand(1);
5812   SDValue VL = Op->getOperand(3);
5813 
5814   MVT ContainerVT = VT;
5815   const bool IsFixed = VT.isFixedLengthVector();
5816   if (IsFixed) {
5817     ContainerVT = getContainerForFixedLengthVector(VT);
5818     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5819     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5820   }
5821 
5822   SDLoc DL(Op);
5823   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5824   if (!IsFixed)
5825     return Val;
5826   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5827 }
5828 
5829 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5830 // matched to a RVV indexed load. The RVV indexed load instructions only
5831 // support the "unsigned unscaled" addressing mode; indices are implicitly
5832 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5833 // signed or scaled indexing is extended to the XLEN value type and scaled
5834 // accordingly.
5835 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5836                                                SelectionDAG &DAG) const {
5837   SDLoc DL(Op);
5838   MVT VT = Op.getSimpleValueType();
5839 
5840   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5841   EVT MemVT = MemSD->getMemoryVT();
5842   MachineMemOperand *MMO = MemSD->getMemOperand();
5843   SDValue Chain = MemSD->getChain();
5844   SDValue BasePtr = MemSD->getBasePtr();
5845 
5846   ISD::LoadExtType LoadExtType;
5847   SDValue Index, Mask, PassThru, VL;
5848 
5849   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5850     Index = VPGN->getIndex();
5851     Mask = VPGN->getMask();
5852     PassThru = DAG.getUNDEF(VT);
5853     VL = VPGN->getVectorLength();
5854     // VP doesn't support extending loads.
5855     LoadExtType = ISD::NON_EXTLOAD;
5856   } else {
5857     // Else it must be a MGATHER.
5858     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5859     Index = MGN->getIndex();
5860     Mask = MGN->getMask();
5861     PassThru = MGN->getPassThru();
5862     LoadExtType = MGN->getExtensionType();
5863   }
5864 
5865   MVT IndexVT = Index.getSimpleValueType();
5866   MVT XLenVT = Subtarget.getXLenVT();
5867 
5868   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5869          "Unexpected VTs!");
5870   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5871   // Targets have to explicitly opt-in for extending vector loads.
5872   assert(LoadExtType == ISD::NON_EXTLOAD &&
5873          "Unexpected extending MGATHER/VP_GATHER");
5874   (void)LoadExtType;
5875 
5876   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5877   // the selection of the masked intrinsics doesn't do this for us.
5878   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5879 
5880   MVT ContainerVT = VT;
5881   if (VT.isFixedLengthVector()) {
5882     // We need to use the larger of the result and index type to determine the
5883     // scalable type to use so we don't increase LMUL for any operand/result.
5884     if (VT.bitsGE(IndexVT)) {
5885       ContainerVT = getContainerForFixedLengthVector(VT);
5886       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5887                                  ContainerVT.getVectorElementCount());
5888     } else {
5889       IndexVT = getContainerForFixedLengthVector(IndexVT);
5890       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5891                                      IndexVT.getVectorElementCount());
5892     }
5893 
5894     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5895 
5896     if (!IsUnmasked) {
5897       MVT MaskVT =
5898           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5899       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5900       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5901     }
5902   }
5903 
5904   if (!VL)
5905     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5906 
5907   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5908     IndexVT = IndexVT.changeVectorElementType(XLenVT);
5909     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
5910                                    VL);
5911     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
5912                         TrueMask, VL);
5913   }
5914 
5915   unsigned IntID =
5916       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5917   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5918   if (IsUnmasked)
5919     Ops.push_back(DAG.getUNDEF(ContainerVT));
5920   else
5921     Ops.push_back(PassThru);
5922   Ops.push_back(BasePtr);
5923   Ops.push_back(Index);
5924   if (!IsUnmasked)
5925     Ops.push_back(Mask);
5926   Ops.push_back(VL);
5927   if (!IsUnmasked)
5928     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5929 
5930   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5931   SDValue Result =
5932       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5933   Chain = Result.getValue(1);
5934 
5935   if (VT.isFixedLengthVector())
5936     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5937 
5938   return DAG.getMergeValues({Result, Chain}, DL);
5939 }
5940 
5941 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5942 // matched to a RVV indexed store. The RVV indexed store instructions only
5943 // support the "unsigned unscaled" addressing mode; indices are implicitly
5944 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5945 // signed or scaled indexing is extended to the XLEN value type and scaled
5946 // accordingly.
5947 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5948                                                 SelectionDAG &DAG) const {
5949   SDLoc DL(Op);
5950   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5951   EVT MemVT = MemSD->getMemoryVT();
5952   MachineMemOperand *MMO = MemSD->getMemOperand();
5953   SDValue Chain = MemSD->getChain();
5954   SDValue BasePtr = MemSD->getBasePtr();
5955 
5956   bool IsTruncatingStore = false;
5957   SDValue Index, Mask, Val, VL;
5958 
5959   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5960     Index = VPSN->getIndex();
5961     Mask = VPSN->getMask();
5962     Val = VPSN->getValue();
5963     VL = VPSN->getVectorLength();
5964     // VP doesn't support truncating stores.
5965     IsTruncatingStore = false;
5966   } else {
5967     // Else it must be a MSCATTER.
5968     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5969     Index = MSN->getIndex();
5970     Mask = MSN->getMask();
5971     Val = MSN->getValue();
5972     IsTruncatingStore = MSN->isTruncatingStore();
5973   }
5974 
5975   MVT VT = Val.getSimpleValueType();
5976   MVT IndexVT = Index.getSimpleValueType();
5977   MVT XLenVT = Subtarget.getXLenVT();
5978 
5979   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5980          "Unexpected VTs!");
5981   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5982   // Targets have to explicitly opt-in for extending vector loads and
5983   // truncating vector stores.
5984   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5985   (void)IsTruncatingStore;
5986 
5987   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5988   // the selection of the masked intrinsics doesn't do this for us.
5989   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5990 
5991   MVT ContainerVT = VT;
5992   if (VT.isFixedLengthVector()) {
5993     // We need to use the larger of the value and index type to determine the
5994     // scalable type to use so we don't increase LMUL for any operand/result.
5995     if (VT.bitsGE(IndexVT)) {
5996       ContainerVT = getContainerForFixedLengthVector(VT);
5997       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5998                                  ContainerVT.getVectorElementCount());
5999     } else {
6000       IndexVT = getContainerForFixedLengthVector(IndexVT);
6001       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6002                                      IndexVT.getVectorElementCount());
6003     }
6004 
6005     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6006     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6007 
6008     if (!IsUnmasked) {
6009       MVT MaskVT =
6010           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6011       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6012     }
6013   }
6014 
6015   if (!VL)
6016     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6017 
6018   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6019     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6020     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6021                                    VL);
6022     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6023                         TrueMask, VL);
6024   }
6025 
6026   unsigned IntID =
6027       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6028   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6029   Ops.push_back(Val);
6030   Ops.push_back(BasePtr);
6031   Ops.push_back(Index);
6032   if (!IsUnmasked)
6033     Ops.push_back(Mask);
6034   Ops.push_back(VL);
6035 
6036   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6037                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6038 }
6039 
6040 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6041                                                SelectionDAG &DAG) const {
6042   const MVT XLenVT = Subtarget.getXLenVT();
6043   SDLoc DL(Op);
6044   SDValue Chain = Op->getOperand(0);
6045   SDValue SysRegNo = DAG.getTargetConstant(
6046       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6047   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6048   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6049 
6050   // Encoding used for rounding mode in RISCV differs from that used in
6051   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6052   // table, which consists of a sequence of 4-bit fields, each representing
6053   // corresponding FLT_ROUNDS mode.
6054   static const int Table =
6055       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6056       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6057       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6058       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6059       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6060 
6061   SDValue Shift =
6062       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6063   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6064                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6065   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6066                                DAG.getConstant(7, DL, XLenVT));
6067 
6068   return DAG.getMergeValues({Masked, Chain}, DL);
6069 }
6070 
6071 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6072                                                SelectionDAG &DAG) const {
6073   const MVT XLenVT = Subtarget.getXLenVT();
6074   SDLoc DL(Op);
6075   SDValue Chain = Op->getOperand(0);
6076   SDValue RMValue = Op->getOperand(1);
6077   SDValue SysRegNo = DAG.getTargetConstant(
6078       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6079 
6080   // Encoding used for rounding mode in RISCV differs from that used in
6081   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6082   // a table, which consists of a sequence of 4-bit fields, each representing
6083   // corresponding RISCV mode.
6084   static const unsigned Table =
6085       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6086       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6087       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6088       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6089       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6090 
6091   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6092                               DAG.getConstant(2, DL, XLenVT));
6093   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6094                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6095   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6096                         DAG.getConstant(0x7, DL, XLenVT));
6097   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6098                      RMValue);
6099 }
6100 
6101 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6102   switch (IntNo) {
6103   default:
6104     llvm_unreachable("Unexpected Intrinsic");
6105   case Intrinsic::riscv_grev:
6106     return RISCVISD::GREVW;
6107   case Intrinsic::riscv_gorc:
6108     return RISCVISD::GORCW;
6109   case Intrinsic::riscv_bcompress:
6110     return RISCVISD::BCOMPRESSW;
6111   case Intrinsic::riscv_bdecompress:
6112     return RISCVISD::BDECOMPRESSW;
6113   case Intrinsic::riscv_bfp:
6114     return RISCVISD::BFPW;
6115   case Intrinsic::riscv_fsl:
6116     return RISCVISD::FSLW;
6117   case Intrinsic::riscv_fsr:
6118     return RISCVISD::FSRW;
6119   }
6120 }
6121 
6122 // Converts the given intrinsic to a i64 operation with any extension.
6123 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6124                                          unsigned IntNo) {
6125   SDLoc DL(N);
6126   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6127   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6128   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6129   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6130   // ReplaceNodeResults requires we maintain the same type for the return value.
6131   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6132 }
6133 
6134 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6135 // form of the given Opcode.
6136 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6137   switch (Opcode) {
6138   default:
6139     llvm_unreachable("Unexpected opcode");
6140   case ISD::SHL:
6141     return RISCVISD::SLLW;
6142   case ISD::SRA:
6143     return RISCVISD::SRAW;
6144   case ISD::SRL:
6145     return RISCVISD::SRLW;
6146   case ISD::SDIV:
6147     return RISCVISD::DIVW;
6148   case ISD::UDIV:
6149     return RISCVISD::DIVUW;
6150   case ISD::UREM:
6151     return RISCVISD::REMUW;
6152   case ISD::ROTL:
6153     return RISCVISD::ROLW;
6154   case ISD::ROTR:
6155     return RISCVISD::RORW;
6156   case RISCVISD::GREV:
6157     return RISCVISD::GREVW;
6158   case RISCVISD::GORC:
6159     return RISCVISD::GORCW;
6160   }
6161 }
6162 
6163 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6164 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6165 // otherwise be promoted to i64, making it difficult to select the
6166 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6167 // type i8/i16/i32 is lost.
6168 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6169                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6170   SDLoc DL(N);
6171   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6172   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6173   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6174   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6175   // ReplaceNodeResults requires we maintain the same type for the return value.
6176   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6177 }
6178 
6179 // Converts the given 32-bit operation to a i64 operation with signed extension
6180 // semantic to reduce the signed extension instructions.
6181 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6182   SDLoc DL(N);
6183   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6184   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6185   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6186   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6187                                DAG.getValueType(MVT::i32));
6188   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6189 }
6190 
6191 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6192                                              SmallVectorImpl<SDValue> &Results,
6193                                              SelectionDAG &DAG) const {
6194   SDLoc DL(N);
6195   switch (N->getOpcode()) {
6196   default:
6197     llvm_unreachable("Don't know how to custom type legalize this operation!");
6198   case ISD::STRICT_FP_TO_SINT:
6199   case ISD::STRICT_FP_TO_UINT:
6200   case ISD::FP_TO_SINT:
6201   case ISD::FP_TO_UINT: {
6202     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6203            "Unexpected custom legalisation");
6204     bool IsStrict = N->isStrictFPOpcode();
6205     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6206                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6207     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6208     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6209         TargetLowering::TypeSoftenFloat) {
6210       if (!isTypeLegal(Op0.getValueType()))
6211         return;
6212       if (IsStrict) {
6213         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6214                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6215         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6216         SDValue Res = DAG.getNode(
6217             Opc, DL, VTs, N->getOperand(0), Op0,
6218             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6219         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6220         Results.push_back(Res.getValue(1));
6221         return;
6222       }
6223       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6224       SDValue Res =
6225           DAG.getNode(Opc, DL, MVT::i64, Op0,
6226                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6227       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6228       return;
6229     }
6230     // If the FP type needs to be softened, emit a library call using the 'si'
6231     // version. If we left it to default legalization we'd end up with 'di'. If
6232     // the FP type doesn't need to be softened just let generic type
6233     // legalization promote the result type.
6234     RTLIB::Libcall LC;
6235     if (IsSigned)
6236       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6237     else
6238       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6239     MakeLibCallOptions CallOptions;
6240     EVT OpVT = Op0.getValueType();
6241     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6242     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6243     SDValue Result;
6244     std::tie(Result, Chain) =
6245         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6246     Results.push_back(Result);
6247     if (IsStrict)
6248       Results.push_back(Chain);
6249     break;
6250   }
6251   case ISD::READCYCLECOUNTER: {
6252     assert(!Subtarget.is64Bit() &&
6253            "READCYCLECOUNTER only has custom type legalization on riscv32");
6254 
6255     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6256     SDValue RCW =
6257         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6258 
6259     Results.push_back(
6260         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6261     Results.push_back(RCW.getValue(2));
6262     break;
6263   }
6264   case ISD::MUL: {
6265     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6266     unsigned XLen = Subtarget.getXLen();
6267     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6268     if (Size > XLen) {
6269       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6270       SDValue LHS = N->getOperand(0);
6271       SDValue RHS = N->getOperand(1);
6272       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6273 
6274       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6275       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6276       // We need exactly one side to be unsigned.
6277       if (LHSIsU == RHSIsU)
6278         return;
6279 
6280       auto MakeMULPair = [&](SDValue S, SDValue U) {
6281         MVT XLenVT = Subtarget.getXLenVT();
6282         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6283         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6284         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6285         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6286         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6287       };
6288 
6289       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6290       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6291 
6292       // The other operand should be signed, but still prefer MULH when
6293       // possible.
6294       if (RHSIsU && LHSIsS && !RHSIsS)
6295         Results.push_back(MakeMULPair(LHS, RHS));
6296       else if (LHSIsU && RHSIsS && !LHSIsS)
6297         Results.push_back(MakeMULPair(RHS, LHS));
6298 
6299       return;
6300     }
6301     LLVM_FALLTHROUGH;
6302   }
6303   case ISD::ADD:
6304   case ISD::SUB:
6305     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6306            "Unexpected custom legalisation");
6307     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6308     break;
6309   case ISD::SHL:
6310   case ISD::SRA:
6311   case ISD::SRL:
6312     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6313            "Unexpected custom legalisation");
6314     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6315       Results.push_back(customLegalizeToWOp(N, DAG));
6316       break;
6317     }
6318 
6319     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6320     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6321     // shift amount.
6322     if (N->getOpcode() == ISD::SHL) {
6323       SDLoc DL(N);
6324       SDValue NewOp0 =
6325           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6326       SDValue NewOp1 =
6327           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6328       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6329       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6330                                    DAG.getValueType(MVT::i32));
6331       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6332     }
6333 
6334     break;
6335   case ISD::ROTL:
6336   case ISD::ROTR:
6337     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6338            "Unexpected custom legalisation");
6339     Results.push_back(customLegalizeToWOp(N, DAG));
6340     break;
6341   case ISD::CTTZ:
6342   case ISD::CTTZ_ZERO_UNDEF:
6343   case ISD::CTLZ:
6344   case ISD::CTLZ_ZERO_UNDEF: {
6345     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6346            "Unexpected custom legalisation");
6347 
6348     SDValue NewOp0 =
6349         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6350     bool IsCTZ =
6351         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6352     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6353     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6354     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6355     return;
6356   }
6357   case ISD::SDIV:
6358   case ISD::UDIV:
6359   case ISD::UREM: {
6360     MVT VT = N->getSimpleValueType(0);
6361     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6362            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6363            "Unexpected custom legalisation");
6364     // Don't promote division/remainder by constant since we should expand those
6365     // to multiply by magic constant.
6366     // FIXME: What if the expansion is disabled for minsize.
6367     if (N->getOperand(1).getOpcode() == ISD::Constant)
6368       return;
6369 
6370     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6371     // the upper 32 bits. For other types we need to sign or zero extend
6372     // based on the opcode.
6373     unsigned ExtOpc = ISD::ANY_EXTEND;
6374     if (VT != MVT::i32)
6375       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6376                                            : ISD::ZERO_EXTEND;
6377 
6378     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6379     break;
6380   }
6381   case ISD::UADDO:
6382   case ISD::USUBO: {
6383     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6384            "Unexpected custom legalisation");
6385     bool IsAdd = N->getOpcode() == ISD::UADDO;
6386     // Create an ADDW or SUBW.
6387     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6388     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6389     SDValue Res =
6390         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6391     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6392                       DAG.getValueType(MVT::i32));
6393 
6394     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6395     // Since the inputs are sign extended from i32, this is equivalent to
6396     // comparing the lower 32 bits.
6397     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6398     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6399                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6400 
6401     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6402     Results.push_back(Overflow);
6403     return;
6404   }
6405   case ISD::UADDSAT:
6406   case ISD::USUBSAT: {
6407     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6408            "Unexpected custom legalisation");
6409     if (Subtarget.hasStdExtZbb()) {
6410       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6411       // sign extend allows overflow of the lower 32 bits to be detected on
6412       // the promoted size.
6413       SDValue LHS =
6414           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6415       SDValue RHS =
6416           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6417       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6418       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6419       return;
6420     }
6421 
6422     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6423     // promotion for UADDO/USUBO.
6424     Results.push_back(expandAddSubSat(N, DAG));
6425     return;
6426   }
6427   case ISD::BITCAST: {
6428     EVT VT = N->getValueType(0);
6429     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6430     SDValue Op0 = N->getOperand(0);
6431     EVT Op0VT = Op0.getValueType();
6432     MVT XLenVT = Subtarget.getXLenVT();
6433     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6434       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6435       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6436     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6437                Subtarget.hasStdExtF()) {
6438       SDValue FPConv =
6439           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6440       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6441     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6442                isTypeLegal(Op0VT)) {
6443       // Custom-legalize bitcasts from fixed-length vector types to illegal
6444       // scalar types in order to improve codegen. Bitcast the vector to a
6445       // one-element vector type whose element type is the same as the result
6446       // type, and extract the first element.
6447       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6448       if (isTypeLegal(BVT)) {
6449         SDValue BVec = DAG.getBitcast(BVT, Op0);
6450         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6451                                       DAG.getConstant(0, DL, XLenVT)));
6452       }
6453     }
6454     break;
6455   }
6456   case RISCVISD::GREV:
6457   case RISCVISD::GORC: {
6458     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6459            "Unexpected custom legalisation");
6460     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6461     // This is similar to customLegalizeToWOp, except that we pass the second
6462     // operand (a TargetConstant) straight through: it is already of type
6463     // XLenVT.
6464     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6465     SDValue NewOp0 =
6466         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6467     SDValue NewOp1 =
6468         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6469     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6470     // ReplaceNodeResults requires we maintain the same type for the return
6471     // value.
6472     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6473     break;
6474   }
6475   case RISCVISD::SHFL: {
6476     // There is no SHFLIW instruction, but we can just promote the operation.
6477     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6478            "Unexpected custom legalisation");
6479     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6480     SDValue NewOp0 =
6481         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6482     SDValue NewOp1 =
6483         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6484     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6485     // ReplaceNodeResults requires we maintain the same type for the return
6486     // value.
6487     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6488     break;
6489   }
6490   case ISD::BSWAP:
6491   case ISD::BITREVERSE: {
6492     MVT VT = N->getSimpleValueType(0);
6493     MVT XLenVT = Subtarget.getXLenVT();
6494     assert((VT == MVT::i8 || VT == MVT::i16 ||
6495             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6496            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6497     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6498     unsigned Imm = VT.getSizeInBits() - 1;
6499     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6500     if (N->getOpcode() == ISD::BSWAP)
6501       Imm &= ~0x7U;
6502     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6503     SDValue GREVI =
6504         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6505     // ReplaceNodeResults requires we maintain the same type for the return
6506     // value.
6507     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6508     break;
6509   }
6510   case ISD::FSHL:
6511   case ISD::FSHR: {
6512     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6513            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6514     SDValue NewOp0 =
6515         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6516     SDValue NewOp1 =
6517         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6518     SDValue NewShAmt =
6519         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6520     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6521     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6522     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6523                            DAG.getConstant(0x1f, DL, MVT::i64));
6524     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6525     // instruction use different orders. fshl will return its first operand for
6526     // shift of zero, fshr will return its second operand. fsl and fsr both
6527     // return rs1 so the ISD nodes need to have different operand orders.
6528     // Shift amount is in rs2.
6529     unsigned Opc = RISCVISD::FSLW;
6530     if (N->getOpcode() == ISD::FSHR) {
6531       std::swap(NewOp0, NewOp1);
6532       Opc = RISCVISD::FSRW;
6533     }
6534     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6535     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6536     break;
6537   }
6538   case ISD::EXTRACT_VECTOR_ELT: {
6539     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6540     // type is illegal (currently only vXi64 RV32).
6541     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6542     // transferred to the destination register. We issue two of these from the
6543     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6544     // first element.
6545     SDValue Vec = N->getOperand(0);
6546     SDValue Idx = N->getOperand(1);
6547 
6548     // The vector type hasn't been legalized yet so we can't issue target
6549     // specific nodes if it needs legalization.
6550     // FIXME: We would manually legalize if it's important.
6551     if (!isTypeLegal(Vec.getValueType()))
6552       return;
6553 
6554     MVT VecVT = Vec.getSimpleValueType();
6555 
6556     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6557            VecVT.getVectorElementType() == MVT::i64 &&
6558            "Unexpected EXTRACT_VECTOR_ELT legalization");
6559 
6560     // If this is a fixed vector, we need to convert it to a scalable vector.
6561     MVT ContainerVT = VecVT;
6562     if (VecVT.isFixedLengthVector()) {
6563       ContainerVT = getContainerForFixedLengthVector(VecVT);
6564       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6565     }
6566 
6567     MVT XLenVT = Subtarget.getXLenVT();
6568 
6569     // Use a VL of 1 to avoid processing more elements than we need.
6570     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6571     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6572     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6573 
6574     // Unless the index is known to be 0, we must slide the vector down to get
6575     // the desired element into index 0.
6576     if (!isNullConstant(Idx)) {
6577       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6578                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6579     }
6580 
6581     // Extract the lower XLEN bits of the correct vector element.
6582     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6583 
6584     // To extract the upper XLEN bits of the vector element, shift the first
6585     // element right by 32 bits and re-extract the lower XLEN bits.
6586     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6587                                      DAG.getConstant(32, DL, XLenVT), VL);
6588     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6589                                  ThirtyTwoV, Mask, VL);
6590 
6591     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6592 
6593     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6594     break;
6595   }
6596   case ISD::INTRINSIC_WO_CHAIN: {
6597     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6598     switch (IntNo) {
6599     default:
6600       llvm_unreachable(
6601           "Don't know how to custom type legalize this intrinsic!");
6602     case Intrinsic::riscv_grev:
6603     case Intrinsic::riscv_gorc:
6604     case Intrinsic::riscv_bcompress:
6605     case Intrinsic::riscv_bdecompress:
6606     case Intrinsic::riscv_bfp: {
6607       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6608              "Unexpected custom legalisation");
6609       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6610       break;
6611     }
6612     case Intrinsic::riscv_fsl:
6613     case Intrinsic::riscv_fsr: {
6614       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6615              "Unexpected custom legalisation");
6616       SDValue NewOp1 =
6617           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6618       SDValue NewOp2 =
6619           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6620       SDValue NewOp3 =
6621           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6622       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6623       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6624       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6625       break;
6626     }
6627     case Intrinsic::riscv_orc_b: {
6628       // Lower to the GORCI encoding for orc.b with the operand extended.
6629       SDValue NewOp =
6630           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6631       // If Zbp is enabled, use GORCIW which will sign extend the result.
6632       unsigned Opc =
6633           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6634       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6635                                 DAG.getConstant(7, DL, MVT::i64));
6636       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6637       return;
6638     }
6639     case Intrinsic::riscv_shfl:
6640     case Intrinsic::riscv_unshfl: {
6641       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6642              "Unexpected custom legalisation");
6643       SDValue NewOp1 =
6644           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6645       SDValue NewOp2 =
6646           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6647       unsigned Opc =
6648           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6649       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6650       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6651       // will be shuffled the same way as the lower 32 bit half, but the two
6652       // halves won't cross.
6653       if (isa<ConstantSDNode>(NewOp2)) {
6654         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6655                              DAG.getConstant(0xf, DL, MVT::i64));
6656         Opc =
6657             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6658       }
6659       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6660       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6661       break;
6662     }
6663     case Intrinsic::riscv_vmv_x_s: {
6664       EVT VT = N->getValueType(0);
6665       MVT XLenVT = Subtarget.getXLenVT();
6666       if (VT.bitsLT(XLenVT)) {
6667         // Simple case just extract using vmv.x.s and truncate.
6668         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6669                                       Subtarget.getXLenVT(), N->getOperand(1));
6670         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6671         return;
6672       }
6673 
6674       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6675              "Unexpected custom legalization");
6676 
6677       // We need to do the move in two steps.
6678       SDValue Vec = N->getOperand(1);
6679       MVT VecVT = Vec.getSimpleValueType();
6680 
6681       // First extract the lower XLEN bits of the element.
6682       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6683 
6684       // To extract the upper XLEN bits of the vector element, shift the first
6685       // element right by 32 bits and re-extract the lower XLEN bits.
6686       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6687       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6688       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6689       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6690                                        DAG.getConstant(32, DL, XLenVT), VL);
6691       SDValue LShr32 =
6692           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6693       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6694 
6695       Results.push_back(
6696           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6697       break;
6698     }
6699     }
6700     break;
6701   }
6702   case ISD::VECREDUCE_ADD:
6703   case ISD::VECREDUCE_AND:
6704   case ISD::VECREDUCE_OR:
6705   case ISD::VECREDUCE_XOR:
6706   case ISD::VECREDUCE_SMAX:
6707   case ISD::VECREDUCE_UMAX:
6708   case ISD::VECREDUCE_SMIN:
6709   case ISD::VECREDUCE_UMIN:
6710     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6711       Results.push_back(V);
6712     break;
6713   case ISD::VP_REDUCE_ADD:
6714   case ISD::VP_REDUCE_AND:
6715   case ISD::VP_REDUCE_OR:
6716   case ISD::VP_REDUCE_XOR:
6717   case ISD::VP_REDUCE_SMAX:
6718   case ISD::VP_REDUCE_UMAX:
6719   case ISD::VP_REDUCE_SMIN:
6720   case ISD::VP_REDUCE_UMIN:
6721     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6722       Results.push_back(V);
6723     break;
6724   case ISD::FLT_ROUNDS_: {
6725     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6726     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6727     Results.push_back(Res.getValue(0));
6728     Results.push_back(Res.getValue(1));
6729     break;
6730   }
6731   }
6732 }
6733 
6734 // A structure to hold one of the bit-manipulation patterns below. Together, a
6735 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6736 //   (or (and (shl x, 1), 0xAAAAAAAA),
6737 //       (and (srl x, 1), 0x55555555))
6738 struct RISCVBitmanipPat {
6739   SDValue Op;
6740   unsigned ShAmt;
6741   bool IsSHL;
6742 
6743   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6744     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6745   }
6746 };
6747 
6748 // Matches patterns of the form
6749 //   (and (shl x, C2), (C1 << C2))
6750 //   (and (srl x, C2), C1)
6751 //   (shl (and x, C1), C2)
6752 //   (srl (and x, (C1 << C2)), C2)
6753 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6754 // The expected masks for each shift amount are specified in BitmanipMasks where
6755 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6756 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6757 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6758 // XLen is 64.
6759 static Optional<RISCVBitmanipPat>
6760 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6761   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6762          "Unexpected number of masks");
6763   Optional<uint64_t> Mask;
6764   // Optionally consume a mask around the shift operation.
6765   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6766     Mask = Op.getConstantOperandVal(1);
6767     Op = Op.getOperand(0);
6768   }
6769   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6770     return None;
6771   bool IsSHL = Op.getOpcode() == ISD::SHL;
6772 
6773   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6774     return None;
6775   uint64_t ShAmt = Op.getConstantOperandVal(1);
6776 
6777   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6778   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6779     return None;
6780   // If we don't have enough masks for 64 bit, then we must be trying to
6781   // match SHFL so we're only allowed to shift 1/4 of the width.
6782   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6783     return None;
6784 
6785   SDValue Src = Op.getOperand(0);
6786 
6787   // The expected mask is shifted left when the AND is found around SHL
6788   // patterns.
6789   //   ((x >> 1) & 0x55555555)
6790   //   ((x << 1) & 0xAAAAAAAA)
6791   bool SHLExpMask = IsSHL;
6792 
6793   if (!Mask) {
6794     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6795     // the mask is all ones: consume that now.
6796     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6797       Mask = Src.getConstantOperandVal(1);
6798       Src = Src.getOperand(0);
6799       // The expected mask is now in fact shifted left for SRL, so reverse the
6800       // decision.
6801       //   ((x & 0xAAAAAAAA) >> 1)
6802       //   ((x & 0x55555555) << 1)
6803       SHLExpMask = !SHLExpMask;
6804     } else {
6805       // Use a default shifted mask of all-ones if there's no AND, truncated
6806       // down to the expected width. This simplifies the logic later on.
6807       Mask = maskTrailingOnes<uint64_t>(Width);
6808       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6809     }
6810   }
6811 
6812   unsigned MaskIdx = Log2_32(ShAmt);
6813   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6814 
6815   if (SHLExpMask)
6816     ExpMask <<= ShAmt;
6817 
6818   if (Mask != ExpMask)
6819     return None;
6820 
6821   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6822 }
6823 
6824 // Matches any of the following bit-manipulation patterns:
6825 //   (and (shl x, 1), (0x55555555 << 1))
6826 //   (and (srl x, 1), 0x55555555)
6827 //   (shl (and x, 0x55555555), 1)
6828 //   (srl (and x, (0x55555555 << 1)), 1)
6829 // where the shift amount and mask may vary thus:
6830 //   [1]  = 0x55555555 / 0xAAAAAAAA
6831 //   [2]  = 0x33333333 / 0xCCCCCCCC
6832 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6833 //   [8]  = 0x00FF00FF / 0xFF00FF00
6834 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6835 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6836 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6837   // These are the unshifted masks which we use to match bit-manipulation
6838   // patterns. They may be shifted left in certain circumstances.
6839   static const uint64_t BitmanipMasks[] = {
6840       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6841       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6842 
6843   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6844 }
6845 
6846 // Match the following pattern as a GREVI(W) operation
6847 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6848 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6849                                const RISCVSubtarget &Subtarget) {
6850   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6851   EVT VT = Op.getValueType();
6852 
6853   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6854     auto LHS = matchGREVIPat(Op.getOperand(0));
6855     auto RHS = matchGREVIPat(Op.getOperand(1));
6856     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6857       SDLoc DL(Op);
6858       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6859                          DAG.getConstant(LHS->ShAmt, DL, VT));
6860     }
6861   }
6862   return SDValue();
6863 }
6864 
6865 // Matches any the following pattern as a GORCI(W) operation
6866 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6867 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6868 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6869 // Note that with the variant of 3.,
6870 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6871 // the inner pattern will first be matched as GREVI and then the outer
6872 // pattern will be matched to GORC via the first rule above.
6873 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6874 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6875                                const RISCVSubtarget &Subtarget) {
6876   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6877   EVT VT = Op.getValueType();
6878 
6879   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6880     SDLoc DL(Op);
6881     SDValue Op0 = Op.getOperand(0);
6882     SDValue Op1 = Op.getOperand(1);
6883 
6884     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6885       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6886           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6887           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6888         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6889       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6890       if ((Reverse.getOpcode() == ISD::ROTL ||
6891            Reverse.getOpcode() == ISD::ROTR) &&
6892           Reverse.getOperand(0) == X &&
6893           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6894         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6895         if (RotAmt == (VT.getSizeInBits() / 2))
6896           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6897                              DAG.getConstant(RotAmt, DL, VT));
6898       }
6899       return SDValue();
6900     };
6901 
6902     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6903     if (SDValue V = MatchOROfReverse(Op0, Op1))
6904       return V;
6905     if (SDValue V = MatchOROfReverse(Op1, Op0))
6906       return V;
6907 
6908     // OR is commutable so canonicalize its OR operand to the left
6909     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6910       std::swap(Op0, Op1);
6911     if (Op0.getOpcode() != ISD::OR)
6912       return SDValue();
6913     SDValue OrOp0 = Op0.getOperand(0);
6914     SDValue OrOp1 = Op0.getOperand(1);
6915     auto LHS = matchGREVIPat(OrOp0);
6916     // OR is commutable so swap the operands and try again: x might have been
6917     // on the left
6918     if (!LHS) {
6919       std::swap(OrOp0, OrOp1);
6920       LHS = matchGREVIPat(OrOp0);
6921     }
6922     auto RHS = matchGREVIPat(Op1);
6923     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6924       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6925                          DAG.getConstant(LHS->ShAmt, DL, VT));
6926     }
6927   }
6928   return SDValue();
6929 }
6930 
6931 // Matches any of the following bit-manipulation patterns:
6932 //   (and (shl x, 1), (0x22222222 << 1))
6933 //   (and (srl x, 1), 0x22222222)
6934 //   (shl (and x, 0x22222222), 1)
6935 //   (srl (and x, (0x22222222 << 1)), 1)
6936 // where the shift amount and mask may vary thus:
6937 //   [1]  = 0x22222222 / 0x44444444
6938 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6939 //   [4]  = 0x00F000F0 / 0x0F000F00
6940 //   [8]  = 0x0000FF00 / 0x00FF0000
6941 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6942 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6943   // These are the unshifted masks which we use to match bit-manipulation
6944   // patterns. They may be shifted left in certain circumstances.
6945   static const uint64_t BitmanipMasks[] = {
6946       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6947       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6948 
6949   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6950 }
6951 
6952 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6953 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6954                                const RISCVSubtarget &Subtarget) {
6955   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6956   EVT VT = Op.getValueType();
6957 
6958   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6959     return SDValue();
6960 
6961   SDValue Op0 = Op.getOperand(0);
6962   SDValue Op1 = Op.getOperand(1);
6963 
6964   // Or is commutable so canonicalize the second OR to the LHS.
6965   if (Op0.getOpcode() != ISD::OR)
6966     std::swap(Op0, Op1);
6967   if (Op0.getOpcode() != ISD::OR)
6968     return SDValue();
6969 
6970   // We found an inner OR, so our operands are the operands of the inner OR
6971   // and the other operand of the outer OR.
6972   SDValue A = Op0.getOperand(0);
6973   SDValue B = Op0.getOperand(1);
6974   SDValue C = Op1;
6975 
6976   auto Match1 = matchSHFLPat(A);
6977   auto Match2 = matchSHFLPat(B);
6978 
6979   // If neither matched, we failed.
6980   if (!Match1 && !Match2)
6981     return SDValue();
6982 
6983   // We had at least one match. if one failed, try the remaining C operand.
6984   if (!Match1) {
6985     std::swap(A, C);
6986     Match1 = matchSHFLPat(A);
6987     if (!Match1)
6988       return SDValue();
6989   } else if (!Match2) {
6990     std::swap(B, C);
6991     Match2 = matchSHFLPat(B);
6992     if (!Match2)
6993       return SDValue();
6994   }
6995   assert(Match1 && Match2);
6996 
6997   // Make sure our matches pair up.
6998   if (!Match1->formsPairWith(*Match2))
6999     return SDValue();
7000 
7001   // All the remains is to make sure C is an AND with the same input, that masks
7002   // out the bits that are being shuffled.
7003   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7004       C.getOperand(0) != Match1->Op)
7005     return SDValue();
7006 
7007   uint64_t Mask = C.getConstantOperandVal(1);
7008 
7009   static const uint64_t BitmanipMasks[] = {
7010       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7011       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7012   };
7013 
7014   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7015   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7016   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7017 
7018   if (Mask != ExpMask)
7019     return SDValue();
7020 
7021   SDLoc DL(Op);
7022   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7023                      DAG.getConstant(Match1->ShAmt, DL, VT));
7024 }
7025 
7026 // Optimize (add (shl x, c0), (shl y, c1)) ->
7027 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7028 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7029                                   const RISCVSubtarget &Subtarget) {
7030   // Perform this optimization only in the zba extension.
7031   if (!Subtarget.hasStdExtZba())
7032     return SDValue();
7033 
7034   // Skip for vector types and larger types.
7035   EVT VT = N->getValueType(0);
7036   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7037     return SDValue();
7038 
7039   // The two operand nodes must be SHL and have no other use.
7040   SDValue N0 = N->getOperand(0);
7041   SDValue N1 = N->getOperand(1);
7042   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7043       !N0->hasOneUse() || !N1->hasOneUse())
7044     return SDValue();
7045 
7046   // Check c0 and c1.
7047   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7048   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7049   if (!N0C || !N1C)
7050     return SDValue();
7051   int64_t C0 = N0C->getSExtValue();
7052   int64_t C1 = N1C->getSExtValue();
7053   if (C0 <= 0 || C1 <= 0)
7054     return SDValue();
7055 
7056   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7057   int64_t Bits = std::min(C0, C1);
7058   int64_t Diff = std::abs(C0 - C1);
7059   if (Diff != 1 && Diff != 2 && Diff != 3)
7060     return SDValue();
7061 
7062   // Build nodes.
7063   SDLoc DL(N);
7064   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7065   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7066   SDValue NA0 =
7067       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7068   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7069   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7070 }
7071 
7072 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7073 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7074 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7075 // not undo itself, but they are redundant.
7076 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7077   SDValue Src = N->getOperand(0);
7078 
7079   if (Src.getOpcode() != N->getOpcode())
7080     return SDValue();
7081 
7082   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7083       !isa<ConstantSDNode>(Src.getOperand(1)))
7084     return SDValue();
7085 
7086   unsigned ShAmt1 = N->getConstantOperandVal(1);
7087   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7088   Src = Src.getOperand(0);
7089 
7090   unsigned CombinedShAmt;
7091   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7092     CombinedShAmt = ShAmt1 | ShAmt2;
7093   else
7094     CombinedShAmt = ShAmt1 ^ ShAmt2;
7095 
7096   if (CombinedShAmt == 0)
7097     return Src;
7098 
7099   SDLoc DL(N);
7100   return DAG.getNode(
7101       N->getOpcode(), DL, N->getValueType(0), Src,
7102       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7103 }
7104 
7105 // Combine a constant select operand into its use:
7106 //
7107 // (and (select cond, -1, c), x)
7108 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7109 // (or  (select cond, 0, c), x)
7110 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7111 // (xor (select cond, 0, c), x)
7112 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7113 // (add (select cond, 0, c), x)
7114 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7115 // (sub x, (select cond, 0, c))
7116 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7117 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7118                                    SelectionDAG &DAG, bool AllOnes) {
7119   EVT VT = N->getValueType(0);
7120 
7121   // Skip vectors.
7122   if (VT.isVector())
7123     return SDValue();
7124 
7125   if ((Slct.getOpcode() != ISD::SELECT &&
7126        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7127       !Slct.hasOneUse())
7128     return SDValue();
7129 
7130   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7131     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7132   };
7133 
7134   bool SwapSelectOps;
7135   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7136   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7137   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7138   SDValue NonConstantVal;
7139   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7140     SwapSelectOps = false;
7141     NonConstantVal = FalseVal;
7142   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7143     SwapSelectOps = true;
7144     NonConstantVal = TrueVal;
7145   } else
7146     return SDValue();
7147 
7148   // Slct is now know to be the desired identity constant when CC is true.
7149   TrueVal = OtherOp;
7150   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7151   // Unless SwapSelectOps says the condition should be false.
7152   if (SwapSelectOps)
7153     std::swap(TrueVal, FalseVal);
7154 
7155   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7156     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7157                        {Slct.getOperand(0), Slct.getOperand(1),
7158                         Slct.getOperand(2), TrueVal, FalseVal});
7159 
7160   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7161                      {Slct.getOperand(0), TrueVal, FalseVal});
7162 }
7163 
7164 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7165 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7166                                               bool AllOnes) {
7167   SDValue N0 = N->getOperand(0);
7168   SDValue N1 = N->getOperand(1);
7169   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7170     return Result;
7171   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7172     return Result;
7173   return SDValue();
7174 }
7175 
7176 // Transform (add (mul x, c0), c1) ->
7177 //           (add (mul (add x, c1/c0), c0), c1%c0).
7178 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7179 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7180 // to an infinite loop in DAGCombine if transformed.
7181 // Or transform (add (mul x, c0), c1) ->
7182 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7183 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7184 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7185 // lead to an infinite loop in DAGCombine if transformed.
7186 // Or transform (add (mul x, c0), c1) ->
7187 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7188 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7189 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7190 // lead to an infinite loop in DAGCombine if transformed.
7191 // Or transform (add (mul x, c0), c1) ->
7192 //              (mul (add x, c1/c0), c0).
7193 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7194 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7195                                      const RISCVSubtarget &Subtarget) {
7196   // Skip for vector types and larger types.
7197   EVT VT = N->getValueType(0);
7198   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7199     return SDValue();
7200   // The first operand node must be a MUL and has no other use.
7201   SDValue N0 = N->getOperand(0);
7202   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7203     return SDValue();
7204   // Check if c0 and c1 match above conditions.
7205   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7206   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7207   if (!N0C || !N1C)
7208     return SDValue();
7209   int64_t C0 = N0C->getSExtValue();
7210   int64_t C1 = N1C->getSExtValue();
7211   int64_t CA, CB;
7212   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7213     return SDValue();
7214   // Search for proper CA (non-zero) and CB that both are simm12.
7215   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7216       !isInt<12>(C0 * (C1 / C0))) {
7217     CA = C1 / C0;
7218     CB = C1 % C0;
7219   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7220              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7221     CA = C1 / C0 + 1;
7222     CB = C1 % C0 - C0;
7223   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7224              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7225     CA = C1 / C0 - 1;
7226     CB = C1 % C0 + C0;
7227   } else
7228     return SDValue();
7229   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7230   SDLoc DL(N);
7231   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7232                              DAG.getConstant(CA, DL, VT));
7233   SDValue New1 =
7234       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7235   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7236 }
7237 
7238 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7239                                  const RISCVSubtarget &Subtarget) {
7240   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7241     return V;
7242   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7243     return V;
7244   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7245   //      (select lhs, rhs, cc, x, (add x, y))
7246   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7247 }
7248 
7249 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7250   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7251   //      (select lhs, rhs, cc, x, (sub x, y))
7252   SDValue N0 = N->getOperand(0);
7253   SDValue N1 = N->getOperand(1);
7254   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7255 }
7256 
7257 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7258   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7259   //      (select lhs, rhs, cc, x, (and x, y))
7260   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7261 }
7262 
7263 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7264                                 const RISCVSubtarget &Subtarget) {
7265   if (Subtarget.hasStdExtZbp()) {
7266     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7267       return GREV;
7268     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7269       return GORC;
7270     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7271       return SHFL;
7272   }
7273 
7274   // fold (or (select cond, 0, y), x) ->
7275   //      (select cond, x, (or x, y))
7276   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7277 }
7278 
7279 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7280   // fold (xor (select cond, 0, y), x) ->
7281   //      (select cond, x, (xor x, y))
7282   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7283 }
7284 
7285 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7286 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7287 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7288 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7289 // ADDW/SUBW/MULW.
7290 static SDValue performANY_EXTENDCombine(SDNode *N,
7291                                         TargetLowering::DAGCombinerInfo &DCI,
7292                                         const RISCVSubtarget &Subtarget) {
7293   if (!Subtarget.is64Bit())
7294     return SDValue();
7295 
7296   SelectionDAG &DAG = DCI.DAG;
7297 
7298   SDValue Src = N->getOperand(0);
7299   EVT VT = N->getValueType(0);
7300   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7301     return SDValue();
7302 
7303   // The opcode must be one that can implicitly sign_extend.
7304   // FIXME: Additional opcodes.
7305   switch (Src.getOpcode()) {
7306   default:
7307     return SDValue();
7308   case ISD::MUL:
7309     if (!Subtarget.hasStdExtM())
7310       return SDValue();
7311     LLVM_FALLTHROUGH;
7312   case ISD::ADD:
7313   case ISD::SUB:
7314     break;
7315   }
7316 
7317   // Only handle cases where the result is used by a CopyToReg. That likely
7318   // means the value is a liveout of the basic block. This helps prevent
7319   // infinite combine loops like PR51206.
7320   if (none_of(N->uses(),
7321               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7322     return SDValue();
7323 
7324   SmallVector<SDNode *, 4> SetCCs;
7325   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7326                             UE = Src.getNode()->use_end();
7327        UI != UE; ++UI) {
7328     SDNode *User = *UI;
7329     if (User == N)
7330       continue;
7331     if (UI.getUse().getResNo() != Src.getResNo())
7332       continue;
7333     // All i32 setccs are legalized by sign extending operands.
7334     if (User->getOpcode() == ISD::SETCC) {
7335       SetCCs.push_back(User);
7336       continue;
7337     }
7338     // We don't know if we can extend this user.
7339     break;
7340   }
7341 
7342   // If we don't have any SetCCs, this isn't worthwhile.
7343   if (SetCCs.empty())
7344     return SDValue();
7345 
7346   SDLoc DL(N);
7347   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7348   DCI.CombineTo(N, SExt);
7349 
7350   // Promote all the setccs.
7351   for (SDNode *SetCC : SetCCs) {
7352     SmallVector<SDValue, 4> Ops;
7353 
7354     for (unsigned j = 0; j != 2; ++j) {
7355       SDValue SOp = SetCC->getOperand(j);
7356       if (SOp == Src)
7357         Ops.push_back(SExt);
7358       else
7359         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7360     }
7361 
7362     Ops.push_back(SetCC->getOperand(2));
7363     DCI.CombineTo(SetCC,
7364                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7365   }
7366   return SDValue(N, 0);
7367 }
7368 
7369 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7370 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7371 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7372                                              bool Commute = false) {
7373   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7374           N->getOpcode() == RISCVISD::SUB_VL) &&
7375          "Unexpected opcode");
7376   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7377   SDValue Op0 = N->getOperand(0);
7378   SDValue Op1 = N->getOperand(1);
7379   if (Commute)
7380     std::swap(Op0, Op1);
7381 
7382   MVT VT = N->getSimpleValueType(0);
7383 
7384   // Determine the narrow size for a widening add/sub.
7385   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7386   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7387                                   VT.getVectorElementCount());
7388 
7389   SDValue Mask = N->getOperand(2);
7390   SDValue VL = N->getOperand(3);
7391 
7392   SDLoc DL(N);
7393 
7394   // If the RHS is a sext or zext, we can form a widening op.
7395   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7396        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7397       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7398     unsigned ExtOpc = Op1.getOpcode();
7399     Op1 = Op1.getOperand(0);
7400     // Re-introduce narrower extends if needed.
7401     if (Op1.getValueType() != NarrowVT)
7402       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7403 
7404     unsigned WOpc;
7405     if (ExtOpc == RISCVISD::VSEXT_VL)
7406       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7407     else
7408       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7409 
7410     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7411   }
7412 
7413   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7414   // sext/zext?
7415 
7416   return SDValue();
7417 }
7418 
7419 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7420 // vwsub(u).vv/vx.
7421 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7422   SDValue Op0 = N->getOperand(0);
7423   SDValue Op1 = N->getOperand(1);
7424   SDValue Mask = N->getOperand(2);
7425   SDValue VL = N->getOperand(3);
7426 
7427   MVT VT = N->getSimpleValueType(0);
7428   MVT NarrowVT = Op1.getSimpleValueType();
7429   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7430 
7431   unsigned VOpc;
7432   switch (N->getOpcode()) {
7433   default: llvm_unreachable("Unexpected opcode");
7434   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7435   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7436   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7437   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7438   }
7439 
7440   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7441                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7442 
7443   SDLoc DL(N);
7444 
7445   // If the LHS is a sext or zext, we can narrow this op to the same size as
7446   // the RHS.
7447   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7448        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7449       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7450     unsigned ExtOpc = Op0.getOpcode();
7451     Op0 = Op0.getOperand(0);
7452     // Re-introduce narrower extends if needed.
7453     if (Op0.getValueType() != NarrowVT)
7454       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7455     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7456   }
7457 
7458   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7459                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7460 
7461   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7462   // to commute and use a vwadd(u).vx instead.
7463   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7464       Op0.getOperand(1) == VL) {
7465     Op0 = Op0.getOperand(0);
7466 
7467     // See if have enough sign bits or zero bits in the scalar to use a
7468     // widening add/sub by splatting to smaller element size.
7469     unsigned EltBits = VT.getScalarSizeInBits();
7470     unsigned ScalarBits = Op0.getValueSizeInBits();
7471     // Make sure we're getting all element bits from the scalar register.
7472     // FIXME: Support implicit sign extension of vmv.v.x?
7473     if (ScalarBits < EltBits)
7474       return SDValue();
7475 
7476     if (IsSigned) {
7477       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7478         return SDValue();
7479     } else {
7480       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7481       if (!DAG.MaskedValueIsZero(Op0, Mask))
7482         return SDValue();
7483     }
7484 
7485     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op0, VL);
7486     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7487   }
7488 
7489   return SDValue();
7490 }
7491 
7492 // Try to form VWMUL, VWMULU or VWMULSU.
7493 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7494 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7495                                        bool Commute) {
7496   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7497   SDValue Op0 = N->getOperand(0);
7498   SDValue Op1 = N->getOperand(1);
7499   if (Commute)
7500     std::swap(Op0, Op1);
7501 
7502   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7503   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7504   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7505   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7506     return SDValue();
7507 
7508   SDValue Mask = N->getOperand(2);
7509   SDValue VL = N->getOperand(3);
7510 
7511   // Make sure the mask and VL match.
7512   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7513     return SDValue();
7514 
7515   MVT VT = N->getSimpleValueType(0);
7516 
7517   // Determine the narrow size for a widening multiply.
7518   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7519   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7520                                   VT.getVectorElementCount());
7521 
7522   SDLoc DL(N);
7523 
7524   // See if the other operand is the same opcode.
7525   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7526     if (!Op1.hasOneUse())
7527       return SDValue();
7528 
7529     // Make sure the mask and VL match.
7530     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7531       return SDValue();
7532 
7533     Op1 = Op1.getOperand(0);
7534   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7535     // The operand is a splat of a scalar.
7536 
7537     // The VL must be the same.
7538     if (Op1.getOperand(1) != VL)
7539       return SDValue();
7540 
7541     // Get the scalar value.
7542     Op1 = Op1.getOperand(0);
7543 
7544     // See if have enough sign bits or zero bits in the scalar to use a
7545     // widening multiply by splatting to smaller element size.
7546     unsigned EltBits = VT.getScalarSizeInBits();
7547     unsigned ScalarBits = Op1.getValueSizeInBits();
7548     // Make sure we're getting all element bits from the scalar register.
7549     // FIXME: Support implicit sign extension of vmv.v.x?
7550     if (ScalarBits < EltBits)
7551       return SDValue();
7552 
7553     if (IsSignExt) {
7554       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7555         return SDValue();
7556     } else {
7557       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7558       if (!DAG.MaskedValueIsZero(Op1, Mask))
7559         return SDValue();
7560     }
7561 
7562     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7563   } else
7564     return SDValue();
7565 
7566   Op0 = Op0.getOperand(0);
7567 
7568   // Re-introduce narrower extends if needed.
7569   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7570   if (Op0.getValueType() != NarrowVT)
7571     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7572   if (Op1.getValueType() != NarrowVT)
7573     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7574 
7575   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7576   if (!IsVWMULSU)
7577     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7578   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7579 }
7580 
7581 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7582   switch (Op.getOpcode()) {
7583   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7584   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7585   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7586   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7587   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7588   }
7589 
7590   return RISCVFPRndMode::Invalid;
7591 }
7592 
7593 // Fold
7594 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7595 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7596 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7597 //   (fp_to_int (fceil X))      -> fcvt X, rup
7598 //   (fp_to_int (fround X))     -> fcvt X, rmm
7599 static SDValue performFP_TO_INTCombine(SDNode *N,
7600                                        TargetLowering::DAGCombinerInfo &DCI,
7601                                        const RISCVSubtarget &Subtarget) {
7602   SelectionDAG &DAG = DCI.DAG;
7603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7604   MVT XLenVT = Subtarget.getXLenVT();
7605 
7606   // Only handle XLen or i32 types. Other types narrower than XLen will
7607   // eventually be legalized to XLenVT.
7608   EVT VT = N->getValueType(0);
7609   if (VT != MVT::i32 && VT != XLenVT)
7610     return SDValue();
7611 
7612   SDValue Src = N->getOperand(0);
7613 
7614   // Ensure the FP type is also legal.
7615   if (!TLI.isTypeLegal(Src.getValueType()))
7616     return SDValue();
7617 
7618   // Don't do this for f16 with Zfhmin and not Zfh.
7619   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7620     return SDValue();
7621 
7622   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7623   if (FRM == RISCVFPRndMode::Invalid)
7624     return SDValue();
7625 
7626   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7627 
7628   unsigned Opc;
7629   if (VT == XLenVT)
7630     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7631   else
7632     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7633 
7634   SDLoc DL(N);
7635   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7636                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7637   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7638 }
7639 
7640 // Fold
7641 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7642 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7643 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7644 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7645 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7646 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7647                                        TargetLowering::DAGCombinerInfo &DCI,
7648                                        const RISCVSubtarget &Subtarget) {
7649   SelectionDAG &DAG = DCI.DAG;
7650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7651   MVT XLenVT = Subtarget.getXLenVT();
7652 
7653   // Only handle XLen types. Other types narrower than XLen will eventually be
7654   // legalized to XLenVT.
7655   EVT DstVT = N->getValueType(0);
7656   if (DstVT != XLenVT)
7657     return SDValue();
7658 
7659   SDValue Src = N->getOperand(0);
7660 
7661   // Ensure the FP type is also legal.
7662   if (!TLI.isTypeLegal(Src.getValueType()))
7663     return SDValue();
7664 
7665   // Don't do this for f16 with Zfhmin and not Zfh.
7666   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7667     return SDValue();
7668 
7669   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7670 
7671   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7672   if (FRM == RISCVFPRndMode::Invalid)
7673     return SDValue();
7674 
7675   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7676 
7677   unsigned Opc;
7678   if (SatVT == DstVT)
7679     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7680   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7681     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7682   else
7683     return SDValue();
7684   // FIXME: Support other SatVTs by clamping before or after the conversion.
7685 
7686   Src = Src.getOperand(0);
7687 
7688   SDLoc DL(N);
7689   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7690                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7691 
7692   // RISCV FP-to-int conversions saturate to the destination register size, but
7693   // don't produce 0 for nan.
7694   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7695   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7696 }
7697 
7698 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7699                                                DAGCombinerInfo &DCI) const {
7700   SelectionDAG &DAG = DCI.DAG;
7701 
7702   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7703   // bits are demanded. N will be added to the Worklist if it was not deleted.
7704   // Caller should return SDValue(N, 0) if this returns true.
7705   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7706     SDValue Op = N->getOperand(OpNo);
7707     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7708     if (!SimplifyDemandedBits(Op, Mask, DCI))
7709       return false;
7710 
7711     if (N->getOpcode() != ISD::DELETED_NODE)
7712       DCI.AddToWorklist(N);
7713     return true;
7714   };
7715 
7716   switch (N->getOpcode()) {
7717   default:
7718     break;
7719   case RISCVISD::SplitF64: {
7720     SDValue Op0 = N->getOperand(0);
7721     // If the input to SplitF64 is just BuildPairF64 then the operation is
7722     // redundant. Instead, use BuildPairF64's operands directly.
7723     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7724       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7725 
7726     SDLoc DL(N);
7727 
7728     // It's cheaper to materialise two 32-bit integers than to load a double
7729     // from the constant pool and transfer it to integer registers through the
7730     // stack.
7731     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7732       APInt V = C->getValueAPF().bitcastToAPInt();
7733       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7734       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7735       return DCI.CombineTo(N, Lo, Hi);
7736     }
7737 
7738     // This is a target-specific version of a DAGCombine performed in
7739     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7740     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7741     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7742     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7743         !Op0.getNode()->hasOneUse())
7744       break;
7745     SDValue NewSplitF64 =
7746         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7747                     Op0.getOperand(0));
7748     SDValue Lo = NewSplitF64.getValue(0);
7749     SDValue Hi = NewSplitF64.getValue(1);
7750     APInt SignBit = APInt::getSignMask(32);
7751     if (Op0.getOpcode() == ISD::FNEG) {
7752       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7753                                   DAG.getConstant(SignBit, DL, MVT::i32));
7754       return DCI.CombineTo(N, Lo, NewHi);
7755     }
7756     assert(Op0.getOpcode() == ISD::FABS);
7757     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7758                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7759     return DCI.CombineTo(N, Lo, NewHi);
7760   }
7761   case RISCVISD::SLLW:
7762   case RISCVISD::SRAW:
7763   case RISCVISD::SRLW:
7764   case RISCVISD::ROLW:
7765   case RISCVISD::RORW: {
7766     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7767     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7768         SimplifyDemandedLowBitsHelper(1, 5))
7769       return SDValue(N, 0);
7770     break;
7771   }
7772   case RISCVISD::CLZW:
7773   case RISCVISD::CTZW: {
7774     // Only the lower 32 bits of the first operand are read
7775     if (SimplifyDemandedLowBitsHelper(0, 32))
7776       return SDValue(N, 0);
7777     break;
7778   }
7779   case RISCVISD::GREV:
7780   case RISCVISD::GORC: {
7781     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7782     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7783     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7784     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7785       return SDValue(N, 0);
7786 
7787     return combineGREVI_GORCI(N, DAG);
7788   }
7789   case RISCVISD::GREVW:
7790   case RISCVISD::GORCW: {
7791     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7792     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7793         SimplifyDemandedLowBitsHelper(1, 5))
7794       return SDValue(N, 0);
7795 
7796     return combineGREVI_GORCI(N, DAG);
7797   }
7798   case RISCVISD::SHFL:
7799   case RISCVISD::UNSHFL: {
7800     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7801     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7802     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7803     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7804       return SDValue(N, 0);
7805 
7806     break;
7807   }
7808   case RISCVISD::SHFLW:
7809   case RISCVISD::UNSHFLW: {
7810     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7811     SDValue LHS = N->getOperand(0);
7812     SDValue RHS = N->getOperand(1);
7813     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7814     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7815     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7816         SimplifyDemandedLowBitsHelper(1, 4))
7817       return SDValue(N, 0);
7818 
7819     break;
7820   }
7821   case RISCVISD::BCOMPRESSW:
7822   case RISCVISD::BDECOMPRESSW: {
7823     // Only the lower 32 bits of LHS and RHS are read.
7824     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7825         SimplifyDemandedLowBitsHelper(1, 32))
7826       return SDValue(N, 0);
7827 
7828     break;
7829   }
7830   case RISCVISD::FMV_X_ANYEXTH:
7831   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7832     SDLoc DL(N);
7833     SDValue Op0 = N->getOperand(0);
7834     MVT VT = N->getSimpleValueType(0);
7835     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7836     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7837     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7838     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7839          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7840         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7841          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7842       assert(Op0.getOperand(0).getValueType() == VT &&
7843              "Unexpected value type!");
7844       return Op0.getOperand(0);
7845     }
7846 
7847     // This is a target-specific version of a DAGCombine performed in
7848     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7849     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7850     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7851     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7852         !Op0.getNode()->hasOneUse())
7853       break;
7854     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7855     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7856     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7857     if (Op0.getOpcode() == ISD::FNEG)
7858       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7859                          DAG.getConstant(SignBit, DL, VT));
7860 
7861     assert(Op0.getOpcode() == ISD::FABS);
7862     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7863                        DAG.getConstant(~SignBit, DL, VT));
7864   }
7865   case ISD::ADD:
7866     return performADDCombine(N, DAG, Subtarget);
7867   case ISD::SUB:
7868     return performSUBCombine(N, DAG);
7869   case ISD::AND:
7870     return performANDCombine(N, DAG);
7871   case ISD::OR:
7872     return performORCombine(N, DAG, Subtarget);
7873   case ISD::XOR:
7874     return performXORCombine(N, DAG);
7875   case ISD::ANY_EXTEND:
7876     return performANY_EXTENDCombine(N, DCI, Subtarget);
7877   case ISD::ZERO_EXTEND:
7878     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7879     // type legalization. This is safe because fp_to_uint produces poison if
7880     // it overflows.
7881     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7882       SDValue Src = N->getOperand(0);
7883       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7884           isTypeLegal(Src.getOperand(0).getValueType()))
7885         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7886                            Src.getOperand(0));
7887       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7888           isTypeLegal(Src.getOperand(1).getValueType())) {
7889         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7890         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7891                                   Src.getOperand(0), Src.getOperand(1));
7892         DCI.CombineTo(N, Res);
7893         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7894         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7895         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7896       }
7897     }
7898     return SDValue();
7899   case RISCVISD::SELECT_CC: {
7900     // Transform
7901     SDValue LHS = N->getOperand(0);
7902     SDValue RHS = N->getOperand(1);
7903     SDValue TrueV = N->getOperand(3);
7904     SDValue FalseV = N->getOperand(4);
7905 
7906     // If the True and False values are the same, we don't need a select_cc.
7907     if (TrueV == FalseV)
7908       return TrueV;
7909 
7910     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7911     if (!ISD::isIntEqualitySetCC(CCVal))
7912       break;
7913 
7914     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7915     //      (select_cc X, Y, lt, trueV, falseV)
7916     // Sometimes the setcc is introduced after select_cc has been formed.
7917     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7918         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7919       // If we're looking for eq 0 instead of ne 0, we need to invert the
7920       // condition.
7921       bool Invert = CCVal == ISD::SETEQ;
7922       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7923       if (Invert)
7924         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7925 
7926       SDLoc DL(N);
7927       RHS = LHS.getOperand(1);
7928       LHS = LHS.getOperand(0);
7929       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7930 
7931       SDValue TargetCC = DAG.getCondCode(CCVal);
7932       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7933                          {LHS, RHS, TargetCC, TrueV, FalseV});
7934     }
7935 
7936     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7937     //      (select_cc X, Y, eq/ne, trueV, falseV)
7938     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7939       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7940                          {LHS.getOperand(0), LHS.getOperand(1),
7941                           N->getOperand(2), TrueV, FalseV});
7942     // (select_cc X, 1, setne, trueV, falseV) ->
7943     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7944     // This can occur when legalizing some floating point comparisons.
7945     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7946     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7947       SDLoc DL(N);
7948       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7949       SDValue TargetCC = DAG.getCondCode(CCVal);
7950       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7951       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7952                          {LHS, RHS, TargetCC, TrueV, FalseV});
7953     }
7954 
7955     break;
7956   }
7957   case RISCVISD::BR_CC: {
7958     SDValue LHS = N->getOperand(1);
7959     SDValue RHS = N->getOperand(2);
7960     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7961     if (!ISD::isIntEqualitySetCC(CCVal))
7962       break;
7963 
7964     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7965     //      (br_cc X, Y, lt, dest)
7966     // Sometimes the setcc is introduced after br_cc has been formed.
7967     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7968         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7969       // If we're looking for eq 0 instead of ne 0, we need to invert the
7970       // condition.
7971       bool Invert = CCVal == ISD::SETEQ;
7972       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7973       if (Invert)
7974         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7975 
7976       SDLoc DL(N);
7977       RHS = LHS.getOperand(1);
7978       LHS = LHS.getOperand(0);
7979       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7980 
7981       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7982                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7983                          N->getOperand(4));
7984     }
7985 
7986     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7987     //      (br_cc X, Y, eq/ne, trueV, falseV)
7988     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7989       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7990                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7991                          N->getOperand(3), N->getOperand(4));
7992 
7993     // (br_cc X, 1, setne, br_cc) ->
7994     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7995     // This can occur when legalizing some floating point comparisons.
7996     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7997     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7998       SDLoc DL(N);
7999       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8000       SDValue TargetCC = DAG.getCondCode(CCVal);
8001       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8002       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8003                          N->getOperand(0), LHS, RHS, TargetCC,
8004                          N->getOperand(4));
8005     }
8006     break;
8007   }
8008   case ISD::FP_TO_SINT:
8009   case ISD::FP_TO_UINT:
8010     return performFP_TO_INTCombine(N, DCI, Subtarget);
8011   case ISD::FP_TO_SINT_SAT:
8012   case ISD::FP_TO_UINT_SAT:
8013     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8014   case ISD::FCOPYSIGN: {
8015     EVT VT = N->getValueType(0);
8016     if (!VT.isVector())
8017       break;
8018     // There is a form of VFSGNJ which injects the negated sign of its second
8019     // operand. Try and bubble any FNEG up after the extend/round to produce
8020     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8021     // TRUNC=1.
8022     SDValue In2 = N->getOperand(1);
8023     // Avoid cases where the extend/round has multiple uses, as duplicating
8024     // those is typically more expensive than removing a fneg.
8025     if (!In2.hasOneUse())
8026       break;
8027     if (In2.getOpcode() != ISD::FP_EXTEND &&
8028         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8029       break;
8030     In2 = In2.getOperand(0);
8031     if (In2.getOpcode() != ISD::FNEG)
8032       break;
8033     SDLoc DL(N);
8034     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8035     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8036                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8037   }
8038   case ISD::MGATHER:
8039   case ISD::MSCATTER:
8040   case ISD::VP_GATHER:
8041   case ISD::VP_SCATTER: {
8042     if (!DCI.isBeforeLegalize())
8043       break;
8044     SDValue Index, ScaleOp;
8045     bool IsIndexScaled = false;
8046     bool IsIndexSigned = false;
8047     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8048       Index = VPGSN->getIndex();
8049       ScaleOp = VPGSN->getScale();
8050       IsIndexScaled = VPGSN->isIndexScaled();
8051       IsIndexSigned = VPGSN->isIndexSigned();
8052     } else {
8053       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8054       Index = MGSN->getIndex();
8055       ScaleOp = MGSN->getScale();
8056       IsIndexScaled = MGSN->isIndexScaled();
8057       IsIndexSigned = MGSN->isIndexSigned();
8058     }
8059     EVT IndexVT = Index.getValueType();
8060     MVT XLenVT = Subtarget.getXLenVT();
8061     // RISCV indexed loads only support the "unsigned unscaled" addressing
8062     // mode, so anything else must be manually legalized.
8063     bool NeedsIdxLegalization =
8064         IsIndexScaled ||
8065         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8066     if (!NeedsIdxLegalization)
8067       break;
8068 
8069     SDLoc DL(N);
8070 
8071     // Any index legalization should first promote to XLenVT, so we don't lose
8072     // bits when scaling. This may create an illegal index type so we let
8073     // LLVM's legalization take care of the splitting.
8074     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8075     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8076       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8077       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8078                           DL, IndexVT, Index);
8079     }
8080 
8081     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8082     if (IsIndexScaled && Scale != 1) {
8083       // Manually scale the indices by the element size.
8084       // TODO: Sanitize the scale operand here?
8085       // TODO: For VP nodes, should we use VP_SHL here?
8086       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8087       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8088       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8089     }
8090 
8091     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8092     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8093       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8094                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8095                               VPGN->getScale(), VPGN->getMask(),
8096                               VPGN->getVectorLength()},
8097                              VPGN->getMemOperand(), NewIndexTy);
8098     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8099       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8100                               {VPSN->getChain(), VPSN->getValue(),
8101                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8102                                VPSN->getMask(), VPSN->getVectorLength()},
8103                               VPSN->getMemOperand(), NewIndexTy);
8104     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8105       return DAG.getMaskedGather(
8106           N->getVTList(), MGN->getMemoryVT(), DL,
8107           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8108            MGN->getBasePtr(), Index, MGN->getScale()},
8109           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8110     const auto *MSN = cast<MaskedScatterSDNode>(N);
8111     return DAG.getMaskedScatter(
8112         N->getVTList(), MSN->getMemoryVT(), DL,
8113         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8114          Index, MSN->getScale()},
8115         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8116   }
8117   case RISCVISD::SRA_VL:
8118   case RISCVISD::SRL_VL:
8119   case RISCVISD::SHL_VL: {
8120     SDValue ShAmt = N->getOperand(1);
8121     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8122       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8123       SDLoc DL(N);
8124       SDValue VL = N->getOperand(3);
8125       EVT VT = N->getValueType(0);
8126       ShAmt =
8127           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
8128       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8129                          N->getOperand(2), N->getOperand(3));
8130     }
8131     break;
8132   }
8133   case ISD::SRA:
8134   case ISD::SRL:
8135   case ISD::SHL: {
8136     SDValue ShAmt = N->getOperand(1);
8137     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8138       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8139       SDLoc DL(N);
8140       EVT VT = N->getValueType(0);
8141       ShAmt =
8142           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
8143       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8144     }
8145     break;
8146   }
8147   case RISCVISD::ADD_VL:
8148     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8149       return V;
8150     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8151   case RISCVISD::SUB_VL:
8152     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8153   case RISCVISD::VWADD_W_VL:
8154   case RISCVISD::VWADDU_W_VL:
8155   case RISCVISD::VWSUB_W_VL:
8156   case RISCVISD::VWSUBU_W_VL:
8157     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8158   case RISCVISD::MUL_VL:
8159     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8160       return V;
8161     // Mul is commutative.
8162     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8163   case ISD::STORE: {
8164     auto *Store = cast<StoreSDNode>(N);
8165     SDValue Val = Store->getValue();
8166     // Combine store of vmv.x.s to vse with VL of 1.
8167     // FIXME: Support FP.
8168     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8169       SDValue Src = Val.getOperand(0);
8170       EVT VecVT = Src.getValueType();
8171       EVT MemVT = Store->getMemoryVT();
8172       // The memory VT and the element type must match.
8173       if (VecVT.getVectorElementType() == MemVT) {
8174         SDLoc DL(N);
8175         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8176         return DAG.getStoreVP(
8177             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8178             DAG.getConstant(1, DL, MaskVT),
8179             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8180             Store->getMemOperand(), Store->getAddressingMode(),
8181             Store->isTruncatingStore(), /*IsCompress*/ false);
8182       }
8183     }
8184 
8185     break;
8186   }
8187   }
8188 
8189   return SDValue();
8190 }
8191 
8192 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8193     const SDNode *N, CombineLevel Level) const {
8194   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8195   // materialised in fewer instructions than `(OP _, c1)`:
8196   //
8197   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8198   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8199   SDValue N0 = N->getOperand(0);
8200   EVT Ty = N0.getValueType();
8201   if (Ty.isScalarInteger() &&
8202       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8203     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8204     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8205     if (C1 && C2) {
8206       const APInt &C1Int = C1->getAPIntValue();
8207       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8208 
8209       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8210       // and the combine should happen, to potentially allow further combines
8211       // later.
8212       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8213           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8214         return true;
8215 
8216       // We can materialise `c1` in an add immediate, so it's "free", and the
8217       // combine should be prevented.
8218       if (C1Int.getMinSignedBits() <= 64 &&
8219           isLegalAddImmediate(C1Int.getSExtValue()))
8220         return false;
8221 
8222       // Neither constant will fit into an immediate, so find materialisation
8223       // costs.
8224       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8225                                               Subtarget.getFeatureBits(),
8226                                               /*CompressionCost*/true);
8227       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8228           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8229           /*CompressionCost*/true);
8230 
8231       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8232       // combine should be prevented.
8233       if (C1Cost < ShiftedC1Cost)
8234         return false;
8235     }
8236   }
8237   return true;
8238 }
8239 
8240 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8241     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8242     TargetLoweringOpt &TLO) const {
8243   // Delay this optimization as late as possible.
8244   if (!TLO.LegalOps)
8245     return false;
8246 
8247   EVT VT = Op.getValueType();
8248   if (VT.isVector())
8249     return false;
8250 
8251   // Only handle AND for now.
8252   if (Op.getOpcode() != ISD::AND)
8253     return false;
8254 
8255   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8256   if (!C)
8257     return false;
8258 
8259   const APInt &Mask = C->getAPIntValue();
8260 
8261   // Clear all non-demanded bits initially.
8262   APInt ShrunkMask = Mask & DemandedBits;
8263 
8264   // Try to make a smaller immediate by setting undemanded bits.
8265 
8266   APInt ExpandedMask = Mask | ~DemandedBits;
8267 
8268   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8269     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8270   };
8271   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8272     if (NewMask == Mask)
8273       return true;
8274     SDLoc DL(Op);
8275     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8276     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8277     return TLO.CombineTo(Op, NewOp);
8278   };
8279 
8280   // If the shrunk mask fits in sign extended 12 bits, let the target
8281   // independent code apply it.
8282   if (ShrunkMask.isSignedIntN(12))
8283     return false;
8284 
8285   // Preserve (and X, 0xffff) when zext.h is supported.
8286   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8287     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8288     if (IsLegalMask(NewMask))
8289       return UseMask(NewMask);
8290   }
8291 
8292   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8293   if (VT == MVT::i64) {
8294     APInt NewMask = APInt(64, 0xffffffff);
8295     if (IsLegalMask(NewMask))
8296       return UseMask(NewMask);
8297   }
8298 
8299   // For the remaining optimizations, we need to be able to make a negative
8300   // number through a combination of mask and undemanded bits.
8301   if (!ExpandedMask.isNegative())
8302     return false;
8303 
8304   // What is the fewest number of bits we need to represent the negative number.
8305   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8306 
8307   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8308   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8309   APInt NewMask = ShrunkMask;
8310   if (MinSignedBits <= 12)
8311     NewMask.setBitsFrom(11);
8312   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8313     NewMask.setBitsFrom(31);
8314   else
8315     return false;
8316 
8317   // Check that our new mask is a subset of the demanded mask.
8318   assert(IsLegalMask(NewMask));
8319   return UseMask(NewMask);
8320 }
8321 
8322 static void computeGREV(APInt &Src, unsigned ShAmt) {
8323   ShAmt &= Src.getBitWidth() - 1;
8324   uint64_t x = Src.getZExtValue();
8325   if (ShAmt & 1)
8326     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8327   if (ShAmt & 2)
8328     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8329   if (ShAmt & 4)
8330     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8331   if (ShAmt & 8)
8332     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8333   if (ShAmt & 16)
8334     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8335   if (ShAmt & 32)
8336     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8337   Src = x;
8338 }
8339 
8340 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8341                                                         KnownBits &Known,
8342                                                         const APInt &DemandedElts,
8343                                                         const SelectionDAG &DAG,
8344                                                         unsigned Depth) const {
8345   unsigned BitWidth = Known.getBitWidth();
8346   unsigned Opc = Op.getOpcode();
8347   assert((Opc >= ISD::BUILTIN_OP_END ||
8348           Opc == ISD::INTRINSIC_WO_CHAIN ||
8349           Opc == ISD::INTRINSIC_W_CHAIN ||
8350           Opc == ISD::INTRINSIC_VOID) &&
8351          "Should use MaskedValueIsZero if you don't know whether Op"
8352          " is a target node!");
8353 
8354   Known.resetAll();
8355   switch (Opc) {
8356   default: break;
8357   case RISCVISD::SELECT_CC: {
8358     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8359     // If we don't know any bits, early out.
8360     if (Known.isUnknown())
8361       break;
8362     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8363 
8364     // Only known if known in both the LHS and RHS.
8365     Known = KnownBits::commonBits(Known, Known2);
8366     break;
8367   }
8368   case RISCVISD::REMUW: {
8369     KnownBits Known2;
8370     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8371     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8372     // We only care about the lower 32 bits.
8373     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8374     // Restore the original width by sign extending.
8375     Known = Known.sext(BitWidth);
8376     break;
8377   }
8378   case RISCVISD::DIVUW: {
8379     KnownBits Known2;
8380     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8381     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8382     // We only care about the lower 32 bits.
8383     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8384     // Restore the original width by sign extending.
8385     Known = Known.sext(BitWidth);
8386     break;
8387   }
8388   case RISCVISD::CTZW: {
8389     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8390     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8391     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8392     Known.Zero.setBitsFrom(LowBits);
8393     break;
8394   }
8395   case RISCVISD::CLZW: {
8396     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8397     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8398     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8399     Known.Zero.setBitsFrom(LowBits);
8400     break;
8401   }
8402   case RISCVISD::GREV:
8403   case RISCVISD::GREVW: {
8404     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8405       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8406       if (Opc == RISCVISD::GREVW)
8407         Known = Known.trunc(32);
8408       unsigned ShAmt = C->getZExtValue();
8409       computeGREV(Known.Zero, ShAmt);
8410       computeGREV(Known.One, ShAmt);
8411       if (Opc == RISCVISD::GREVW)
8412         Known = Known.sext(BitWidth);
8413     }
8414     break;
8415   }
8416   case RISCVISD::READ_VLENB: {
8417     // If we know the minimum VLen from Zvl extensions, we can use that to
8418     // determine the trailing zeros of VLENB.
8419     // FIXME: Limit to 128 bit vectors until we have more testing.
8420     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8421     if (MinVLenB > 0)
8422       Known.Zero.setLowBits(Log2_32(MinVLenB));
8423     // We assume VLENB is no more than 65536 / 8 bytes.
8424     Known.Zero.setBitsFrom(14);
8425     break;
8426   }
8427   case ISD::INTRINSIC_W_CHAIN:
8428   case ISD::INTRINSIC_WO_CHAIN: {
8429     unsigned IntNo =
8430         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8431     switch (IntNo) {
8432     default:
8433       // We can't do anything for most intrinsics.
8434       break;
8435     case Intrinsic::riscv_vsetvli:
8436     case Intrinsic::riscv_vsetvlimax:
8437     case Intrinsic::riscv_vsetvli_opt:
8438     case Intrinsic::riscv_vsetvlimax_opt:
8439       // Assume that VL output is positive and would fit in an int32_t.
8440       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8441       if (BitWidth >= 32)
8442         Known.Zero.setBitsFrom(31);
8443       break;
8444     }
8445     break;
8446   }
8447   }
8448 }
8449 
8450 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8451     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8452     unsigned Depth) const {
8453   switch (Op.getOpcode()) {
8454   default:
8455     break;
8456   case RISCVISD::SELECT_CC: {
8457     unsigned Tmp =
8458         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8459     if (Tmp == 1) return 1;  // Early out.
8460     unsigned Tmp2 =
8461         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8462     return std::min(Tmp, Tmp2);
8463   }
8464   case RISCVISD::SLLW:
8465   case RISCVISD::SRAW:
8466   case RISCVISD::SRLW:
8467   case RISCVISD::DIVW:
8468   case RISCVISD::DIVUW:
8469   case RISCVISD::REMUW:
8470   case RISCVISD::ROLW:
8471   case RISCVISD::RORW:
8472   case RISCVISD::GREVW:
8473   case RISCVISD::GORCW:
8474   case RISCVISD::FSLW:
8475   case RISCVISD::FSRW:
8476   case RISCVISD::SHFLW:
8477   case RISCVISD::UNSHFLW:
8478   case RISCVISD::BCOMPRESSW:
8479   case RISCVISD::BDECOMPRESSW:
8480   case RISCVISD::BFPW:
8481   case RISCVISD::FCVT_W_RV64:
8482   case RISCVISD::FCVT_WU_RV64:
8483   case RISCVISD::STRICT_FCVT_W_RV64:
8484   case RISCVISD::STRICT_FCVT_WU_RV64:
8485     // TODO: As the result is sign-extended, this is conservatively correct. A
8486     // more precise answer could be calculated for SRAW depending on known
8487     // bits in the shift amount.
8488     return 33;
8489   case RISCVISD::SHFL:
8490   case RISCVISD::UNSHFL: {
8491     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8492     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8493     // will stay within the upper 32 bits. If there were more than 32 sign bits
8494     // before there will be at least 33 sign bits after.
8495     if (Op.getValueType() == MVT::i64 &&
8496         isa<ConstantSDNode>(Op.getOperand(1)) &&
8497         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8498       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8499       if (Tmp > 32)
8500         return 33;
8501     }
8502     break;
8503   }
8504   case RISCVISD::VMV_X_S: {
8505     // The number of sign bits of the scalar result is computed by obtaining the
8506     // element type of the input vector operand, subtracting its width from the
8507     // XLEN, and then adding one (sign bit within the element type). If the
8508     // element type is wider than XLen, the least-significant XLEN bits are
8509     // taken.
8510     unsigned XLen = Subtarget.getXLen();
8511     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8512     if (EltBits <= XLen)
8513       return XLen - EltBits + 1;
8514     break;
8515   }
8516   }
8517 
8518   return 1;
8519 }
8520 
8521 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8522                                                   MachineBasicBlock *BB) {
8523   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8524 
8525   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8526   // Should the count have wrapped while it was being read, we need to try
8527   // again.
8528   // ...
8529   // read:
8530   // rdcycleh x3 # load high word of cycle
8531   // rdcycle  x2 # load low word of cycle
8532   // rdcycleh x4 # load high word of cycle
8533   // bne x3, x4, read # check if high word reads match, otherwise try again
8534   // ...
8535 
8536   MachineFunction &MF = *BB->getParent();
8537   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8538   MachineFunction::iterator It = ++BB->getIterator();
8539 
8540   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8541   MF.insert(It, LoopMBB);
8542 
8543   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8544   MF.insert(It, DoneMBB);
8545 
8546   // Transfer the remainder of BB and its successor edges to DoneMBB.
8547   DoneMBB->splice(DoneMBB->begin(), BB,
8548                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8549   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8550 
8551   BB->addSuccessor(LoopMBB);
8552 
8553   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8554   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8555   Register LoReg = MI.getOperand(0).getReg();
8556   Register HiReg = MI.getOperand(1).getReg();
8557   DebugLoc DL = MI.getDebugLoc();
8558 
8559   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8560   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8561       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8562       .addReg(RISCV::X0);
8563   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8564       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8565       .addReg(RISCV::X0);
8566   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8567       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8568       .addReg(RISCV::X0);
8569 
8570   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8571       .addReg(HiReg)
8572       .addReg(ReadAgainReg)
8573       .addMBB(LoopMBB);
8574 
8575   LoopMBB->addSuccessor(LoopMBB);
8576   LoopMBB->addSuccessor(DoneMBB);
8577 
8578   MI.eraseFromParent();
8579 
8580   return DoneMBB;
8581 }
8582 
8583 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8584                                              MachineBasicBlock *BB) {
8585   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8586 
8587   MachineFunction &MF = *BB->getParent();
8588   DebugLoc DL = MI.getDebugLoc();
8589   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8590   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8591   Register LoReg = MI.getOperand(0).getReg();
8592   Register HiReg = MI.getOperand(1).getReg();
8593   Register SrcReg = MI.getOperand(2).getReg();
8594   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8595   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8596 
8597   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8598                           RI);
8599   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8600   MachineMemOperand *MMOLo =
8601       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8602   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8603       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8604   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8605       .addFrameIndex(FI)
8606       .addImm(0)
8607       .addMemOperand(MMOLo);
8608   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8609       .addFrameIndex(FI)
8610       .addImm(4)
8611       .addMemOperand(MMOHi);
8612   MI.eraseFromParent(); // The pseudo instruction is gone now.
8613   return BB;
8614 }
8615 
8616 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8617                                                  MachineBasicBlock *BB) {
8618   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8619          "Unexpected instruction");
8620 
8621   MachineFunction &MF = *BB->getParent();
8622   DebugLoc DL = MI.getDebugLoc();
8623   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8624   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8625   Register DstReg = MI.getOperand(0).getReg();
8626   Register LoReg = MI.getOperand(1).getReg();
8627   Register HiReg = MI.getOperand(2).getReg();
8628   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8629   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8630 
8631   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8632   MachineMemOperand *MMOLo =
8633       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8634   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8635       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8636   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8637       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8638       .addFrameIndex(FI)
8639       .addImm(0)
8640       .addMemOperand(MMOLo);
8641   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8642       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8643       .addFrameIndex(FI)
8644       .addImm(4)
8645       .addMemOperand(MMOHi);
8646   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8647   MI.eraseFromParent(); // The pseudo instruction is gone now.
8648   return BB;
8649 }
8650 
8651 static bool isSelectPseudo(MachineInstr &MI) {
8652   switch (MI.getOpcode()) {
8653   default:
8654     return false;
8655   case RISCV::Select_GPR_Using_CC_GPR:
8656   case RISCV::Select_FPR16_Using_CC_GPR:
8657   case RISCV::Select_FPR32_Using_CC_GPR:
8658   case RISCV::Select_FPR64_Using_CC_GPR:
8659     return true;
8660   }
8661 }
8662 
8663 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8664                                         unsigned RelOpcode, unsigned EqOpcode,
8665                                         const RISCVSubtarget &Subtarget) {
8666   DebugLoc DL = MI.getDebugLoc();
8667   Register DstReg = MI.getOperand(0).getReg();
8668   Register Src1Reg = MI.getOperand(1).getReg();
8669   Register Src2Reg = MI.getOperand(2).getReg();
8670   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8671   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8672   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8673 
8674   // Save the current FFLAGS.
8675   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8676 
8677   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8678                  .addReg(Src1Reg)
8679                  .addReg(Src2Reg);
8680   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8681     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8682 
8683   // Restore the FFLAGS.
8684   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8685       .addReg(SavedFFlags, RegState::Kill);
8686 
8687   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8688   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8689                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8690                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8691   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8692     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8693 
8694   // Erase the pseudoinstruction.
8695   MI.eraseFromParent();
8696   return BB;
8697 }
8698 
8699 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8700                                            MachineBasicBlock *BB,
8701                                            const RISCVSubtarget &Subtarget) {
8702   // To "insert" Select_* instructions, we actually have to insert the triangle
8703   // control-flow pattern.  The incoming instructions know the destination vreg
8704   // to set, the condition code register to branch on, the true/false values to
8705   // select between, and the condcode to use to select the appropriate branch.
8706   //
8707   // We produce the following control flow:
8708   //     HeadMBB
8709   //     |  \
8710   //     |  IfFalseMBB
8711   //     | /
8712   //    TailMBB
8713   //
8714   // When we find a sequence of selects we attempt to optimize their emission
8715   // by sharing the control flow. Currently we only handle cases where we have
8716   // multiple selects with the exact same condition (same LHS, RHS and CC).
8717   // The selects may be interleaved with other instructions if the other
8718   // instructions meet some requirements we deem safe:
8719   // - They are debug instructions. Otherwise,
8720   // - They do not have side-effects, do not access memory and their inputs do
8721   //   not depend on the results of the select pseudo-instructions.
8722   // The TrueV/FalseV operands of the selects cannot depend on the result of
8723   // previous selects in the sequence.
8724   // These conditions could be further relaxed. See the X86 target for a
8725   // related approach and more information.
8726   Register LHS = MI.getOperand(1).getReg();
8727   Register RHS = MI.getOperand(2).getReg();
8728   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8729 
8730   SmallVector<MachineInstr *, 4> SelectDebugValues;
8731   SmallSet<Register, 4> SelectDests;
8732   SelectDests.insert(MI.getOperand(0).getReg());
8733 
8734   MachineInstr *LastSelectPseudo = &MI;
8735 
8736   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8737        SequenceMBBI != E; ++SequenceMBBI) {
8738     if (SequenceMBBI->isDebugInstr())
8739       continue;
8740     else if (isSelectPseudo(*SequenceMBBI)) {
8741       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8742           SequenceMBBI->getOperand(2).getReg() != RHS ||
8743           SequenceMBBI->getOperand(3).getImm() != CC ||
8744           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8745           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8746         break;
8747       LastSelectPseudo = &*SequenceMBBI;
8748       SequenceMBBI->collectDebugValues(SelectDebugValues);
8749       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8750     } else {
8751       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8752           SequenceMBBI->mayLoadOrStore())
8753         break;
8754       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8755             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8756           }))
8757         break;
8758     }
8759   }
8760 
8761   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8762   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8763   DebugLoc DL = MI.getDebugLoc();
8764   MachineFunction::iterator I = ++BB->getIterator();
8765 
8766   MachineBasicBlock *HeadMBB = BB;
8767   MachineFunction *F = BB->getParent();
8768   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8769   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8770 
8771   F->insert(I, IfFalseMBB);
8772   F->insert(I, TailMBB);
8773 
8774   // Transfer debug instructions associated with the selects to TailMBB.
8775   for (MachineInstr *DebugInstr : SelectDebugValues) {
8776     TailMBB->push_back(DebugInstr->removeFromParent());
8777   }
8778 
8779   // Move all instructions after the sequence to TailMBB.
8780   TailMBB->splice(TailMBB->end(), HeadMBB,
8781                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8782   // Update machine-CFG edges by transferring all successors of the current
8783   // block to the new block which will contain the Phi nodes for the selects.
8784   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8785   // Set the successors for HeadMBB.
8786   HeadMBB->addSuccessor(IfFalseMBB);
8787   HeadMBB->addSuccessor(TailMBB);
8788 
8789   // Insert appropriate branch.
8790   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8791     .addReg(LHS)
8792     .addReg(RHS)
8793     .addMBB(TailMBB);
8794 
8795   // IfFalseMBB just falls through to TailMBB.
8796   IfFalseMBB->addSuccessor(TailMBB);
8797 
8798   // Create PHIs for all of the select pseudo-instructions.
8799   auto SelectMBBI = MI.getIterator();
8800   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8801   auto InsertionPoint = TailMBB->begin();
8802   while (SelectMBBI != SelectEnd) {
8803     auto Next = std::next(SelectMBBI);
8804     if (isSelectPseudo(*SelectMBBI)) {
8805       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8806       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8807               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8808           .addReg(SelectMBBI->getOperand(4).getReg())
8809           .addMBB(HeadMBB)
8810           .addReg(SelectMBBI->getOperand(5).getReg())
8811           .addMBB(IfFalseMBB);
8812       SelectMBBI->eraseFromParent();
8813     }
8814     SelectMBBI = Next;
8815   }
8816 
8817   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8818   return TailMBB;
8819 }
8820 
8821 MachineBasicBlock *
8822 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8823                                                  MachineBasicBlock *BB) const {
8824   switch (MI.getOpcode()) {
8825   default:
8826     llvm_unreachable("Unexpected instr type to insert");
8827   case RISCV::ReadCycleWide:
8828     assert(!Subtarget.is64Bit() &&
8829            "ReadCycleWrite is only to be used on riscv32");
8830     return emitReadCycleWidePseudo(MI, BB);
8831   case RISCV::Select_GPR_Using_CC_GPR:
8832   case RISCV::Select_FPR16_Using_CC_GPR:
8833   case RISCV::Select_FPR32_Using_CC_GPR:
8834   case RISCV::Select_FPR64_Using_CC_GPR:
8835     return emitSelectPseudo(MI, BB, Subtarget);
8836   case RISCV::BuildPairF64Pseudo:
8837     return emitBuildPairF64Pseudo(MI, BB);
8838   case RISCV::SplitF64Pseudo:
8839     return emitSplitF64Pseudo(MI, BB);
8840   case RISCV::PseudoQuietFLE_H:
8841     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8842   case RISCV::PseudoQuietFLT_H:
8843     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8844   case RISCV::PseudoQuietFLE_S:
8845     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8846   case RISCV::PseudoQuietFLT_S:
8847     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8848   case RISCV::PseudoQuietFLE_D:
8849     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8850   case RISCV::PseudoQuietFLT_D:
8851     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8852   }
8853 }
8854 
8855 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8856                                                         SDNode *Node) const {
8857   // Add FRM dependency to any instructions with dynamic rounding mode.
8858   unsigned Opc = MI.getOpcode();
8859   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8860   if (Idx < 0)
8861     return;
8862   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8863     return;
8864   // If the instruction already reads FRM, don't add another read.
8865   if (MI.readsRegister(RISCV::FRM))
8866     return;
8867   MI.addOperand(
8868       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8869 }
8870 
8871 // Calling Convention Implementation.
8872 // The expectations for frontend ABI lowering vary from target to target.
8873 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8874 // details, but this is a longer term goal. For now, we simply try to keep the
8875 // role of the frontend as simple and well-defined as possible. The rules can
8876 // be summarised as:
8877 // * Never split up large scalar arguments. We handle them here.
8878 // * If a hardfloat calling convention is being used, and the struct may be
8879 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8880 // available, then pass as two separate arguments. If either the GPRs or FPRs
8881 // are exhausted, then pass according to the rule below.
8882 // * If a struct could never be passed in registers or directly in a stack
8883 // slot (as it is larger than 2*XLEN and the floating point rules don't
8884 // apply), then pass it using a pointer with the byval attribute.
8885 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8886 // word-sized array or a 2*XLEN scalar (depending on alignment).
8887 // * The frontend can determine whether a struct is returned by reference or
8888 // not based on its size and fields. If it will be returned by reference, the
8889 // frontend must modify the prototype so a pointer with the sret annotation is
8890 // passed as the first argument. This is not necessary for large scalar
8891 // returns.
8892 // * Struct return values and varargs should be coerced to structs containing
8893 // register-size fields in the same situations they would be for fixed
8894 // arguments.
8895 
8896 static const MCPhysReg ArgGPRs[] = {
8897   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8898   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8899 };
8900 static const MCPhysReg ArgFPR16s[] = {
8901   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8902   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8903 };
8904 static const MCPhysReg ArgFPR32s[] = {
8905   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8906   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8907 };
8908 static const MCPhysReg ArgFPR64s[] = {
8909   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8910   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8911 };
8912 // This is an interim calling convention and it may be changed in the future.
8913 static const MCPhysReg ArgVRs[] = {
8914     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8915     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8916     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8917 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8918                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8919                                      RISCV::V20M2, RISCV::V22M2};
8920 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8921                                      RISCV::V20M4};
8922 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8923 
8924 // Pass a 2*XLEN argument that has been split into two XLEN values through
8925 // registers or the stack as necessary.
8926 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8927                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8928                                 MVT ValVT2, MVT LocVT2,
8929                                 ISD::ArgFlagsTy ArgFlags2) {
8930   unsigned XLenInBytes = XLen / 8;
8931   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8932     // At least one half can be passed via register.
8933     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8934                                      VA1.getLocVT(), CCValAssign::Full));
8935   } else {
8936     // Both halves must be passed on the stack, with proper alignment.
8937     Align StackAlign =
8938         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8939     State.addLoc(
8940         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8941                             State.AllocateStack(XLenInBytes, StackAlign),
8942                             VA1.getLocVT(), CCValAssign::Full));
8943     State.addLoc(CCValAssign::getMem(
8944         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8945         LocVT2, CCValAssign::Full));
8946     return false;
8947   }
8948 
8949   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8950     // The second half can also be passed via register.
8951     State.addLoc(
8952         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8953   } else {
8954     // The second half is passed via the stack, without additional alignment.
8955     State.addLoc(CCValAssign::getMem(
8956         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8957         LocVT2, CCValAssign::Full));
8958   }
8959 
8960   return false;
8961 }
8962 
8963 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8964                                Optional<unsigned> FirstMaskArgument,
8965                                CCState &State, const RISCVTargetLowering &TLI) {
8966   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8967   if (RC == &RISCV::VRRegClass) {
8968     // Assign the first mask argument to V0.
8969     // This is an interim calling convention and it may be changed in the
8970     // future.
8971     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8972       return State.AllocateReg(RISCV::V0);
8973     return State.AllocateReg(ArgVRs);
8974   }
8975   if (RC == &RISCV::VRM2RegClass)
8976     return State.AllocateReg(ArgVRM2s);
8977   if (RC == &RISCV::VRM4RegClass)
8978     return State.AllocateReg(ArgVRM4s);
8979   if (RC == &RISCV::VRM8RegClass)
8980     return State.AllocateReg(ArgVRM8s);
8981   llvm_unreachable("Unhandled register class for ValueType");
8982 }
8983 
8984 // Implements the RISC-V calling convention. Returns true upon failure.
8985 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8986                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8987                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8988                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8989                      Optional<unsigned> FirstMaskArgument) {
8990   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8991   assert(XLen == 32 || XLen == 64);
8992   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8993 
8994   // Any return value split in to more than two values can't be returned
8995   // directly. Vectors are returned via the available vector registers.
8996   if (!LocVT.isVector() && IsRet && ValNo > 1)
8997     return true;
8998 
8999   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9000   // variadic argument, or if no F16/F32 argument registers are available.
9001   bool UseGPRForF16_F32 = true;
9002   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9003   // variadic argument, or if no F64 argument registers are available.
9004   bool UseGPRForF64 = true;
9005 
9006   switch (ABI) {
9007   default:
9008     llvm_unreachable("Unexpected ABI");
9009   case RISCVABI::ABI_ILP32:
9010   case RISCVABI::ABI_LP64:
9011     break;
9012   case RISCVABI::ABI_ILP32F:
9013   case RISCVABI::ABI_LP64F:
9014     UseGPRForF16_F32 = !IsFixed;
9015     break;
9016   case RISCVABI::ABI_ILP32D:
9017   case RISCVABI::ABI_LP64D:
9018     UseGPRForF16_F32 = !IsFixed;
9019     UseGPRForF64 = !IsFixed;
9020     break;
9021   }
9022 
9023   // FPR16, FPR32, and FPR64 alias each other.
9024   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9025     UseGPRForF16_F32 = true;
9026     UseGPRForF64 = true;
9027   }
9028 
9029   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9030   // similar local variables rather than directly checking against the target
9031   // ABI.
9032 
9033   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9034     LocVT = XLenVT;
9035     LocInfo = CCValAssign::BCvt;
9036   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9037     LocVT = MVT::i64;
9038     LocInfo = CCValAssign::BCvt;
9039   }
9040 
9041   // If this is a variadic argument, the RISC-V calling convention requires
9042   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9043   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9044   // be used regardless of whether the original argument was split during
9045   // legalisation or not. The argument will not be passed by registers if the
9046   // original type is larger than 2*XLEN, so the register alignment rule does
9047   // not apply.
9048   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9049   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9050       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9051     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9052     // Skip 'odd' register if necessary.
9053     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9054       State.AllocateReg(ArgGPRs);
9055   }
9056 
9057   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9058   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9059       State.getPendingArgFlags();
9060 
9061   assert(PendingLocs.size() == PendingArgFlags.size() &&
9062          "PendingLocs and PendingArgFlags out of sync");
9063 
9064   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9065   // registers are exhausted.
9066   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9067     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9068            "Can't lower f64 if it is split");
9069     // Depending on available argument GPRS, f64 may be passed in a pair of
9070     // GPRs, split between a GPR and the stack, or passed completely on the
9071     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9072     // cases.
9073     Register Reg = State.AllocateReg(ArgGPRs);
9074     LocVT = MVT::i32;
9075     if (!Reg) {
9076       unsigned StackOffset = State.AllocateStack(8, Align(8));
9077       State.addLoc(
9078           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9079       return false;
9080     }
9081     if (!State.AllocateReg(ArgGPRs))
9082       State.AllocateStack(4, Align(4));
9083     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9084     return false;
9085   }
9086 
9087   // Fixed-length vectors are located in the corresponding scalable-vector
9088   // container types.
9089   if (ValVT.isFixedLengthVector())
9090     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9091 
9092   // Split arguments might be passed indirectly, so keep track of the pending
9093   // values. Split vectors are passed via a mix of registers and indirectly, so
9094   // treat them as we would any other argument.
9095   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9096     LocVT = XLenVT;
9097     LocInfo = CCValAssign::Indirect;
9098     PendingLocs.push_back(
9099         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9100     PendingArgFlags.push_back(ArgFlags);
9101     if (!ArgFlags.isSplitEnd()) {
9102       return false;
9103     }
9104   }
9105 
9106   // If the split argument only had two elements, it should be passed directly
9107   // in registers or on the stack.
9108   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9109       PendingLocs.size() <= 2) {
9110     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9111     // Apply the normal calling convention rules to the first half of the
9112     // split argument.
9113     CCValAssign VA = PendingLocs[0];
9114     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9115     PendingLocs.clear();
9116     PendingArgFlags.clear();
9117     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9118                                ArgFlags);
9119   }
9120 
9121   // Allocate to a register if possible, or else a stack slot.
9122   Register Reg;
9123   unsigned StoreSizeBytes = XLen / 8;
9124   Align StackAlign = Align(XLen / 8);
9125 
9126   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9127     Reg = State.AllocateReg(ArgFPR16s);
9128   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9129     Reg = State.AllocateReg(ArgFPR32s);
9130   else if (ValVT == MVT::f64 && !UseGPRForF64)
9131     Reg = State.AllocateReg(ArgFPR64s);
9132   else if (ValVT.isVector()) {
9133     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9134     if (!Reg) {
9135       // For return values, the vector must be passed fully via registers or
9136       // via the stack.
9137       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9138       // but we're using all of them.
9139       if (IsRet)
9140         return true;
9141       // Try using a GPR to pass the address
9142       if ((Reg = State.AllocateReg(ArgGPRs))) {
9143         LocVT = XLenVT;
9144         LocInfo = CCValAssign::Indirect;
9145       } else if (ValVT.isScalableVector()) {
9146         LocVT = XLenVT;
9147         LocInfo = CCValAssign::Indirect;
9148       } else {
9149         // Pass fixed-length vectors on the stack.
9150         LocVT = ValVT;
9151         StoreSizeBytes = ValVT.getStoreSize();
9152         // Align vectors to their element sizes, being careful for vXi1
9153         // vectors.
9154         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9155       }
9156     }
9157   } else {
9158     Reg = State.AllocateReg(ArgGPRs);
9159   }
9160 
9161   unsigned StackOffset =
9162       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9163 
9164   // If we reach this point and PendingLocs is non-empty, we must be at the
9165   // end of a split argument that must be passed indirectly.
9166   if (!PendingLocs.empty()) {
9167     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9168     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9169 
9170     for (auto &It : PendingLocs) {
9171       if (Reg)
9172         It.convertToReg(Reg);
9173       else
9174         It.convertToMem(StackOffset);
9175       State.addLoc(It);
9176     }
9177     PendingLocs.clear();
9178     PendingArgFlags.clear();
9179     return false;
9180   }
9181 
9182   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9183           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9184          "Expected an XLenVT or vector types at this stage");
9185 
9186   if (Reg) {
9187     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9188     return false;
9189   }
9190 
9191   // When a floating-point value is passed on the stack, no bit-conversion is
9192   // needed.
9193   if (ValVT.isFloatingPoint()) {
9194     LocVT = ValVT;
9195     LocInfo = CCValAssign::Full;
9196   }
9197   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9198   return false;
9199 }
9200 
9201 template <typename ArgTy>
9202 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9203   for (const auto &ArgIdx : enumerate(Args)) {
9204     MVT ArgVT = ArgIdx.value().VT;
9205     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9206       return ArgIdx.index();
9207   }
9208   return None;
9209 }
9210 
9211 void RISCVTargetLowering::analyzeInputArgs(
9212     MachineFunction &MF, CCState &CCInfo,
9213     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9214     RISCVCCAssignFn Fn) const {
9215   unsigned NumArgs = Ins.size();
9216   FunctionType *FType = MF.getFunction().getFunctionType();
9217 
9218   Optional<unsigned> FirstMaskArgument;
9219   if (Subtarget.hasVInstructions())
9220     FirstMaskArgument = preAssignMask(Ins);
9221 
9222   for (unsigned i = 0; i != NumArgs; ++i) {
9223     MVT ArgVT = Ins[i].VT;
9224     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9225 
9226     Type *ArgTy = nullptr;
9227     if (IsRet)
9228       ArgTy = FType->getReturnType();
9229     else if (Ins[i].isOrigArg())
9230       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9231 
9232     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9233     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9234            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9235            FirstMaskArgument)) {
9236       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9237                         << EVT(ArgVT).getEVTString() << '\n');
9238       llvm_unreachable(nullptr);
9239     }
9240   }
9241 }
9242 
9243 void RISCVTargetLowering::analyzeOutputArgs(
9244     MachineFunction &MF, CCState &CCInfo,
9245     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9246     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9247   unsigned NumArgs = Outs.size();
9248 
9249   Optional<unsigned> FirstMaskArgument;
9250   if (Subtarget.hasVInstructions())
9251     FirstMaskArgument = preAssignMask(Outs);
9252 
9253   for (unsigned i = 0; i != NumArgs; i++) {
9254     MVT ArgVT = Outs[i].VT;
9255     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9256     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9257 
9258     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9259     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9260            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9261            FirstMaskArgument)) {
9262       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9263                         << EVT(ArgVT).getEVTString() << "\n");
9264       llvm_unreachable(nullptr);
9265     }
9266   }
9267 }
9268 
9269 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9270 // values.
9271 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9272                                    const CCValAssign &VA, const SDLoc &DL,
9273                                    const RISCVSubtarget &Subtarget) {
9274   switch (VA.getLocInfo()) {
9275   default:
9276     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9277   case CCValAssign::Full:
9278     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9279       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9280     break;
9281   case CCValAssign::BCvt:
9282     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9283       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9284     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9285       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9286     else
9287       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9288     break;
9289   }
9290   return Val;
9291 }
9292 
9293 // The caller is responsible for loading the full value if the argument is
9294 // passed with CCValAssign::Indirect.
9295 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9296                                 const CCValAssign &VA, const SDLoc &DL,
9297                                 const RISCVTargetLowering &TLI) {
9298   MachineFunction &MF = DAG.getMachineFunction();
9299   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9300   EVT LocVT = VA.getLocVT();
9301   SDValue Val;
9302   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9303   Register VReg = RegInfo.createVirtualRegister(RC);
9304   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9305   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9306 
9307   if (VA.getLocInfo() == CCValAssign::Indirect)
9308     return Val;
9309 
9310   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9311 }
9312 
9313 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9314                                    const CCValAssign &VA, const SDLoc &DL,
9315                                    const RISCVSubtarget &Subtarget) {
9316   EVT LocVT = VA.getLocVT();
9317 
9318   switch (VA.getLocInfo()) {
9319   default:
9320     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9321   case CCValAssign::Full:
9322     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9323       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9324     break;
9325   case CCValAssign::BCvt:
9326     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9327       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9328     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9329       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9330     else
9331       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9332     break;
9333   }
9334   return Val;
9335 }
9336 
9337 // The caller is responsible for loading the full value if the argument is
9338 // passed with CCValAssign::Indirect.
9339 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9340                                 const CCValAssign &VA, const SDLoc &DL) {
9341   MachineFunction &MF = DAG.getMachineFunction();
9342   MachineFrameInfo &MFI = MF.getFrameInfo();
9343   EVT LocVT = VA.getLocVT();
9344   EVT ValVT = VA.getValVT();
9345   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9346   if (ValVT.isScalableVector()) {
9347     // When the value is a scalable vector, we save the pointer which points to
9348     // the scalable vector value in the stack. The ValVT will be the pointer
9349     // type, instead of the scalable vector type.
9350     ValVT = LocVT;
9351   }
9352   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9353                                  /*IsImmutable=*/true);
9354   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9355   SDValue Val;
9356 
9357   ISD::LoadExtType ExtType;
9358   switch (VA.getLocInfo()) {
9359   default:
9360     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9361   case CCValAssign::Full:
9362   case CCValAssign::Indirect:
9363   case CCValAssign::BCvt:
9364     ExtType = ISD::NON_EXTLOAD;
9365     break;
9366   }
9367   Val = DAG.getExtLoad(
9368       ExtType, DL, LocVT, Chain, FIN,
9369       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9370   return Val;
9371 }
9372 
9373 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9374                                        const CCValAssign &VA, const SDLoc &DL) {
9375   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9376          "Unexpected VA");
9377   MachineFunction &MF = DAG.getMachineFunction();
9378   MachineFrameInfo &MFI = MF.getFrameInfo();
9379   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9380 
9381   if (VA.isMemLoc()) {
9382     // f64 is passed on the stack.
9383     int FI =
9384         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9385     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9386     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9387                        MachinePointerInfo::getFixedStack(MF, FI));
9388   }
9389 
9390   assert(VA.isRegLoc() && "Expected register VA assignment");
9391 
9392   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9393   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9394   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9395   SDValue Hi;
9396   if (VA.getLocReg() == RISCV::X17) {
9397     // Second half of f64 is passed on the stack.
9398     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9399     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9400     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9401                      MachinePointerInfo::getFixedStack(MF, FI));
9402   } else {
9403     // Second half of f64 is passed in another GPR.
9404     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9405     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9406     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9407   }
9408   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9409 }
9410 
9411 // FastCC has less than 1% performance improvement for some particular
9412 // benchmark. But theoretically, it may has benenfit for some cases.
9413 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9414                             unsigned ValNo, MVT ValVT, MVT LocVT,
9415                             CCValAssign::LocInfo LocInfo,
9416                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9417                             bool IsFixed, bool IsRet, Type *OrigTy,
9418                             const RISCVTargetLowering &TLI,
9419                             Optional<unsigned> FirstMaskArgument) {
9420 
9421   // X5 and X6 might be used for save-restore libcall.
9422   static const MCPhysReg GPRList[] = {
9423       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9424       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9425       RISCV::X29, RISCV::X30, RISCV::X31};
9426 
9427   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9428     if (unsigned Reg = State.AllocateReg(GPRList)) {
9429       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9430       return false;
9431     }
9432   }
9433 
9434   if (LocVT == MVT::f16) {
9435     static const MCPhysReg FPR16List[] = {
9436         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9437         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9438         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9439         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9440     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9441       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9442       return false;
9443     }
9444   }
9445 
9446   if (LocVT == MVT::f32) {
9447     static const MCPhysReg FPR32List[] = {
9448         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9449         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9450         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9451         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9452     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9453       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9454       return false;
9455     }
9456   }
9457 
9458   if (LocVT == MVT::f64) {
9459     static const MCPhysReg FPR64List[] = {
9460         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9461         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9462         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9463         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9464     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9465       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9466       return false;
9467     }
9468   }
9469 
9470   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9471     unsigned Offset4 = State.AllocateStack(4, Align(4));
9472     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9473     return false;
9474   }
9475 
9476   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9477     unsigned Offset5 = State.AllocateStack(8, Align(8));
9478     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9479     return false;
9480   }
9481 
9482   if (LocVT.isVector()) {
9483     if (unsigned Reg =
9484             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9485       // Fixed-length vectors are located in the corresponding scalable-vector
9486       // container types.
9487       if (ValVT.isFixedLengthVector())
9488         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9489       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9490     } else {
9491       // Try and pass the address via a "fast" GPR.
9492       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9493         LocInfo = CCValAssign::Indirect;
9494         LocVT = TLI.getSubtarget().getXLenVT();
9495         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9496       } else if (ValVT.isFixedLengthVector()) {
9497         auto StackAlign =
9498             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9499         unsigned StackOffset =
9500             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9501         State.addLoc(
9502             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9503       } else {
9504         // Can't pass scalable vectors on the stack.
9505         return true;
9506       }
9507     }
9508 
9509     return false;
9510   }
9511 
9512   return true; // CC didn't match.
9513 }
9514 
9515 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9516                          CCValAssign::LocInfo LocInfo,
9517                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9518 
9519   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9520     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9521     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9522     static const MCPhysReg GPRList[] = {
9523         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9524         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9525     if (unsigned Reg = State.AllocateReg(GPRList)) {
9526       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9527       return false;
9528     }
9529   }
9530 
9531   if (LocVT == MVT::f32) {
9532     // Pass in STG registers: F1, ..., F6
9533     //                        fs0 ... fs5
9534     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9535                                           RISCV::F18_F, RISCV::F19_F,
9536                                           RISCV::F20_F, RISCV::F21_F};
9537     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9538       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9539       return false;
9540     }
9541   }
9542 
9543   if (LocVT == MVT::f64) {
9544     // Pass in STG registers: D1, ..., D6
9545     //                        fs6 ... fs11
9546     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9547                                           RISCV::F24_D, RISCV::F25_D,
9548                                           RISCV::F26_D, RISCV::F27_D};
9549     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9550       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9551       return false;
9552     }
9553   }
9554 
9555   report_fatal_error("No registers left in GHC calling convention");
9556   return true;
9557 }
9558 
9559 // Transform physical registers into virtual registers.
9560 SDValue RISCVTargetLowering::LowerFormalArguments(
9561     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9562     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9563     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9564 
9565   MachineFunction &MF = DAG.getMachineFunction();
9566 
9567   switch (CallConv) {
9568   default:
9569     report_fatal_error("Unsupported calling convention");
9570   case CallingConv::C:
9571   case CallingConv::Fast:
9572     break;
9573   case CallingConv::GHC:
9574     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9575         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9576       report_fatal_error(
9577         "GHC calling convention requires the F and D instruction set extensions");
9578   }
9579 
9580   const Function &Func = MF.getFunction();
9581   if (Func.hasFnAttribute("interrupt")) {
9582     if (!Func.arg_empty())
9583       report_fatal_error(
9584         "Functions with the interrupt attribute cannot have arguments!");
9585 
9586     StringRef Kind =
9587       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9588 
9589     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9590       report_fatal_error(
9591         "Function interrupt attribute argument not supported!");
9592   }
9593 
9594   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9595   MVT XLenVT = Subtarget.getXLenVT();
9596   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9597   // Used with vargs to acumulate store chains.
9598   std::vector<SDValue> OutChains;
9599 
9600   // Assign locations to all of the incoming arguments.
9601   SmallVector<CCValAssign, 16> ArgLocs;
9602   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9603 
9604   if (CallConv == CallingConv::GHC)
9605     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9606   else
9607     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9608                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9609                                                    : CC_RISCV);
9610 
9611   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9612     CCValAssign &VA = ArgLocs[i];
9613     SDValue ArgValue;
9614     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9615     // case.
9616     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9617       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9618     else if (VA.isRegLoc())
9619       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9620     else
9621       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9622 
9623     if (VA.getLocInfo() == CCValAssign::Indirect) {
9624       // If the original argument was split and passed by reference (e.g. i128
9625       // on RV32), we need to load all parts of it here (using the same
9626       // address). Vectors may be partly split to registers and partly to the
9627       // stack, in which case the base address is partly offset and subsequent
9628       // stores are relative to that.
9629       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9630                                    MachinePointerInfo()));
9631       unsigned ArgIndex = Ins[i].OrigArgIndex;
9632       unsigned ArgPartOffset = Ins[i].PartOffset;
9633       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9634       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9635         CCValAssign &PartVA = ArgLocs[i + 1];
9636         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9637         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9638         if (PartVA.getValVT().isScalableVector())
9639           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9640         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9641         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9642                                      MachinePointerInfo()));
9643         ++i;
9644       }
9645       continue;
9646     }
9647     InVals.push_back(ArgValue);
9648   }
9649 
9650   if (IsVarArg) {
9651     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9652     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9653     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9654     MachineFrameInfo &MFI = MF.getFrameInfo();
9655     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9656     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9657 
9658     // Offset of the first variable argument from stack pointer, and size of
9659     // the vararg save area. For now, the varargs save area is either zero or
9660     // large enough to hold a0-a7.
9661     int VaArgOffset, VarArgsSaveSize;
9662 
9663     // If all registers are allocated, then all varargs must be passed on the
9664     // stack and we don't need to save any argregs.
9665     if (ArgRegs.size() == Idx) {
9666       VaArgOffset = CCInfo.getNextStackOffset();
9667       VarArgsSaveSize = 0;
9668     } else {
9669       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9670       VaArgOffset = -VarArgsSaveSize;
9671     }
9672 
9673     // Record the frame index of the first variable argument
9674     // which is a value necessary to VASTART.
9675     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9676     RVFI->setVarArgsFrameIndex(FI);
9677 
9678     // If saving an odd number of registers then create an extra stack slot to
9679     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9680     // offsets to even-numbered registered remain 2*XLEN-aligned.
9681     if (Idx % 2) {
9682       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9683       VarArgsSaveSize += XLenInBytes;
9684     }
9685 
9686     // Copy the integer registers that may have been used for passing varargs
9687     // to the vararg save area.
9688     for (unsigned I = Idx; I < ArgRegs.size();
9689          ++I, VaArgOffset += XLenInBytes) {
9690       const Register Reg = RegInfo.createVirtualRegister(RC);
9691       RegInfo.addLiveIn(ArgRegs[I], Reg);
9692       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9693       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9694       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9695       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9696                                    MachinePointerInfo::getFixedStack(MF, FI));
9697       cast<StoreSDNode>(Store.getNode())
9698           ->getMemOperand()
9699           ->setValue((Value *)nullptr);
9700       OutChains.push_back(Store);
9701     }
9702     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9703   }
9704 
9705   // All stores are grouped in one node to allow the matching between
9706   // the size of Ins and InVals. This only happens for vararg functions.
9707   if (!OutChains.empty()) {
9708     OutChains.push_back(Chain);
9709     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9710   }
9711 
9712   return Chain;
9713 }
9714 
9715 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9716 /// for tail call optimization.
9717 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9718 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9719     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9720     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9721 
9722   auto &Callee = CLI.Callee;
9723   auto CalleeCC = CLI.CallConv;
9724   auto &Outs = CLI.Outs;
9725   auto &Caller = MF.getFunction();
9726   auto CallerCC = Caller.getCallingConv();
9727 
9728   // Exception-handling functions need a special set of instructions to
9729   // indicate a return to the hardware. Tail-calling another function would
9730   // probably break this.
9731   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9732   // should be expanded as new function attributes are introduced.
9733   if (Caller.hasFnAttribute("interrupt"))
9734     return false;
9735 
9736   // Do not tail call opt if the stack is used to pass parameters.
9737   if (CCInfo.getNextStackOffset() != 0)
9738     return false;
9739 
9740   // Do not tail call opt if any parameters need to be passed indirectly.
9741   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9742   // passed indirectly. So the address of the value will be passed in a
9743   // register, or if not available, then the address is put on the stack. In
9744   // order to pass indirectly, space on the stack often needs to be allocated
9745   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9746   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9747   // are passed CCValAssign::Indirect.
9748   for (auto &VA : ArgLocs)
9749     if (VA.getLocInfo() == CCValAssign::Indirect)
9750       return false;
9751 
9752   // Do not tail call opt if either caller or callee uses struct return
9753   // semantics.
9754   auto IsCallerStructRet = Caller.hasStructRetAttr();
9755   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9756   if (IsCallerStructRet || IsCalleeStructRet)
9757     return false;
9758 
9759   // Externally-defined functions with weak linkage should not be
9760   // tail-called. The behaviour of branch instructions in this situation (as
9761   // used for tail calls) is implementation-defined, so we cannot rely on the
9762   // linker replacing the tail call with a return.
9763   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9764     const GlobalValue *GV = G->getGlobal();
9765     if (GV->hasExternalWeakLinkage())
9766       return false;
9767   }
9768 
9769   // The callee has to preserve all registers the caller needs to preserve.
9770   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9771   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9772   if (CalleeCC != CallerCC) {
9773     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9774     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9775       return false;
9776   }
9777 
9778   // Byval parameters hand the function a pointer directly into the stack area
9779   // we want to reuse during a tail call. Working around this *is* possible
9780   // but less efficient and uglier in LowerCall.
9781   for (auto &Arg : Outs)
9782     if (Arg.Flags.isByVal())
9783       return false;
9784 
9785   return true;
9786 }
9787 
9788 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9789   return DAG.getDataLayout().getPrefTypeAlign(
9790       VT.getTypeForEVT(*DAG.getContext()));
9791 }
9792 
9793 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9794 // and output parameter nodes.
9795 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9796                                        SmallVectorImpl<SDValue> &InVals) const {
9797   SelectionDAG &DAG = CLI.DAG;
9798   SDLoc &DL = CLI.DL;
9799   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9800   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9801   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9802   SDValue Chain = CLI.Chain;
9803   SDValue Callee = CLI.Callee;
9804   bool &IsTailCall = CLI.IsTailCall;
9805   CallingConv::ID CallConv = CLI.CallConv;
9806   bool IsVarArg = CLI.IsVarArg;
9807   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9808   MVT XLenVT = Subtarget.getXLenVT();
9809 
9810   MachineFunction &MF = DAG.getMachineFunction();
9811 
9812   // Analyze the operands of the call, assigning locations to each operand.
9813   SmallVector<CCValAssign, 16> ArgLocs;
9814   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9815 
9816   if (CallConv == CallingConv::GHC)
9817     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9818   else
9819     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9820                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9821                                                     : CC_RISCV);
9822 
9823   // Check if it's really possible to do a tail call.
9824   if (IsTailCall)
9825     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9826 
9827   if (IsTailCall)
9828     ++NumTailCalls;
9829   else if (CLI.CB && CLI.CB->isMustTailCall())
9830     report_fatal_error("failed to perform tail call elimination on a call "
9831                        "site marked musttail");
9832 
9833   // Get a count of how many bytes are to be pushed on the stack.
9834   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9835 
9836   // Create local copies for byval args
9837   SmallVector<SDValue, 8> ByValArgs;
9838   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9839     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9840     if (!Flags.isByVal())
9841       continue;
9842 
9843     SDValue Arg = OutVals[i];
9844     unsigned Size = Flags.getByValSize();
9845     Align Alignment = Flags.getNonZeroByValAlign();
9846 
9847     int FI =
9848         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9849     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9850     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9851 
9852     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9853                           /*IsVolatile=*/false,
9854                           /*AlwaysInline=*/false, IsTailCall,
9855                           MachinePointerInfo(), MachinePointerInfo());
9856     ByValArgs.push_back(FIPtr);
9857   }
9858 
9859   if (!IsTailCall)
9860     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9861 
9862   // Copy argument values to their designated locations.
9863   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9864   SmallVector<SDValue, 8> MemOpChains;
9865   SDValue StackPtr;
9866   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9867     CCValAssign &VA = ArgLocs[i];
9868     SDValue ArgValue = OutVals[i];
9869     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9870 
9871     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9872     bool IsF64OnRV32DSoftABI =
9873         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9874     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9875       SDValue SplitF64 = DAG.getNode(
9876           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9877       SDValue Lo = SplitF64.getValue(0);
9878       SDValue Hi = SplitF64.getValue(1);
9879 
9880       Register RegLo = VA.getLocReg();
9881       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9882 
9883       if (RegLo == RISCV::X17) {
9884         // Second half of f64 is passed on the stack.
9885         // Work out the address of the stack slot.
9886         if (!StackPtr.getNode())
9887           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9888         // Emit the store.
9889         MemOpChains.push_back(
9890             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9891       } else {
9892         // Second half of f64 is passed in another GPR.
9893         assert(RegLo < RISCV::X31 && "Invalid register pair");
9894         Register RegHigh = RegLo + 1;
9895         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9896       }
9897       continue;
9898     }
9899 
9900     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9901     // as any other MemLoc.
9902 
9903     // Promote the value if needed.
9904     // For now, only handle fully promoted and indirect arguments.
9905     if (VA.getLocInfo() == CCValAssign::Indirect) {
9906       // Store the argument in a stack slot and pass its address.
9907       Align StackAlign =
9908           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9909                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9910       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9911       // If the original argument was split (e.g. i128), we need
9912       // to store the required parts of it here (and pass just one address).
9913       // Vectors may be partly split to registers and partly to the stack, in
9914       // which case the base address is partly offset and subsequent stores are
9915       // relative to that.
9916       unsigned ArgIndex = Outs[i].OrigArgIndex;
9917       unsigned ArgPartOffset = Outs[i].PartOffset;
9918       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9919       // Calculate the total size to store. We don't have access to what we're
9920       // actually storing other than performing the loop and collecting the
9921       // info.
9922       SmallVector<std::pair<SDValue, SDValue>> Parts;
9923       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9924         SDValue PartValue = OutVals[i + 1];
9925         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9926         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9927         EVT PartVT = PartValue.getValueType();
9928         if (PartVT.isScalableVector())
9929           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9930         StoredSize += PartVT.getStoreSize();
9931         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9932         Parts.push_back(std::make_pair(PartValue, Offset));
9933         ++i;
9934       }
9935       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9936       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9937       MemOpChains.push_back(
9938           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9939                        MachinePointerInfo::getFixedStack(MF, FI)));
9940       for (const auto &Part : Parts) {
9941         SDValue PartValue = Part.first;
9942         SDValue PartOffset = Part.second;
9943         SDValue Address =
9944             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9945         MemOpChains.push_back(
9946             DAG.getStore(Chain, DL, PartValue, Address,
9947                          MachinePointerInfo::getFixedStack(MF, FI)));
9948       }
9949       ArgValue = SpillSlot;
9950     } else {
9951       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9952     }
9953 
9954     // Use local copy if it is a byval arg.
9955     if (Flags.isByVal())
9956       ArgValue = ByValArgs[j++];
9957 
9958     if (VA.isRegLoc()) {
9959       // Queue up the argument copies and emit them at the end.
9960       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9961     } else {
9962       assert(VA.isMemLoc() && "Argument not register or memory");
9963       assert(!IsTailCall && "Tail call not allowed if stack is used "
9964                             "for passing parameters");
9965 
9966       // Work out the address of the stack slot.
9967       if (!StackPtr.getNode())
9968         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9969       SDValue Address =
9970           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9971                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9972 
9973       // Emit the store.
9974       MemOpChains.push_back(
9975           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9976     }
9977   }
9978 
9979   // Join the stores, which are independent of one another.
9980   if (!MemOpChains.empty())
9981     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9982 
9983   SDValue Glue;
9984 
9985   // Build a sequence of copy-to-reg nodes, chained and glued together.
9986   for (auto &Reg : RegsToPass) {
9987     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9988     Glue = Chain.getValue(1);
9989   }
9990 
9991   // Validate that none of the argument registers have been marked as
9992   // reserved, if so report an error. Do the same for the return address if this
9993   // is not a tailcall.
9994   validateCCReservedRegs(RegsToPass, MF);
9995   if (!IsTailCall &&
9996       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9997     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9998         MF.getFunction(),
9999         "Return address register required, but has been reserved."});
10000 
10001   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10002   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10003   // split it and then direct call can be matched by PseudoCALL.
10004   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10005     const GlobalValue *GV = S->getGlobal();
10006 
10007     unsigned OpFlags = RISCVII::MO_CALL;
10008     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10009       OpFlags = RISCVII::MO_PLT;
10010 
10011     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10012   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10013     unsigned OpFlags = RISCVII::MO_CALL;
10014 
10015     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10016                                                  nullptr))
10017       OpFlags = RISCVII::MO_PLT;
10018 
10019     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10020   }
10021 
10022   // The first call operand is the chain and the second is the target address.
10023   SmallVector<SDValue, 8> Ops;
10024   Ops.push_back(Chain);
10025   Ops.push_back(Callee);
10026 
10027   // Add argument registers to the end of the list so that they are
10028   // known live into the call.
10029   for (auto &Reg : RegsToPass)
10030     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10031 
10032   if (!IsTailCall) {
10033     // Add a register mask operand representing the call-preserved registers.
10034     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10035     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10036     assert(Mask && "Missing call preserved mask for calling convention");
10037     Ops.push_back(DAG.getRegisterMask(Mask));
10038   }
10039 
10040   // Glue the call to the argument copies, if any.
10041   if (Glue.getNode())
10042     Ops.push_back(Glue);
10043 
10044   // Emit the call.
10045   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10046 
10047   if (IsTailCall) {
10048     MF.getFrameInfo().setHasTailCall();
10049     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10050   }
10051 
10052   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10053   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10054   Glue = Chain.getValue(1);
10055 
10056   // Mark the end of the call, which is glued to the call itself.
10057   Chain = DAG.getCALLSEQ_END(Chain,
10058                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10059                              DAG.getConstant(0, DL, PtrVT, true),
10060                              Glue, DL);
10061   Glue = Chain.getValue(1);
10062 
10063   // Assign locations to each value returned by this call.
10064   SmallVector<CCValAssign, 16> RVLocs;
10065   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10066   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10067 
10068   // Copy all of the result registers out of their specified physreg.
10069   for (auto &VA : RVLocs) {
10070     // Copy the value out
10071     SDValue RetValue =
10072         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10073     // Glue the RetValue to the end of the call sequence
10074     Chain = RetValue.getValue(1);
10075     Glue = RetValue.getValue(2);
10076 
10077     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10078       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10079       SDValue RetValue2 =
10080           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10081       Chain = RetValue2.getValue(1);
10082       Glue = RetValue2.getValue(2);
10083       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10084                              RetValue2);
10085     }
10086 
10087     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10088 
10089     InVals.push_back(RetValue);
10090   }
10091 
10092   return Chain;
10093 }
10094 
10095 bool RISCVTargetLowering::CanLowerReturn(
10096     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10097     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10098   SmallVector<CCValAssign, 16> RVLocs;
10099   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10100 
10101   Optional<unsigned> FirstMaskArgument;
10102   if (Subtarget.hasVInstructions())
10103     FirstMaskArgument = preAssignMask(Outs);
10104 
10105   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10106     MVT VT = Outs[i].VT;
10107     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10108     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10109     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10110                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10111                  *this, FirstMaskArgument))
10112       return false;
10113   }
10114   return true;
10115 }
10116 
10117 SDValue
10118 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10119                                  bool IsVarArg,
10120                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10121                                  const SmallVectorImpl<SDValue> &OutVals,
10122                                  const SDLoc &DL, SelectionDAG &DAG) const {
10123   const MachineFunction &MF = DAG.getMachineFunction();
10124   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10125 
10126   // Stores the assignment of the return value to a location.
10127   SmallVector<CCValAssign, 16> RVLocs;
10128 
10129   // Info about the registers and stack slot.
10130   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10131                  *DAG.getContext());
10132 
10133   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10134                     nullptr, CC_RISCV);
10135 
10136   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10137     report_fatal_error("GHC functions return void only");
10138 
10139   SDValue Glue;
10140   SmallVector<SDValue, 4> RetOps(1, Chain);
10141 
10142   // Copy the result values into the output registers.
10143   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10144     SDValue Val = OutVals[i];
10145     CCValAssign &VA = RVLocs[i];
10146     assert(VA.isRegLoc() && "Can only return in registers!");
10147 
10148     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10149       // Handle returning f64 on RV32D with a soft float ABI.
10150       assert(VA.isRegLoc() && "Expected return via registers");
10151       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10152                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10153       SDValue Lo = SplitF64.getValue(0);
10154       SDValue Hi = SplitF64.getValue(1);
10155       Register RegLo = VA.getLocReg();
10156       assert(RegLo < RISCV::X31 && "Invalid register pair");
10157       Register RegHi = RegLo + 1;
10158 
10159       if (STI.isRegisterReservedByUser(RegLo) ||
10160           STI.isRegisterReservedByUser(RegHi))
10161         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10162             MF.getFunction(),
10163             "Return value register required, but has been reserved."});
10164 
10165       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10166       Glue = Chain.getValue(1);
10167       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10168       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10169       Glue = Chain.getValue(1);
10170       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10171     } else {
10172       // Handle a 'normal' return.
10173       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10174       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10175 
10176       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10177         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10178             MF.getFunction(),
10179             "Return value register required, but has been reserved."});
10180 
10181       // Guarantee that all emitted copies are stuck together.
10182       Glue = Chain.getValue(1);
10183       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10184     }
10185   }
10186 
10187   RetOps[0] = Chain; // Update chain.
10188 
10189   // Add the glue node if we have it.
10190   if (Glue.getNode()) {
10191     RetOps.push_back(Glue);
10192   }
10193 
10194   unsigned RetOpc = RISCVISD::RET_FLAG;
10195   // Interrupt service routines use different return instructions.
10196   const Function &Func = DAG.getMachineFunction().getFunction();
10197   if (Func.hasFnAttribute("interrupt")) {
10198     if (!Func.getReturnType()->isVoidTy())
10199       report_fatal_error(
10200           "Functions with the interrupt attribute must have void return type!");
10201 
10202     MachineFunction &MF = DAG.getMachineFunction();
10203     StringRef Kind =
10204       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10205 
10206     if (Kind == "user")
10207       RetOpc = RISCVISD::URET_FLAG;
10208     else if (Kind == "supervisor")
10209       RetOpc = RISCVISD::SRET_FLAG;
10210     else
10211       RetOpc = RISCVISD::MRET_FLAG;
10212   }
10213 
10214   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10215 }
10216 
10217 void RISCVTargetLowering::validateCCReservedRegs(
10218     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10219     MachineFunction &MF) const {
10220   const Function &F = MF.getFunction();
10221   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10222 
10223   if (llvm::any_of(Regs, [&STI](auto Reg) {
10224         return STI.isRegisterReservedByUser(Reg.first);
10225       }))
10226     F.getContext().diagnose(DiagnosticInfoUnsupported{
10227         F, "Argument register required, but has been reserved."});
10228 }
10229 
10230 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10231   return CI->isTailCall();
10232 }
10233 
10234 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10235 #define NODE_NAME_CASE(NODE)                                                   \
10236   case RISCVISD::NODE:                                                         \
10237     return "RISCVISD::" #NODE;
10238   // clang-format off
10239   switch ((RISCVISD::NodeType)Opcode) {
10240   case RISCVISD::FIRST_NUMBER:
10241     break;
10242   NODE_NAME_CASE(RET_FLAG)
10243   NODE_NAME_CASE(URET_FLAG)
10244   NODE_NAME_CASE(SRET_FLAG)
10245   NODE_NAME_CASE(MRET_FLAG)
10246   NODE_NAME_CASE(CALL)
10247   NODE_NAME_CASE(SELECT_CC)
10248   NODE_NAME_CASE(BR_CC)
10249   NODE_NAME_CASE(BuildPairF64)
10250   NODE_NAME_CASE(SplitF64)
10251   NODE_NAME_CASE(TAIL)
10252   NODE_NAME_CASE(MULHSU)
10253   NODE_NAME_CASE(SLLW)
10254   NODE_NAME_CASE(SRAW)
10255   NODE_NAME_CASE(SRLW)
10256   NODE_NAME_CASE(DIVW)
10257   NODE_NAME_CASE(DIVUW)
10258   NODE_NAME_CASE(REMUW)
10259   NODE_NAME_CASE(ROLW)
10260   NODE_NAME_CASE(RORW)
10261   NODE_NAME_CASE(CLZW)
10262   NODE_NAME_CASE(CTZW)
10263   NODE_NAME_CASE(FSLW)
10264   NODE_NAME_CASE(FSRW)
10265   NODE_NAME_CASE(FSL)
10266   NODE_NAME_CASE(FSR)
10267   NODE_NAME_CASE(FMV_H_X)
10268   NODE_NAME_CASE(FMV_X_ANYEXTH)
10269   NODE_NAME_CASE(FMV_W_X_RV64)
10270   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10271   NODE_NAME_CASE(FCVT_X)
10272   NODE_NAME_CASE(FCVT_XU)
10273   NODE_NAME_CASE(FCVT_W_RV64)
10274   NODE_NAME_CASE(FCVT_WU_RV64)
10275   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10276   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10277   NODE_NAME_CASE(READ_CYCLE_WIDE)
10278   NODE_NAME_CASE(GREV)
10279   NODE_NAME_CASE(GREVW)
10280   NODE_NAME_CASE(GORC)
10281   NODE_NAME_CASE(GORCW)
10282   NODE_NAME_CASE(SHFL)
10283   NODE_NAME_CASE(SHFLW)
10284   NODE_NAME_CASE(UNSHFL)
10285   NODE_NAME_CASE(UNSHFLW)
10286   NODE_NAME_CASE(BFP)
10287   NODE_NAME_CASE(BFPW)
10288   NODE_NAME_CASE(BCOMPRESS)
10289   NODE_NAME_CASE(BCOMPRESSW)
10290   NODE_NAME_CASE(BDECOMPRESS)
10291   NODE_NAME_CASE(BDECOMPRESSW)
10292   NODE_NAME_CASE(VMV_V_X_VL)
10293   NODE_NAME_CASE(VFMV_V_F_VL)
10294   NODE_NAME_CASE(VMV_X_S)
10295   NODE_NAME_CASE(VMV_S_X_VL)
10296   NODE_NAME_CASE(VFMV_S_F_VL)
10297   NODE_NAME_CASE(SPLAT_VECTOR_I64)
10298   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10299   NODE_NAME_CASE(READ_VLENB)
10300   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10301   NODE_NAME_CASE(VSLIDEUP_VL)
10302   NODE_NAME_CASE(VSLIDE1UP_VL)
10303   NODE_NAME_CASE(VSLIDEDOWN_VL)
10304   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10305   NODE_NAME_CASE(VID_VL)
10306   NODE_NAME_CASE(VFNCVT_ROD_VL)
10307   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10308   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10309   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10310   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10311   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10312   NODE_NAME_CASE(VECREDUCE_AND_VL)
10313   NODE_NAME_CASE(VECREDUCE_OR_VL)
10314   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10315   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10316   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10317   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10318   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10319   NODE_NAME_CASE(ADD_VL)
10320   NODE_NAME_CASE(AND_VL)
10321   NODE_NAME_CASE(MUL_VL)
10322   NODE_NAME_CASE(OR_VL)
10323   NODE_NAME_CASE(SDIV_VL)
10324   NODE_NAME_CASE(SHL_VL)
10325   NODE_NAME_CASE(SREM_VL)
10326   NODE_NAME_CASE(SRA_VL)
10327   NODE_NAME_CASE(SRL_VL)
10328   NODE_NAME_CASE(SUB_VL)
10329   NODE_NAME_CASE(UDIV_VL)
10330   NODE_NAME_CASE(UREM_VL)
10331   NODE_NAME_CASE(XOR_VL)
10332   NODE_NAME_CASE(SADDSAT_VL)
10333   NODE_NAME_CASE(UADDSAT_VL)
10334   NODE_NAME_CASE(SSUBSAT_VL)
10335   NODE_NAME_CASE(USUBSAT_VL)
10336   NODE_NAME_CASE(FADD_VL)
10337   NODE_NAME_CASE(FSUB_VL)
10338   NODE_NAME_CASE(FMUL_VL)
10339   NODE_NAME_CASE(FDIV_VL)
10340   NODE_NAME_CASE(FNEG_VL)
10341   NODE_NAME_CASE(FABS_VL)
10342   NODE_NAME_CASE(FSQRT_VL)
10343   NODE_NAME_CASE(FMA_VL)
10344   NODE_NAME_CASE(FCOPYSIGN_VL)
10345   NODE_NAME_CASE(SMIN_VL)
10346   NODE_NAME_CASE(SMAX_VL)
10347   NODE_NAME_CASE(UMIN_VL)
10348   NODE_NAME_CASE(UMAX_VL)
10349   NODE_NAME_CASE(FMINNUM_VL)
10350   NODE_NAME_CASE(FMAXNUM_VL)
10351   NODE_NAME_CASE(MULHS_VL)
10352   NODE_NAME_CASE(MULHU_VL)
10353   NODE_NAME_CASE(FP_TO_SINT_VL)
10354   NODE_NAME_CASE(FP_TO_UINT_VL)
10355   NODE_NAME_CASE(SINT_TO_FP_VL)
10356   NODE_NAME_CASE(UINT_TO_FP_VL)
10357   NODE_NAME_CASE(FP_EXTEND_VL)
10358   NODE_NAME_CASE(FP_ROUND_VL)
10359   NODE_NAME_CASE(VWMUL_VL)
10360   NODE_NAME_CASE(VWMULU_VL)
10361   NODE_NAME_CASE(VWMULSU_VL)
10362   NODE_NAME_CASE(VWADD_VL)
10363   NODE_NAME_CASE(VWADDU_VL)
10364   NODE_NAME_CASE(VWSUB_VL)
10365   NODE_NAME_CASE(VWSUBU_VL)
10366   NODE_NAME_CASE(VWADD_W_VL)
10367   NODE_NAME_CASE(VWADDU_W_VL)
10368   NODE_NAME_CASE(VWSUB_W_VL)
10369   NODE_NAME_CASE(VWSUBU_W_VL)
10370   NODE_NAME_CASE(SETCC_VL)
10371   NODE_NAME_CASE(VSELECT_VL)
10372   NODE_NAME_CASE(VP_MERGE_VL)
10373   NODE_NAME_CASE(VMAND_VL)
10374   NODE_NAME_CASE(VMOR_VL)
10375   NODE_NAME_CASE(VMXOR_VL)
10376   NODE_NAME_CASE(VMCLR_VL)
10377   NODE_NAME_CASE(VMSET_VL)
10378   NODE_NAME_CASE(VRGATHER_VX_VL)
10379   NODE_NAME_CASE(VRGATHER_VV_VL)
10380   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10381   NODE_NAME_CASE(VSEXT_VL)
10382   NODE_NAME_CASE(VZEXT_VL)
10383   NODE_NAME_CASE(VCPOP_VL)
10384   NODE_NAME_CASE(VLE_VL)
10385   NODE_NAME_CASE(VSE_VL)
10386   NODE_NAME_CASE(READ_CSR)
10387   NODE_NAME_CASE(WRITE_CSR)
10388   NODE_NAME_CASE(SWAP_CSR)
10389   }
10390   // clang-format on
10391   return nullptr;
10392 #undef NODE_NAME_CASE
10393 }
10394 
10395 /// getConstraintType - Given a constraint letter, return the type of
10396 /// constraint it is for this target.
10397 RISCVTargetLowering::ConstraintType
10398 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10399   if (Constraint.size() == 1) {
10400     switch (Constraint[0]) {
10401     default:
10402       break;
10403     case 'f':
10404       return C_RegisterClass;
10405     case 'I':
10406     case 'J':
10407     case 'K':
10408       return C_Immediate;
10409     case 'A':
10410       return C_Memory;
10411     case 'S': // A symbolic address
10412       return C_Other;
10413     }
10414   } else {
10415     if (Constraint == "vr" || Constraint == "vm")
10416       return C_RegisterClass;
10417   }
10418   return TargetLowering::getConstraintType(Constraint);
10419 }
10420 
10421 std::pair<unsigned, const TargetRegisterClass *>
10422 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10423                                                   StringRef Constraint,
10424                                                   MVT VT) const {
10425   // First, see if this is a constraint that directly corresponds to a
10426   // RISCV register class.
10427   if (Constraint.size() == 1) {
10428     switch (Constraint[0]) {
10429     case 'r':
10430       // TODO: Support fixed vectors up to XLen for P extension?
10431       if (VT.isVector())
10432         break;
10433       return std::make_pair(0U, &RISCV::GPRRegClass);
10434     case 'f':
10435       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10436         return std::make_pair(0U, &RISCV::FPR16RegClass);
10437       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10438         return std::make_pair(0U, &RISCV::FPR32RegClass);
10439       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10440         return std::make_pair(0U, &RISCV::FPR64RegClass);
10441       break;
10442     default:
10443       break;
10444     }
10445   } else if (Constraint == "vr") {
10446     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10447                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10448       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10449         return std::make_pair(0U, RC);
10450     }
10451   } else if (Constraint == "vm") {
10452     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10453       return std::make_pair(0U, &RISCV::VMV0RegClass);
10454   }
10455 
10456   // Clang will correctly decode the usage of register name aliases into their
10457   // official names. However, other frontends like `rustc` do not. This allows
10458   // users of these frontends to use the ABI names for registers in LLVM-style
10459   // register constraints.
10460   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10461                                .Case("{zero}", RISCV::X0)
10462                                .Case("{ra}", RISCV::X1)
10463                                .Case("{sp}", RISCV::X2)
10464                                .Case("{gp}", RISCV::X3)
10465                                .Case("{tp}", RISCV::X4)
10466                                .Case("{t0}", RISCV::X5)
10467                                .Case("{t1}", RISCV::X6)
10468                                .Case("{t2}", RISCV::X7)
10469                                .Cases("{s0}", "{fp}", RISCV::X8)
10470                                .Case("{s1}", RISCV::X9)
10471                                .Case("{a0}", RISCV::X10)
10472                                .Case("{a1}", RISCV::X11)
10473                                .Case("{a2}", RISCV::X12)
10474                                .Case("{a3}", RISCV::X13)
10475                                .Case("{a4}", RISCV::X14)
10476                                .Case("{a5}", RISCV::X15)
10477                                .Case("{a6}", RISCV::X16)
10478                                .Case("{a7}", RISCV::X17)
10479                                .Case("{s2}", RISCV::X18)
10480                                .Case("{s3}", RISCV::X19)
10481                                .Case("{s4}", RISCV::X20)
10482                                .Case("{s5}", RISCV::X21)
10483                                .Case("{s6}", RISCV::X22)
10484                                .Case("{s7}", RISCV::X23)
10485                                .Case("{s8}", RISCV::X24)
10486                                .Case("{s9}", RISCV::X25)
10487                                .Case("{s10}", RISCV::X26)
10488                                .Case("{s11}", RISCV::X27)
10489                                .Case("{t3}", RISCV::X28)
10490                                .Case("{t4}", RISCV::X29)
10491                                .Case("{t5}", RISCV::X30)
10492                                .Case("{t6}", RISCV::X31)
10493                                .Default(RISCV::NoRegister);
10494   if (XRegFromAlias != RISCV::NoRegister)
10495     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10496 
10497   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10498   // TableGen record rather than the AsmName to choose registers for InlineAsm
10499   // constraints, plus we want to match those names to the widest floating point
10500   // register type available, manually select floating point registers here.
10501   //
10502   // The second case is the ABI name of the register, so that frontends can also
10503   // use the ABI names in register constraint lists.
10504   if (Subtarget.hasStdExtF()) {
10505     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10506                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10507                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10508                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10509                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10510                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10511                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10512                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10513                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10514                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10515                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10516                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10517                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10518                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10519                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10520                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10521                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10522                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10523                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10524                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10525                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10526                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10527                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10528                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10529                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10530                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10531                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10532                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10533                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10534                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10535                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10536                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10537                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10538                         .Default(RISCV::NoRegister);
10539     if (FReg != RISCV::NoRegister) {
10540       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10541       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10542         unsigned RegNo = FReg - RISCV::F0_F;
10543         unsigned DReg = RISCV::F0_D + RegNo;
10544         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10545       }
10546       if (VT == MVT::f32 || VT == MVT::Other)
10547         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10548       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10549         unsigned RegNo = FReg - RISCV::F0_F;
10550         unsigned HReg = RISCV::F0_H + RegNo;
10551         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10552       }
10553     }
10554   }
10555 
10556   if (Subtarget.hasVInstructions()) {
10557     Register VReg = StringSwitch<Register>(Constraint.lower())
10558                         .Case("{v0}", RISCV::V0)
10559                         .Case("{v1}", RISCV::V1)
10560                         .Case("{v2}", RISCV::V2)
10561                         .Case("{v3}", RISCV::V3)
10562                         .Case("{v4}", RISCV::V4)
10563                         .Case("{v5}", RISCV::V5)
10564                         .Case("{v6}", RISCV::V6)
10565                         .Case("{v7}", RISCV::V7)
10566                         .Case("{v8}", RISCV::V8)
10567                         .Case("{v9}", RISCV::V9)
10568                         .Case("{v10}", RISCV::V10)
10569                         .Case("{v11}", RISCV::V11)
10570                         .Case("{v12}", RISCV::V12)
10571                         .Case("{v13}", RISCV::V13)
10572                         .Case("{v14}", RISCV::V14)
10573                         .Case("{v15}", RISCV::V15)
10574                         .Case("{v16}", RISCV::V16)
10575                         .Case("{v17}", RISCV::V17)
10576                         .Case("{v18}", RISCV::V18)
10577                         .Case("{v19}", RISCV::V19)
10578                         .Case("{v20}", RISCV::V20)
10579                         .Case("{v21}", RISCV::V21)
10580                         .Case("{v22}", RISCV::V22)
10581                         .Case("{v23}", RISCV::V23)
10582                         .Case("{v24}", RISCV::V24)
10583                         .Case("{v25}", RISCV::V25)
10584                         .Case("{v26}", RISCV::V26)
10585                         .Case("{v27}", RISCV::V27)
10586                         .Case("{v28}", RISCV::V28)
10587                         .Case("{v29}", RISCV::V29)
10588                         .Case("{v30}", RISCV::V30)
10589                         .Case("{v31}", RISCV::V31)
10590                         .Default(RISCV::NoRegister);
10591     if (VReg != RISCV::NoRegister) {
10592       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10593         return std::make_pair(VReg, &RISCV::VMRegClass);
10594       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10595         return std::make_pair(VReg, &RISCV::VRRegClass);
10596       for (const auto *RC :
10597            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10598         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10599           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10600           return std::make_pair(VReg, RC);
10601         }
10602       }
10603     }
10604   }
10605 
10606   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10607 }
10608 
10609 unsigned
10610 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10611   // Currently only support length 1 constraints.
10612   if (ConstraintCode.size() == 1) {
10613     switch (ConstraintCode[0]) {
10614     case 'A':
10615       return InlineAsm::Constraint_A;
10616     default:
10617       break;
10618     }
10619   }
10620 
10621   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10622 }
10623 
10624 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10625     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10626     SelectionDAG &DAG) const {
10627   // Currently only support length 1 constraints.
10628   if (Constraint.length() == 1) {
10629     switch (Constraint[0]) {
10630     case 'I':
10631       // Validate & create a 12-bit signed immediate operand.
10632       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10633         uint64_t CVal = C->getSExtValue();
10634         if (isInt<12>(CVal))
10635           Ops.push_back(
10636               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10637       }
10638       return;
10639     case 'J':
10640       // Validate & create an integer zero operand.
10641       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10642         if (C->getZExtValue() == 0)
10643           Ops.push_back(
10644               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10645       return;
10646     case 'K':
10647       // Validate & create a 5-bit unsigned immediate operand.
10648       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10649         uint64_t CVal = C->getZExtValue();
10650         if (isUInt<5>(CVal))
10651           Ops.push_back(
10652               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10653       }
10654       return;
10655     case 'S':
10656       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10657         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10658                                                  GA->getValueType(0)));
10659       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10660         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10661                                                 BA->getValueType(0)));
10662       }
10663       return;
10664     default:
10665       break;
10666     }
10667   }
10668   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10669 }
10670 
10671 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10672                                                    Instruction *Inst,
10673                                                    AtomicOrdering Ord) const {
10674   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10675     return Builder.CreateFence(Ord);
10676   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10677     return Builder.CreateFence(AtomicOrdering::Release);
10678   return nullptr;
10679 }
10680 
10681 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10682                                                     Instruction *Inst,
10683                                                     AtomicOrdering Ord) const {
10684   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10685     return Builder.CreateFence(AtomicOrdering::Acquire);
10686   return nullptr;
10687 }
10688 
10689 TargetLowering::AtomicExpansionKind
10690 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10691   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10692   // point operations can't be used in an lr/sc sequence without breaking the
10693   // forward-progress guarantee.
10694   if (AI->isFloatingPointOperation())
10695     return AtomicExpansionKind::CmpXChg;
10696 
10697   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10698   if (Size == 8 || Size == 16)
10699     return AtomicExpansionKind::MaskedIntrinsic;
10700   return AtomicExpansionKind::None;
10701 }
10702 
10703 static Intrinsic::ID
10704 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10705   if (XLen == 32) {
10706     switch (BinOp) {
10707     default:
10708       llvm_unreachable("Unexpected AtomicRMW BinOp");
10709     case AtomicRMWInst::Xchg:
10710       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10711     case AtomicRMWInst::Add:
10712       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10713     case AtomicRMWInst::Sub:
10714       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10715     case AtomicRMWInst::Nand:
10716       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10717     case AtomicRMWInst::Max:
10718       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10719     case AtomicRMWInst::Min:
10720       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10721     case AtomicRMWInst::UMax:
10722       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10723     case AtomicRMWInst::UMin:
10724       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10725     }
10726   }
10727 
10728   if (XLen == 64) {
10729     switch (BinOp) {
10730     default:
10731       llvm_unreachable("Unexpected AtomicRMW BinOp");
10732     case AtomicRMWInst::Xchg:
10733       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10734     case AtomicRMWInst::Add:
10735       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10736     case AtomicRMWInst::Sub:
10737       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10738     case AtomicRMWInst::Nand:
10739       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10740     case AtomicRMWInst::Max:
10741       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10742     case AtomicRMWInst::Min:
10743       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10744     case AtomicRMWInst::UMax:
10745       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10746     case AtomicRMWInst::UMin:
10747       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10748     }
10749   }
10750 
10751   llvm_unreachable("Unexpected XLen\n");
10752 }
10753 
10754 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10755     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10756     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10757   unsigned XLen = Subtarget.getXLen();
10758   Value *Ordering =
10759       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10760   Type *Tys[] = {AlignedAddr->getType()};
10761   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10762       AI->getModule(),
10763       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10764 
10765   if (XLen == 64) {
10766     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10767     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10768     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10769   }
10770 
10771   Value *Result;
10772 
10773   // Must pass the shift amount needed to sign extend the loaded value prior
10774   // to performing a signed comparison for min/max. ShiftAmt is the number of
10775   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10776   // is the number of bits to left+right shift the value in order to
10777   // sign-extend.
10778   if (AI->getOperation() == AtomicRMWInst::Min ||
10779       AI->getOperation() == AtomicRMWInst::Max) {
10780     const DataLayout &DL = AI->getModule()->getDataLayout();
10781     unsigned ValWidth =
10782         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10783     Value *SextShamt =
10784         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10785     Result = Builder.CreateCall(LrwOpScwLoop,
10786                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10787   } else {
10788     Result =
10789         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10790   }
10791 
10792   if (XLen == 64)
10793     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10794   return Result;
10795 }
10796 
10797 TargetLowering::AtomicExpansionKind
10798 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10799     AtomicCmpXchgInst *CI) const {
10800   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10801   if (Size == 8 || Size == 16)
10802     return AtomicExpansionKind::MaskedIntrinsic;
10803   return AtomicExpansionKind::None;
10804 }
10805 
10806 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10807     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10808     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10809   unsigned XLen = Subtarget.getXLen();
10810   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10811   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10812   if (XLen == 64) {
10813     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10814     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10815     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10816     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10817   }
10818   Type *Tys[] = {AlignedAddr->getType()};
10819   Function *MaskedCmpXchg =
10820       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10821   Value *Result = Builder.CreateCall(
10822       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10823   if (XLen == 64)
10824     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10825   return Result;
10826 }
10827 
10828 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10829   return false;
10830 }
10831 
10832 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10833                                                EVT VT) const {
10834   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10835     return false;
10836 
10837   switch (FPVT.getSimpleVT().SimpleTy) {
10838   case MVT::f16:
10839     return Subtarget.hasStdExtZfh();
10840   case MVT::f32:
10841     return Subtarget.hasStdExtF();
10842   case MVT::f64:
10843     return Subtarget.hasStdExtD();
10844   default:
10845     return false;
10846   }
10847 }
10848 
10849 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10850   // If we are using the small code model, we can reduce size of jump table
10851   // entry to 4 bytes.
10852   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10853       getTargetMachine().getCodeModel() == CodeModel::Small) {
10854     return MachineJumpTableInfo::EK_Custom32;
10855   }
10856   return TargetLowering::getJumpTableEncoding();
10857 }
10858 
10859 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10860     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10861     unsigned uid, MCContext &Ctx) const {
10862   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10863          getTargetMachine().getCodeModel() == CodeModel::Small);
10864   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10865 }
10866 
10867 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10868                                                      EVT VT) const {
10869   VT = VT.getScalarType();
10870 
10871   if (!VT.isSimple())
10872     return false;
10873 
10874   switch (VT.getSimpleVT().SimpleTy) {
10875   case MVT::f16:
10876     return Subtarget.hasStdExtZfh();
10877   case MVT::f32:
10878     return Subtarget.hasStdExtF();
10879   case MVT::f64:
10880     return Subtarget.hasStdExtD();
10881   default:
10882     break;
10883   }
10884 
10885   return false;
10886 }
10887 
10888 Register RISCVTargetLowering::getExceptionPointerRegister(
10889     const Constant *PersonalityFn) const {
10890   return RISCV::X10;
10891 }
10892 
10893 Register RISCVTargetLowering::getExceptionSelectorRegister(
10894     const Constant *PersonalityFn) const {
10895   return RISCV::X11;
10896 }
10897 
10898 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10899   // Return false to suppress the unnecessary extensions if the LibCall
10900   // arguments or return value is f32 type for LP64 ABI.
10901   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10902   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10903     return false;
10904 
10905   return true;
10906 }
10907 
10908 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10909   if (Subtarget.is64Bit() && Type == MVT::i32)
10910     return true;
10911 
10912   return IsSigned;
10913 }
10914 
10915 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10916                                                  SDValue C) const {
10917   // Check integral scalar types.
10918   if (VT.isScalarInteger()) {
10919     // Omit the optimization if the sub target has the M extension and the data
10920     // size exceeds XLen.
10921     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10922       return false;
10923     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10924       // Break the MUL to a SLLI and an ADD/SUB.
10925       const APInt &Imm = ConstNode->getAPIntValue();
10926       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10927           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10928         return true;
10929       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10930       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10931           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10932            (Imm - 8).isPowerOf2()))
10933         return true;
10934       // Omit the following optimization if the sub target has the M extension
10935       // and the data size >= XLen.
10936       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10937         return false;
10938       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10939       // a pair of LUI/ADDI.
10940       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10941         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10942         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10943             (1 - ImmS).isPowerOf2())
10944         return true;
10945       }
10946     }
10947   }
10948 
10949   return false;
10950 }
10951 
10952 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10953     const SDValue &AddNode, const SDValue &ConstNode) const {
10954   // Let the DAGCombiner decide for vectors.
10955   EVT VT = AddNode.getValueType();
10956   if (VT.isVector())
10957     return true;
10958 
10959   // Let the DAGCombiner decide for larger types.
10960   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10961     return true;
10962 
10963   // It is worse if c1 is simm12 while c1*c2 is not.
10964   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10965   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10966   const APInt &C1 = C1Node->getAPIntValue();
10967   const APInt &C2 = C2Node->getAPIntValue();
10968   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10969     return false;
10970 
10971   // Default to true and let the DAGCombiner decide.
10972   return true;
10973 }
10974 
10975 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10976     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10977     bool *Fast) const {
10978   if (!VT.isVector())
10979     return false;
10980 
10981   EVT ElemVT = VT.getVectorElementType();
10982   if (Alignment >= ElemVT.getStoreSize()) {
10983     if (Fast)
10984       *Fast = true;
10985     return true;
10986   }
10987 
10988   return false;
10989 }
10990 
10991 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10992     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10993     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10994   bool IsABIRegCopy = CC.hasValue();
10995   EVT ValueVT = Val.getValueType();
10996   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10997     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10998     // and cast to f32.
10999     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11000     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11001     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11002                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11003     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11004     Parts[0] = Val;
11005     return true;
11006   }
11007 
11008   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11009     LLVMContext &Context = *DAG.getContext();
11010     EVT ValueEltVT = ValueVT.getVectorElementType();
11011     EVT PartEltVT = PartVT.getVectorElementType();
11012     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11013     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11014     if (PartVTBitSize % ValueVTBitSize == 0) {
11015       assert(PartVTBitSize >= ValueVTBitSize);
11016       // If the element types are different, bitcast to the same element type of
11017       // PartVT first.
11018       // Give an example here, we want copy a <vscale x 1 x i8> value to
11019       // <vscale x 4 x i16>.
11020       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11021       // subvector, then we can bitcast to <vscale x 4 x i16>.
11022       if (ValueEltVT != PartEltVT) {
11023         if (PartVTBitSize > ValueVTBitSize) {
11024           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11025           assert(Count != 0 && "The number of element should not be zero.");
11026           EVT SameEltTypeVT =
11027               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11028           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11029                             DAG.getUNDEF(SameEltTypeVT), Val,
11030                             DAG.getVectorIdxConstant(0, DL));
11031         }
11032         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11033       } else {
11034         Val =
11035             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11036                         Val, DAG.getVectorIdxConstant(0, DL));
11037       }
11038       Parts[0] = Val;
11039       return true;
11040     }
11041   }
11042   return false;
11043 }
11044 
11045 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11046     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11047     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11048   bool IsABIRegCopy = CC.hasValue();
11049   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11050     SDValue Val = Parts[0];
11051 
11052     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11053     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11054     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11055     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11056     return Val;
11057   }
11058 
11059   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11060     LLVMContext &Context = *DAG.getContext();
11061     SDValue Val = Parts[0];
11062     EVT ValueEltVT = ValueVT.getVectorElementType();
11063     EVT PartEltVT = PartVT.getVectorElementType();
11064     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11065     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11066     if (PartVTBitSize % ValueVTBitSize == 0) {
11067       assert(PartVTBitSize >= ValueVTBitSize);
11068       EVT SameEltTypeVT = ValueVT;
11069       // If the element types are different, convert it to the same element type
11070       // of PartVT.
11071       // Give an example here, we want copy a <vscale x 1 x i8> value from
11072       // <vscale x 4 x i16>.
11073       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11074       // then we can extract <vscale x 1 x i8>.
11075       if (ValueEltVT != PartEltVT) {
11076         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11077         assert(Count != 0 && "The number of element should not be zero.");
11078         SameEltTypeVT =
11079             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11080         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11081       }
11082       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11083                         DAG.getVectorIdxConstant(0, DL));
11084       return Val;
11085     }
11086   }
11087   return SDValue();
11088 }
11089 
11090 SDValue
11091 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11092                                    SelectionDAG &DAG,
11093                                    SmallVectorImpl<SDNode *> &Created) const {
11094   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11095   if (isIntDivCheap(N->getValueType(0), Attr))
11096     return SDValue(N, 0); // Lower SDIV as SDIV
11097 
11098   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11099          "Unexpected divisor!");
11100 
11101   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11102   if (!Subtarget.hasStdExtZbt())
11103     return SDValue();
11104 
11105   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11106   // Besides, more critical path instructions will be generated when dividing
11107   // by 2. So we keep using the original DAGs for these cases.
11108   unsigned Lg2 = Divisor.countTrailingZeros();
11109   if (Lg2 == 1 || Lg2 >= 12)
11110     return SDValue();
11111 
11112   // fold (sdiv X, pow2)
11113   EVT VT = N->getValueType(0);
11114   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11115     return SDValue();
11116 
11117   SDLoc DL(N);
11118   SDValue N0 = N->getOperand(0);
11119   SDValue Zero = DAG.getConstant(0, DL, VT);
11120   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11121 
11122   // Add (N0 < 0) ? Pow2 - 1 : 0;
11123   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11124   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11125   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11126 
11127   Created.push_back(Cmp.getNode());
11128   Created.push_back(Add.getNode());
11129   Created.push_back(Sel.getNode());
11130 
11131   // Divide by pow2.
11132   SDValue SRA =
11133       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11134 
11135   // If we're dividing by a positive value, we're done.  Otherwise, we must
11136   // negate the result.
11137   if (Divisor.isNonNegative())
11138     return SRA;
11139 
11140   Created.push_back(SRA.getNode());
11141   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11142 }
11143 
11144 #define GET_REGISTER_MATCHER
11145 #include "RISCVGenAsmMatcher.inc"
11146 
11147 Register
11148 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11149                                        const MachineFunction &MF) const {
11150   Register Reg = MatchRegisterAltName(RegName);
11151   if (Reg == RISCV::NoRegister)
11152     Reg = MatchRegisterName(RegName);
11153   if (Reg == RISCV::NoRegister)
11154     report_fatal_error(
11155         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11156   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11157   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11158     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11159                              StringRef(RegName) + "\"."));
11160   return Reg;
11161 }
11162 
11163 namespace llvm {
11164 namespace RISCVVIntrinsicsTable {
11165 
11166 #define GET_RISCVVIntrinsicsTable_IMPL
11167 #include "RISCVGenSearchableTables.inc"
11168 
11169 } // namespace RISCVVIntrinsicsTable
11170 
11171 } // namespace llvm
11172