xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.cpp (revision d56accc7c3dcc897489b6a07834763a03b9f3d68)
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 VLMax 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->getSExtValue() == RISCV::VLMaxSentinel) {
2291       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2292       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2293       // access the subtarget here now.
2294       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL);
2295       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2296     }
2297   }
2298 
2299   // Fall back to a stack store and stride x0 vector load.
2300   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2301 }
2302 
2303 // Called by type legalization to handle splat of i64 on RV32.
2304 // FIXME: We can optimize this when the type has sign or zero bits in one
2305 // of the halves.
2306 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2307                                    SDValue VL, SelectionDAG &DAG) {
2308   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2309   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2310                            DAG.getConstant(0, DL, MVT::i32));
2311   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2312                            DAG.getConstant(1, DL, MVT::i32));
2313   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2314 }
2315 
2316 // This function lowers a splat of a scalar operand Splat with the vector
2317 // length VL. It ensures the final sequence is type legal, which is useful when
2318 // lowering a splat after type legalization.
2319 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2320                                 SelectionDAG &DAG,
2321                                 const RISCVSubtarget &Subtarget) {
2322   if (VT.isFloatingPoint()) {
2323     // If VL is 1, we could use vfmv.s.f.
2324     if (isOneConstant(VL))
2325       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2326                          Scalar, VL);
2327     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2328   }
2329 
2330   MVT XLenVT = Subtarget.getXLenVT();
2331 
2332   // Simplest case is that the operand needs to be promoted to XLenVT.
2333   if (Scalar.getValueType().bitsLE(XLenVT)) {
2334     // If the operand is a constant, sign extend to increase our chances
2335     // of being able to use a .vi instruction. ANY_EXTEND would become a
2336     // a zero extend and the simm5 check in isel would fail.
2337     // FIXME: Should we ignore the upper bits in isel instead?
2338     unsigned ExtOpc =
2339         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2340     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2341     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2342     // If VL is 1 and the scalar value won't benefit from immediate, we could
2343     // use vmv.s.x.
2344     if (isOneConstant(VL) &&
2345         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2346       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2347                          VL);
2348     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2349   }
2350 
2351   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2352          "Unexpected scalar for splat lowering!");
2353 
2354   if (isOneConstant(VL) && isNullConstant(Scalar))
2355     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2356                        DAG.getConstant(0, DL, XLenVT), VL);
2357 
2358   // Otherwise use the more complicated splatting algorithm.
2359   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2360 }
2361 
2362 // Is the mask a slidedown that shifts in undefs.
2363 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2364   int Size = Mask.size();
2365 
2366   // Elements shifted in should be undef.
2367   auto CheckUndefs = [&](int Shift) {
2368     for (int i = Size - Shift; i != Size; ++i)
2369       if (Mask[i] >= 0)
2370         return false;
2371     return true;
2372   };
2373 
2374   // Elements should be shifted or undef.
2375   auto MatchShift = [&](int Shift) {
2376     for (int i = 0; i != Size - Shift; ++i)
2377        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2378          return false;
2379     return true;
2380   };
2381 
2382   // Try all possible shifts.
2383   for (int Shift = 1; Shift != Size; ++Shift)
2384     if (CheckUndefs(Shift) && MatchShift(Shift))
2385       return Shift;
2386 
2387   // No match.
2388   return -1;
2389 }
2390 
2391 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2392                                 const RISCVSubtarget &Subtarget) {
2393   // We need to be able to widen elements to the next larger integer type.
2394   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2395     return false;
2396 
2397   int Size = Mask.size();
2398   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2399 
2400   int Srcs[] = {-1, -1};
2401   for (int i = 0; i != Size; ++i) {
2402     // Ignore undef elements.
2403     if (Mask[i] < 0)
2404       continue;
2405 
2406     // Is this an even or odd element.
2407     int Pol = i % 2;
2408 
2409     // Ensure we consistently use the same source for this element polarity.
2410     int Src = Mask[i] / Size;
2411     if (Srcs[Pol] < 0)
2412       Srcs[Pol] = Src;
2413     if (Srcs[Pol] != Src)
2414       return false;
2415 
2416     // Make sure the element within the source is appropriate for this element
2417     // in the destination.
2418     int Elt = Mask[i] % Size;
2419     if (Elt != i / 2)
2420       return false;
2421   }
2422 
2423   // We need to find a source for each polarity and they can't be the same.
2424   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2425     return false;
2426 
2427   // Swap the sources if the second source was in the even polarity.
2428   SwapSources = Srcs[0] > Srcs[1];
2429 
2430   return true;
2431 }
2432 
2433 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2434                                    const RISCVSubtarget &Subtarget) {
2435   SDValue V1 = Op.getOperand(0);
2436   SDValue V2 = Op.getOperand(1);
2437   SDLoc DL(Op);
2438   MVT XLenVT = Subtarget.getXLenVT();
2439   MVT VT = Op.getSimpleValueType();
2440   unsigned NumElts = VT.getVectorNumElements();
2441   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2442 
2443   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2444 
2445   SDValue TrueMask, VL;
2446   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2447 
2448   if (SVN->isSplat()) {
2449     const int Lane = SVN->getSplatIndex();
2450     if (Lane >= 0) {
2451       MVT SVT = VT.getVectorElementType();
2452 
2453       // Turn splatted vector load into a strided load with an X0 stride.
2454       SDValue V = V1;
2455       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2456       // with undef.
2457       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2458       int Offset = Lane;
2459       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2460         int OpElements =
2461             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2462         V = V.getOperand(Offset / OpElements);
2463         Offset %= OpElements;
2464       }
2465 
2466       // We need to ensure the load isn't atomic or volatile.
2467       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2468         auto *Ld = cast<LoadSDNode>(V);
2469         Offset *= SVT.getStoreSize();
2470         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2471                                                    TypeSize::Fixed(Offset), DL);
2472 
2473         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2474         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2475           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2476           SDValue IntID =
2477               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2478           SDValue Ops[] = {Ld->getChain(),
2479                            IntID,
2480                            DAG.getUNDEF(ContainerVT),
2481                            NewAddr,
2482                            DAG.getRegister(RISCV::X0, XLenVT),
2483                            VL};
2484           SDValue NewLoad = DAG.getMemIntrinsicNode(
2485               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2486               DAG.getMachineFunction().getMachineMemOperand(
2487                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2488           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2489           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2490         }
2491 
2492         // Otherwise use a scalar load and splat. This will give the best
2493         // opportunity to fold a splat into the operation. ISel can turn it into
2494         // the x0 strided load if we aren't able to fold away the select.
2495         if (SVT.isFloatingPoint())
2496           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2497                           Ld->getPointerInfo().getWithOffset(Offset),
2498                           Ld->getOriginalAlign(),
2499                           Ld->getMemOperand()->getFlags());
2500         else
2501           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2502                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2503                              Ld->getOriginalAlign(),
2504                              Ld->getMemOperand()->getFlags());
2505         DAG.makeEquivalentMemoryOrdering(Ld, V);
2506 
2507         unsigned Opc =
2508             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2509         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2510         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2511       }
2512 
2513       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2514       assert(Lane < (int)NumElts && "Unexpected lane!");
2515       SDValue Gather =
2516           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2517                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2518       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2519     }
2520   }
2521 
2522   ArrayRef<int> Mask = SVN->getMask();
2523 
2524   // Try to match as a slidedown.
2525   int SlideAmt = matchShuffleAsSlideDown(Mask);
2526   if (SlideAmt >= 0) {
2527     // TODO: Should we reduce the VL to account for the upper undef elements?
2528     // Requires additional vsetvlis, but might be faster to execute.
2529     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2530     SDValue SlideDown =
2531         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2532                     DAG.getUNDEF(ContainerVT), V1,
2533                     DAG.getConstant(SlideAmt, DL, XLenVT),
2534                     TrueMask, VL);
2535     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2536   }
2537 
2538   // Detect an interleave shuffle and lower to
2539   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2540   bool SwapSources;
2541   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2542     // Swap sources if needed.
2543     if (SwapSources)
2544       std::swap(V1, V2);
2545 
2546     // Extract the lower half of the vectors.
2547     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2548     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2549                      DAG.getConstant(0, DL, XLenVT));
2550     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2551                      DAG.getConstant(0, DL, XLenVT));
2552 
2553     // Double the element width and halve the number of elements in an int type.
2554     unsigned EltBits = VT.getScalarSizeInBits();
2555     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2556     MVT WideIntVT =
2557         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2558     // Convert this to a scalable vector. We need to base this on the
2559     // destination size to ensure there's always a type with a smaller LMUL.
2560     MVT WideIntContainerVT =
2561         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2562 
2563     // Convert sources to scalable vectors with the same element count as the
2564     // larger type.
2565     MVT HalfContainerVT = MVT::getVectorVT(
2566         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2567     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2568     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2569 
2570     // Cast sources to integer.
2571     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2572     MVT IntHalfVT =
2573         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2574     V1 = DAG.getBitcast(IntHalfVT, V1);
2575     V2 = DAG.getBitcast(IntHalfVT, V2);
2576 
2577     // Freeze V2 since we use it twice and we need to be sure that the add and
2578     // multiply see the same value.
2579     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2580 
2581     // Recreate TrueMask using the widened type's element count.
2582     MVT MaskVT =
2583         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2584     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2585 
2586     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2587     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2588                               V2, TrueMask, VL);
2589     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2590     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2591                                      DAG.getAllOnesConstant(DL, XLenVT));
2592     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2593                                    V2, Multiplier, TrueMask, VL);
2594     // Add the new copies to our previous addition giving us 2^eltbits copies of
2595     // V2. This is equivalent to shifting V2 left by eltbits. This should
2596     // combine with the vwmulu.vv above to form vwmaccu.vv.
2597     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2598                       TrueMask, VL);
2599     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2600     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2601     // vector VT.
2602     ContainerVT =
2603         MVT::getVectorVT(VT.getVectorElementType(),
2604                          WideIntContainerVT.getVectorElementCount() * 2);
2605     Add = DAG.getBitcast(ContainerVT, Add);
2606     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2607   }
2608 
2609   // Detect shuffles which can be re-expressed as vector selects; these are
2610   // shuffles in which each element in the destination is taken from an element
2611   // at the corresponding index in either source vectors.
2612   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2613     int MaskIndex = MaskIdx.value();
2614     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2615   });
2616 
2617   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2618 
2619   SmallVector<SDValue> MaskVals;
2620   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2621   // merged with a second vrgather.
2622   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2623 
2624   // By default we preserve the original operand order, and use a mask to
2625   // select LHS as true and RHS as false. However, since RVV vector selects may
2626   // feature splats but only on the LHS, we may choose to invert our mask and
2627   // instead select between RHS and LHS.
2628   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2629   bool InvertMask = IsSelect == SwapOps;
2630 
2631   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2632   // half.
2633   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2634 
2635   // Now construct the mask that will be used by the vselect or blended
2636   // vrgather operation. For vrgathers, construct the appropriate indices into
2637   // each vector.
2638   for (int MaskIndex : Mask) {
2639     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2640     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2641     if (!IsSelect) {
2642       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2643       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2644                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2645                                      : DAG.getUNDEF(XLenVT));
2646       GatherIndicesRHS.push_back(
2647           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2648                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2649       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2650         ++LHSIndexCounts[MaskIndex];
2651       if (!IsLHSOrUndefIndex)
2652         ++RHSIndexCounts[MaskIndex - NumElts];
2653     }
2654   }
2655 
2656   if (SwapOps) {
2657     std::swap(V1, V2);
2658     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2659   }
2660 
2661   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2662   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2663   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2664 
2665   if (IsSelect)
2666     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2667 
2668   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2669     // On such a large vector we're unable to use i8 as the index type.
2670     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2671     // may involve vector splitting if we're already at LMUL=8, or our
2672     // user-supplied maximum fixed-length LMUL.
2673     return SDValue();
2674   }
2675 
2676   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2677   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2678   MVT IndexVT = VT.changeTypeToInteger();
2679   // Since we can't introduce illegal index types at this stage, use i16 and
2680   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2681   // than XLenVT.
2682   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2683     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2684     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2685   }
2686 
2687   MVT IndexContainerVT =
2688       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2689 
2690   SDValue Gather;
2691   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2692   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2693   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2694     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2695   } else {
2696     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2697     // If only one index is used, we can use a "splat" vrgather.
2698     // TODO: We can splat the most-common index and fix-up any stragglers, if
2699     // that's beneficial.
2700     if (LHSIndexCounts.size() == 1) {
2701       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2702       Gather =
2703           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2704                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2705     } else {
2706       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2707       LHSIndices =
2708           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2709 
2710       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2711                            TrueMask, VL);
2712     }
2713   }
2714 
2715   // If a second vector operand is used by this shuffle, blend it in with an
2716   // additional vrgather.
2717   if (!V2.isUndef()) {
2718     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2719     // If only one index is used, we can use a "splat" vrgather.
2720     // TODO: We can splat the most-common index and fix-up any stragglers, if
2721     // that's beneficial.
2722     if (RHSIndexCounts.size() == 1) {
2723       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2724       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2725                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2726     } else {
2727       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2728       RHSIndices =
2729           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2730       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2731                        VL);
2732     }
2733 
2734     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2735     SelectMask =
2736         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2737 
2738     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2739                          Gather, VL);
2740   }
2741 
2742   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2743 }
2744 
2745 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2746                                      SDLoc DL, SelectionDAG &DAG,
2747                                      const RISCVSubtarget &Subtarget) {
2748   if (VT.isScalableVector())
2749     return DAG.getFPExtendOrRound(Op, DL, VT);
2750   assert(VT.isFixedLengthVector() &&
2751          "Unexpected value type for RVV FP extend/round lowering");
2752   SDValue Mask, VL;
2753   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2754   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2755                         ? RISCVISD::FP_EXTEND_VL
2756                         : RISCVISD::FP_ROUND_VL;
2757   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2758 }
2759 
2760 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2761 // the exponent.
2762 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2763   MVT VT = Op.getSimpleValueType();
2764   unsigned EltSize = VT.getScalarSizeInBits();
2765   SDValue Src = Op.getOperand(0);
2766   SDLoc DL(Op);
2767 
2768   // We need a FP type that can represent the value.
2769   // TODO: Use f16 for i8 when possible?
2770   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2771   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2772 
2773   // Legal types should have been checked in the RISCVTargetLowering
2774   // constructor.
2775   // TODO: Splitting may make sense in some cases.
2776   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2777          "Expected legal float type!");
2778 
2779   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2780   // The trailing zero count is equal to log2 of this single bit value.
2781   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2782     SDValue Neg =
2783         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2784     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2785   }
2786 
2787   // We have a legal FP type, convert to it.
2788   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2789   // Bitcast to integer and shift the exponent to the LSB.
2790   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2791   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2792   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2793   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2794                               DAG.getConstant(ShiftAmt, DL, IntVT));
2795   // Truncate back to original type to allow vnsrl.
2796   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2797   // The exponent contains log2 of the value in biased form.
2798   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2799 
2800   // For trailing zeros, we just need to subtract the bias.
2801   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2802     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2803                        DAG.getConstant(ExponentBias, DL, VT));
2804 
2805   // For leading zeros, we need to remove the bias and convert from log2 to
2806   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2807   unsigned Adjust = ExponentBias + (EltSize - 1);
2808   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2809 }
2810 
2811 // While RVV has alignment restrictions, we should always be able to load as a
2812 // legal equivalently-sized byte-typed vector instead. This method is
2813 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2814 // the load is already correctly-aligned, it returns SDValue().
2815 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2816                                                     SelectionDAG &DAG) const {
2817   auto *Load = cast<LoadSDNode>(Op);
2818   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2819 
2820   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2821                                      Load->getMemoryVT(),
2822                                      *Load->getMemOperand()))
2823     return SDValue();
2824 
2825   SDLoc DL(Op);
2826   MVT VT = Op.getSimpleValueType();
2827   unsigned EltSizeBits = VT.getScalarSizeInBits();
2828   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2829          "Unexpected unaligned RVV load type");
2830   MVT NewVT =
2831       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2832   assert(NewVT.isValid() &&
2833          "Expecting equally-sized RVV vector types to be legal");
2834   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2835                           Load->getPointerInfo(), Load->getOriginalAlign(),
2836                           Load->getMemOperand()->getFlags());
2837   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2838 }
2839 
2840 // While RVV has alignment restrictions, we should always be able to store as a
2841 // legal equivalently-sized byte-typed vector instead. This method is
2842 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2843 // returns SDValue() if the store is already correctly aligned.
2844 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2845                                                      SelectionDAG &DAG) const {
2846   auto *Store = cast<StoreSDNode>(Op);
2847   assert(Store && Store->getValue().getValueType().isVector() &&
2848          "Expected vector store");
2849 
2850   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2851                                      Store->getMemoryVT(),
2852                                      *Store->getMemOperand()))
2853     return SDValue();
2854 
2855   SDLoc DL(Op);
2856   SDValue StoredVal = Store->getValue();
2857   MVT VT = StoredVal.getSimpleValueType();
2858   unsigned EltSizeBits = VT.getScalarSizeInBits();
2859   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2860          "Unexpected unaligned RVV store type");
2861   MVT NewVT =
2862       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2863   assert(NewVT.isValid() &&
2864          "Expecting equally-sized RVV vector types to be legal");
2865   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2866   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2867                       Store->getPointerInfo(), Store->getOriginalAlign(),
2868                       Store->getMemOperand()->getFlags());
2869 }
2870 
2871 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2872                                             SelectionDAG &DAG) const {
2873   switch (Op.getOpcode()) {
2874   default:
2875     report_fatal_error("unimplemented operand");
2876   case ISD::GlobalAddress:
2877     return lowerGlobalAddress(Op, DAG);
2878   case ISD::BlockAddress:
2879     return lowerBlockAddress(Op, DAG);
2880   case ISD::ConstantPool:
2881     return lowerConstantPool(Op, DAG);
2882   case ISD::JumpTable:
2883     return lowerJumpTable(Op, DAG);
2884   case ISD::GlobalTLSAddress:
2885     return lowerGlobalTLSAddress(Op, DAG);
2886   case ISD::SELECT:
2887     return lowerSELECT(Op, DAG);
2888   case ISD::BRCOND:
2889     return lowerBRCOND(Op, DAG);
2890   case ISD::VASTART:
2891     return lowerVASTART(Op, DAG);
2892   case ISD::FRAMEADDR:
2893     return lowerFRAMEADDR(Op, DAG);
2894   case ISD::RETURNADDR:
2895     return lowerRETURNADDR(Op, DAG);
2896   case ISD::SHL_PARTS:
2897     return lowerShiftLeftParts(Op, DAG);
2898   case ISD::SRA_PARTS:
2899     return lowerShiftRightParts(Op, DAG, true);
2900   case ISD::SRL_PARTS:
2901     return lowerShiftRightParts(Op, DAG, false);
2902   case ISD::BITCAST: {
2903     SDLoc DL(Op);
2904     EVT VT = Op.getValueType();
2905     SDValue Op0 = Op.getOperand(0);
2906     EVT Op0VT = Op0.getValueType();
2907     MVT XLenVT = Subtarget.getXLenVT();
2908     if (VT.isFixedLengthVector()) {
2909       // We can handle fixed length vector bitcasts with a simple replacement
2910       // in isel.
2911       if (Op0VT.isFixedLengthVector())
2912         return Op;
2913       // When bitcasting from scalar to fixed-length vector, insert the scalar
2914       // into a one-element vector of the result type, and perform a vector
2915       // bitcast.
2916       if (!Op0VT.isVector()) {
2917         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2918         if (!isTypeLegal(BVT))
2919           return SDValue();
2920         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2921                                               DAG.getUNDEF(BVT), Op0,
2922                                               DAG.getConstant(0, DL, XLenVT)));
2923       }
2924       return SDValue();
2925     }
2926     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2927     // thus: bitcast the vector to a one-element vector type whose element type
2928     // is the same as the result type, and extract the first element.
2929     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2930       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2931       if (!isTypeLegal(BVT))
2932         return SDValue();
2933       SDValue BVec = DAG.getBitcast(BVT, Op0);
2934       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2935                          DAG.getConstant(0, DL, XLenVT));
2936     }
2937     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2938       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2939       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2940       return FPConv;
2941     }
2942     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2943         Subtarget.hasStdExtF()) {
2944       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2945       SDValue FPConv =
2946           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2947       return FPConv;
2948     }
2949     return SDValue();
2950   }
2951   case ISD::INTRINSIC_WO_CHAIN:
2952     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2953   case ISD::INTRINSIC_W_CHAIN:
2954     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2955   case ISD::INTRINSIC_VOID:
2956     return LowerINTRINSIC_VOID(Op, DAG);
2957   case ISD::BSWAP:
2958   case ISD::BITREVERSE: {
2959     MVT VT = Op.getSimpleValueType();
2960     SDLoc DL(Op);
2961     if (Subtarget.hasStdExtZbp()) {
2962       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2963       // Start with the maximum immediate value which is the bitwidth - 1.
2964       unsigned Imm = VT.getSizeInBits() - 1;
2965       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2966       if (Op.getOpcode() == ISD::BSWAP)
2967         Imm &= ~0x7U;
2968       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2969                          DAG.getConstant(Imm, DL, VT));
2970     }
2971     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
2972     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
2973     // Expand bitreverse to a bswap(rev8) followed by brev8.
2974     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
2975     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
2976     // as brev8 by an isel pattern.
2977     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
2978                        DAG.getConstant(7, DL, VT));
2979   }
2980   case ISD::FSHL:
2981   case ISD::FSHR: {
2982     MVT VT = Op.getSimpleValueType();
2983     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2984     SDLoc DL(Op);
2985     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2986     // use log(XLen) bits. Mask the shift amount accordingly to prevent
2987     // accidentally setting the extra bit.
2988     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2989     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2990                                 DAG.getConstant(ShAmtWidth, DL, VT));
2991     // fshl and fshr concatenate their operands in the same order. fsr and fsl
2992     // instruction use different orders. fshl will return its first operand for
2993     // shift of zero, fshr will return its second operand. fsl and fsr both
2994     // return rs1 so the ISD nodes need to have different operand orders.
2995     // Shift amount is in rs2.
2996     SDValue Op0 = Op.getOperand(0);
2997     SDValue Op1 = Op.getOperand(1);
2998     unsigned Opc = RISCVISD::FSL;
2999     if (Op.getOpcode() == ISD::FSHR) {
3000       std::swap(Op0, Op1);
3001       Opc = RISCVISD::FSR;
3002     }
3003     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3004   }
3005   case ISD::TRUNCATE: {
3006     SDLoc DL(Op);
3007     MVT VT = Op.getSimpleValueType();
3008     // Only custom-lower vector truncates
3009     if (!VT.isVector())
3010       return Op;
3011 
3012     // Truncates to mask types are handled differently
3013     if (VT.getVectorElementType() == MVT::i1)
3014       return lowerVectorMaskTrunc(Op, DAG);
3015 
3016     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3017     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3018     // truncate by one power of two at a time.
3019     MVT DstEltVT = VT.getVectorElementType();
3020 
3021     SDValue Src = Op.getOperand(0);
3022     MVT SrcVT = Src.getSimpleValueType();
3023     MVT SrcEltVT = SrcVT.getVectorElementType();
3024 
3025     assert(DstEltVT.bitsLT(SrcEltVT) &&
3026            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3027            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3028            "Unexpected vector truncate lowering");
3029 
3030     MVT ContainerVT = SrcVT;
3031     if (SrcVT.isFixedLengthVector()) {
3032       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3033       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3034     }
3035 
3036     SDValue Result = Src;
3037     SDValue Mask, VL;
3038     std::tie(Mask, VL) =
3039         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3040     LLVMContext &Context = *DAG.getContext();
3041     const ElementCount Count = ContainerVT.getVectorElementCount();
3042     do {
3043       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3044       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3045       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3046                            Mask, VL);
3047     } while (SrcEltVT != DstEltVT);
3048 
3049     if (SrcVT.isFixedLengthVector())
3050       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3051 
3052     return Result;
3053   }
3054   case ISD::ANY_EXTEND:
3055   case ISD::ZERO_EXTEND:
3056     if (Op.getOperand(0).getValueType().isVector() &&
3057         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3058       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3059     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3060   case ISD::SIGN_EXTEND:
3061     if (Op.getOperand(0).getValueType().isVector() &&
3062         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3063       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3064     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3065   case ISD::SPLAT_VECTOR_PARTS:
3066     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3067   case ISD::INSERT_VECTOR_ELT:
3068     return lowerINSERT_VECTOR_ELT(Op, DAG);
3069   case ISD::EXTRACT_VECTOR_ELT:
3070     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3071   case ISD::VSCALE: {
3072     MVT VT = Op.getSimpleValueType();
3073     SDLoc DL(Op);
3074     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3075     // We define our scalable vector types for lmul=1 to use a 64 bit known
3076     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3077     // vscale as VLENB / 8.
3078     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3079     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3080       report_fatal_error("Support for VLEN==32 is incomplete.");
3081     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3082       // We assume VLENB is a multiple of 8. We manually choose the best shift
3083       // here because SimplifyDemandedBits isn't always able to simplify it.
3084       uint64_t Val = Op.getConstantOperandVal(0);
3085       if (isPowerOf2_64(Val)) {
3086         uint64_t Log2 = Log2_64(Val);
3087         if (Log2 < 3)
3088           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3089                              DAG.getConstant(3 - Log2, DL, VT));
3090         if (Log2 > 3)
3091           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3092                              DAG.getConstant(Log2 - 3, DL, VT));
3093         return VLENB;
3094       }
3095       // If the multiplier is a multiple of 8, scale it down to avoid needing
3096       // to shift the VLENB value.
3097       if ((Val % 8) == 0)
3098         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3099                            DAG.getConstant(Val / 8, DL, VT));
3100     }
3101 
3102     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3103                                  DAG.getConstant(3, DL, VT));
3104     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3105   }
3106   case ISD::FPOWI: {
3107     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3108     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3109     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3110         Op.getOperand(1).getValueType() == MVT::i32) {
3111       SDLoc DL(Op);
3112       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3113       SDValue Powi =
3114           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3115       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3116                          DAG.getIntPtrConstant(0, DL));
3117     }
3118     return SDValue();
3119   }
3120   case ISD::FP_EXTEND: {
3121     // RVV can only do fp_extend to types double the size as the source. We
3122     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3123     // via f32.
3124     SDLoc DL(Op);
3125     MVT VT = Op.getSimpleValueType();
3126     SDValue Src = Op.getOperand(0);
3127     MVT SrcVT = Src.getSimpleValueType();
3128 
3129     // Prepare any fixed-length vector operands.
3130     MVT ContainerVT = VT;
3131     if (SrcVT.isFixedLengthVector()) {
3132       ContainerVT = getContainerForFixedLengthVector(VT);
3133       MVT SrcContainerVT =
3134           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3135       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3136     }
3137 
3138     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3139         SrcVT.getVectorElementType() != MVT::f16) {
3140       // For scalable vectors, we only need to close the gap between
3141       // vXf16->vXf64.
3142       if (!VT.isFixedLengthVector())
3143         return Op;
3144       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3145       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3146       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3147     }
3148 
3149     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3150     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3151     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3152         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3153 
3154     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3155                                            DL, DAG, Subtarget);
3156     if (VT.isFixedLengthVector())
3157       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3158     return Extend;
3159   }
3160   case ISD::FP_ROUND: {
3161     // RVV can only do fp_round to types half the size as the source. We
3162     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3163     // conversion instruction.
3164     SDLoc DL(Op);
3165     MVT VT = Op.getSimpleValueType();
3166     SDValue Src = Op.getOperand(0);
3167     MVT SrcVT = Src.getSimpleValueType();
3168 
3169     // Prepare any fixed-length vector operands.
3170     MVT ContainerVT = VT;
3171     if (VT.isFixedLengthVector()) {
3172       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3173       ContainerVT =
3174           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3175       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3176     }
3177 
3178     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3179         SrcVT.getVectorElementType() != MVT::f64) {
3180       // For scalable vectors, we only need to close the gap between
3181       // vXf64<->vXf16.
3182       if (!VT.isFixedLengthVector())
3183         return Op;
3184       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3185       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3186       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3187     }
3188 
3189     SDValue Mask, VL;
3190     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3191 
3192     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3193     SDValue IntermediateRound =
3194         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3195     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3196                                           DL, DAG, Subtarget);
3197 
3198     if (VT.isFixedLengthVector())
3199       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3200     return Round;
3201   }
3202   case ISD::FP_TO_SINT:
3203   case ISD::FP_TO_UINT:
3204   case ISD::SINT_TO_FP:
3205   case ISD::UINT_TO_FP: {
3206     // RVV can only do fp<->int conversions to types half/double the size as
3207     // the source. We custom-lower any conversions that do two hops into
3208     // sequences.
3209     MVT VT = Op.getSimpleValueType();
3210     if (!VT.isVector())
3211       return Op;
3212     SDLoc DL(Op);
3213     SDValue Src = Op.getOperand(0);
3214     MVT EltVT = VT.getVectorElementType();
3215     MVT SrcVT = Src.getSimpleValueType();
3216     MVT SrcEltVT = SrcVT.getVectorElementType();
3217     unsigned EltSize = EltVT.getSizeInBits();
3218     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3219     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3220            "Unexpected vector element types");
3221 
3222     bool IsInt2FP = SrcEltVT.isInteger();
3223     // Widening conversions
3224     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3225       if (IsInt2FP) {
3226         // Do a regular integer sign/zero extension then convert to float.
3227         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3228                                       VT.getVectorElementCount());
3229         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3230                                  ? ISD::ZERO_EXTEND
3231                                  : ISD::SIGN_EXTEND;
3232         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3233         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3234       }
3235       // FP2Int
3236       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3237       // Do one doubling fp_extend then complete the operation by converting
3238       // to int.
3239       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3240       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3241       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3242     }
3243 
3244     // Narrowing conversions
3245     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3246       if (IsInt2FP) {
3247         // One narrowing int_to_fp, then an fp_round.
3248         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3249         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3250         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3251         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3252       }
3253       // FP2Int
3254       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3255       // representable by the integer, the result is poison.
3256       MVT IVecVT =
3257           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3258                            VT.getVectorElementCount());
3259       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3260       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3261     }
3262 
3263     // Scalable vectors can exit here. Patterns will handle equally-sized
3264     // conversions halving/doubling ones.
3265     if (!VT.isFixedLengthVector())
3266       return Op;
3267 
3268     // For fixed-length vectors we lower to a custom "VL" node.
3269     unsigned RVVOpc = 0;
3270     switch (Op.getOpcode()) {
3271     default:
3272       llvm_unreachable("Impossible opcode");
3273     case ISD::FP_TO_SINT:
3274       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3275       break;
3276     case ISD::FP_TO_UINT:
3277       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3278       break;
3279     case ISD::SINT_TO_FP:
3280       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3281       break;
3282     case ISD::UINT_TO_FP:
3283       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3284       break;
3285     }
3286 
3287     MVT ContainerVT, SrcContainerVT;
3288     // Derive the reference container type from the larger vector type.
3289     if (SrcEltSize > EltSize) {
3290       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3291       ContainerVT =
3292           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3293     } else {
3294       ContainerVT = getContainerForFixedLengthVector(VT);
3295       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3296     }
3297 
3298     SDValue Mask, VL;
3299     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3300 
3301     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3302     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3303     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3304   }
3305   case ISD::FP_TO_SINT_SAT:
3306   case ISD::FP_TO_UINT_SAT:
3307     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3308   case ISD::FTRUNC:
3309   case ISD::FCEIL:
3310   case ISD::FFLOOR:
3311     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3312   case ISD::VECREDUCE_ADD:
3313   case ISD::VECREDUCE_UMAX:
3314   case ISD::VECREDUCE_SMAX:
3315   case ISD::VECREDUCE_UMIN:
3316   case ISD::VECREDUCE_SMIN:
3317     return lowerVECREDUCE(Op, DAG);
3318   case ISD::VECREDUCE_AND:
3319   case ISD::VECREDUCE_OR:
3320   case ISD::VECREDUCE_XOR:
3321     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3322       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3323     return lowerVECREDUCE(Op, DAG);
3324   case ISD::VECREDUCE_FADD:
3325   case ISD::VECREDUCE_SEQ_FADD:
3326   case ISD::VECREDUCE_FMIN:
3327   case ISD::VECREDUCE_FMAX:
3328     return lowerFPVECREDUCE(Op, DAG);
3329   case ISD::VP_REDUCE_ADD:
3330   case ISD::VP_REDUCE_UMAX:
3331   case ISD::VP_REDUCE_SMAX:
3332   case ISD::VP_REDUCE_UMIN:
3333   case ISD::VP_REDUCE_SMIN:
3334   case ISD::VP_REDUCE_FADD:
3335   case ISD::VP_REDUCE_SEQ_FADD:
3336   case ISD::VP_REDUCE_FMIN:
3337   case ISD::VP_REDUCE_FMAX:
3338     return lowerVPREDUCE(Op, DAG);
3339   case ISD::VP_REDUCE_AND:
3340   case ISD::VP_REDUCE_OR:
3341   case ISD::VP_REDUCE_XOR:
3342     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3343       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3344     return lowerVPREDUCE(Op, DAG);
3345   case ISD::INSERT_SUBVECTOR:
3346     return lowerINSERT_SUBVECTOR(Op, DAG);
3347   case ISD::EXTRACT_SUBVECTOR:
3348     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3349   case ISD::STEP_VECTOR:
3350     return lowerSTEP_VECTOR(Op, DAG);
3351   case ISD::VECTOR_REVERSE:
3352     return lowerVECTOR_REVERSE(Op, DAG);
3353   case ISD::BUILD_VECTOR:
3354     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3355   case ISD::SPLAT_VECTOR:
3356     if (Op.getValueType().getVectorElementType() == MVT::i1)
3357       return lowerVectorMaskSplat(Op, DAG);
3358     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3359   case ISD::VECTOR_SHUFFLE:
3360     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3361   case ISD::CONCAT_VECTORS: {
3362     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3363     // better than going through the stack, as the default expansion does.
3364     SDLoc DL(Op);
3365     MVT VT = Op.getSimpleValueType();
3366     unsigned NumOpElts =
3367         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3368     SDValue Vec = DAG.getUNDEF(VT);
3369     for (const auto &OpIdx : enumerate(Op->ops())) {
3370       SDValue SubVec = OpIdx.value();
3371       // Don't insert undef subvectors.
3372       if (SubVec.isUndef())
3373         continue;
3374       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3375                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3376     }
3377     return Vec;
3378   }
3379   case ISD::LOAD:
3380     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3381       return V;
3382     if (Op.getValueType().isFixedLengthVector())
3383       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3384     return Op;
3385   case ISD::STORE:
3386     if (auto V = expandUnalignedRVVStore(Op, DAG))
3387       return V;
3388     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3389       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3390     return Op;
3391   case ISD::MLOAD:
3392   case ISD::VP_LOAD:
3393     return lowerMaskedLoad(Op, DAG);
3394   case ISD::MSTORE:
3395   case ISD::VP_STORE:
3396     return lowerMaskedStore(Op, DAG);
3397   case ISD::SETCC:
3398     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3399   case ISD::ADD:
3400     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3401   case ISD::SUB:
3402     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3403   case ISD::MUL:
3404     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3405   case ISD::MULHS:
3406     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3407   case ISD::MULHU:
3408     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3409   case ISD::AND:
3410     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3411                                               RISCVISD::AND_VL);
3412   case ISD::OR:
3413     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3414                                               RISCVISD::OR_VL);
3415   case ISD::XOR:
3416     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3417                                               RISCVISD::XOR_VL);
3418   case ISD::SDIV:
3419     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3420   case ISD::SREM:
3421     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3422   case ISD::UDIV:
3423     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3424   case ISD::UREM:
3425     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3426   case ISD::SHL:
3427   case ISD::SRA:
3428   case ISD::SRL:
3429     if (Op.getSimpleValueType().isFixedLengthVector())
3430       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3431     // This can be called for an i32 shift amount that needs to be promoted.
3432     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3433            "Unexpected custom legalisation");
3434     return SDValue();
3435   case ISD::SADDSAT:
3436     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3437   case ISD::UADDSAT:
3438     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3439   case ISD::SSUBSAT:
3440     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3441   case ISD::USUBSAT:
3442     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3443   case ISD::FADD:
3444     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3445   case ISD::FSUB:
3446     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3447   case ISD::FMUL:
3448     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3449   case ISD::FDIV:
3450     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3451   case ISD::FNEG:
3452     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3453   case ISD::FABS:
3454     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3455   case ISD::FSQRT:
3456     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3457   case ISD::FMA:
3458     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3459   case ISD::SMIN:
3460     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3461   case ISD::SMAX:
3462     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3463   case ISD::UMIN:
3464     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3465   case ISD::UMAX:
3466     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3467   case ISD::FMINNUM:
3468     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3469   case ISD::FMAXNUM:
3470     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3471   case ISD::ABS:
3472     return lowerABS(Op, DAG);
3473   case ISD::CTLZ_ZERO_UNDEF:
3474   case ISD::CTTZ_ZERO_UNDEF:
3475     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3476   case ISD::VSELECT:
3477     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3478   case ISD::FCOPYSIGN:
3479     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3480   case ISD::MGATHER:
3481   case ISD::VP_GATHER:
3482     return lowerMaskedGather(Op, DAG);
3483   case ISD::MSCATTER:
3484   case ISD::VP_SCATTER:
3485     return lowerMaskedScatter(Op, DAG);
3486   case ISD::FLT_ROUNDS_:
3487     return lowerGET_ROUNDING(Op, DAG);
3488   case ISD::SET_ROUNDING:
3489     return lowerSET_ROUNDING(Op, DAG);
3490   case ISD::VP_SELECT:
3491     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3492   case ISD::VP_MERGE:
3493     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3494   case ISD::VP_ADD:
3495     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3496   case ISD::VP_SUB:
3497     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3498   case ISD::VP_MUL:
3499     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3500   case ISD::VP_SDIV:
3501     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3502   case ISD::VP_UDIV:
3503     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3504   case ISD::VP_SREM:
3505     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3506   case ISD::VP_UREM:
3507     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3508   case ISD::VP_AND:
3509     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3510   case ISD::VP_OR:
3511     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3512   case ISD::VP_XOR:
3513     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3514   case ISD::VP_ASHR:
3515     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3516   case ISD::VP_LSHR:
3517     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3518   case ISD::VP_SHL:
3519     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3520   case ISD::VP_FADD:
3521     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3522   case ISD::VP_FSUB:
3523     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3524   case ISD::VP_FMUL:
3525     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3526   case ISD::VP_FDIV:
3527     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3528   }
3529 }
3530 
3531 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3532                              SelectionDAG &DAG, unsigned Flags) {
3533   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3534 }
3535 
3536 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3537                              SelectionDAG &DAG, unsigned Flags) {
3538   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3539                                    Flags);
3540 }
3541 
3542 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3543                              SelectionDAG &DAG, unsigned Flags) {
3544   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3545                                    N->getOffset(), Flags);
3546 }
3547 
3548 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3549                              SelectionDAG &DAG, unsigned Flags) {
3550   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3551 }
3552 
3553 template <class NodeTy>
3554 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3555                                      bool IsLocal) const {
3556   SDLoc DL(N);
3557   EVT Ty = getPointerTy(DAG.getDataLayout());
3558 
3559   if (isPositionIndependent()) {
3560     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3561     if (IsLocal)
3562       // Use PC-relative addressing to access the symbol. This generates the
3563       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3564       // %pcrel_lo(auipc)).
3565       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3566 
3567     // Use PC-relative addressing to access the GOT for this symbol, then load
3568     // the address from the GOT. This generates the pattern (PseudoLA sym),
3569     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3570     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3571   }
3572 
3573   switch (getTargetMachine().getCodeModel()) {
3574   default:
3575     report_fatal_error("Unsupported code model for lowering");
3576   case CodeModel::Small: {
3577     // Generate a sequence for accessing addresses within the first 2 GiB of
3578     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3579     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3580     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3581     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3582     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3583   }
3584   case CodeModel::Medium: {
3585     // Generate a sequence for accessing addresses within any 2GiB range within
3586     // the address space. This generates the pattern (PseudoLLA sym), which
3587     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3588     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3589     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3590   }
3591   }
3592 }
3593 
3594 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3595                                                 SelectionDAG &DAG) const {
3596   SDLoc DL(Op);
3597   EVT Ty = Op.getValueType();
3598   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3599   int64_t Offset = N->getOffset();
3600   MVT XLenVT = Subtarget.getXLenVT();
3601 
3602   const GlobalValue *GV = N->getGlobal();
3603   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3604   SDValue Addr = getAddr(N, DAG, IsLocal);
3605 
3606   // In order to maximise the opportunity for common subexpression elimination,
3607   // emit a separate ADD node for the global address offset instead of folding
3608   // it in the global address node. Later peephole optimisations may choose to
3609   // fold it back in when profitable.
3610   if (Offset != 0)
3611     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3612                        DAG.getConstant(Offset, DL, XLenVT));
3613   return Addr;
3614 }
3615 
3616 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3617                                                SelectionDAG &DAG) const {
3618   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3619 
3620   return getAddr(N, DAG);
3621 }
3622 
3623 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3624                                                SelectionDAG &DAG) const {
3625   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3626 
3627   return getAddr(N, DAG);
3628 }
3629 
3630 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3631                                             SelectionDAG &DAG) const {
3632   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3633 
3634   return getAddr(N, DAG);
3635 }
3636 
3637 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3638                                               SelectionDAG &DAG,
3639                                               bool UseGOT) const {
3640   SDLoc DL(N);
3641   EVT Ty = getPointerTy(DAG.getDataLayout());
3642   const GlobalValue *GV = N->getGlobal();
3643   MVT XLenVT = Subtarget.getXLenVT();
3644 
3645   if (UseGOT) {
3646     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3647     // load the address from the GOT and add the thread pointer. This generates
3648     // the pattern (PseudoLA_TLS_IE sym), which expands to
3649     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3650     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3651     SDValue Load =
3652         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3653 
3654     // Add the thread pointer.
3655     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3656     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3657   }
3658 
3659   // Generate a sequence for accessing the address relative to the thread
3660   // pointer, with the appropriate adjustment for the thread pointer offset.
3661   // This generates the pattern
3662   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3663   SDValue AddrHi =
3664       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3665   SDValue AddrAdd =
3666       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3667   SDValue AddrLo =
3668       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3669 
3670   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3671   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3672   SDValue MNAdd = SDValue(
3673       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3674       0);
3675   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3676 }
3677 
3678 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3679                                                SelectionDAG &DAG) const {
3680   SDLoc DL(N);
3681   EVT Ty = getPointerTy(DAG.getDataLayout());
3682   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3683   const GlobalValue *GV = N->getGlobal();
3684 
3685   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3686   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3687   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3688   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3689   SDValue Load =
3690       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3691 
3692   // Prepare argument list to generate call.
3693   ArgListTy Args;
3694   ArgListEntry Entry;
3695   Entry.Node = Load;
3696   Entry.Ty = CallTy;
3697   Args.push_back(Entry);
3698 
3699   // Setup call to __tls_get_addr.
3700   TargetLowering::CallLoweringInfo CLI(DAG);
3701   CLI.setDebugLoc(DL)
3702       .setChain(DAG.getEntryNode())
3703       .setLibCallee(CallingConv::C, CallTy,
3704                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3705                     std::move(Args));
3706 
3707   return LowerCallTo(CLI).first;
3708 }
3709 
3710 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3711                                                    SelectionDAG &DAG) const {
3712   SDLoc DL(Op);
3713   EVT Ty = Op.getValueType();
3714   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3715   int64_t Offset = N->getOffset();
3716   MVT XLenVT = Subtarget.getXLenVT();
3717 
3718   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3719 
3720   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3721       CallingConv::GHC)
3722     report_fatal_error("In GHC calling convention TLS is not supported");
3723 
3724   SDValue Addr;
3725   switch (Model) {
3726   case TLSModel::LocalExec:
3727     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3728     break;
3729   case TLSModel::InitialExec:
3730     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3731     break;
3732   case TLSModel::LocalDynamic:
3733   case TLSModel::GeneralDynamic:
3734     Addr = getDynamicTLSAddr(N, DAG);
3735     break;
3736   }
3737 
3738   // In order to maximise the opportunity for common subexpression elimination,
3739   // emit a separate ADD node for the global address offset instead of folding
3740   // it in the global address node. Later peephole optimisations may choose to
3741   // fold it back in when profitable.
3742   if (Offset != 0)
3743     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3744                        DAG.getConstant(Offset, DL, XLenVT));
3745   return Addr;
3746 }
3747 
3748 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3749   SDValue CondV = Op.getOperand(0);
3750   SDValue TrueV = Op.getOperand(1);
3751   SDValue FalseV = Op.getOperand(2);
3752   SDLoc DL(Op);
3753   MVT VT = Op.getSimpleValueType();
3754   MVT XLenVT = Subtarget.getXLenVT();
3755 
3756   // Lower vector SELECTs to VSELECTs by splatting the condition.
3757   if (VT.isVector()) {
3758     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3759     SDValue CondSplat = VT.isScalableVector()
3760                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3761                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3762     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3763   }
3764 
3765   // If the result type is XLenVT and CondV is the output of a SETCC node
3766   // which also operated on XLenVT inputs, then merge the SETCC node into the
3767   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3768   // compare+branch instructions. i.e.:
3769   // (select (setcc lhs, rhs, cc), truev, falsev)
3770   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3771   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3772       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3773     SDValue LHS = CondV.getOperand(0);
3774     SDValue RHS = CondV.getOperand(1);
3775     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3776     ISD::CondCode CCVal = CC->get();
3777 
3778     // Special case for a select of 2 constants that have a diffence of 1.
3779     // Normally this is done by DAGCombine, but if the select is introduced by
3780     // type legalization or op legalization, we miss it. Restricting to SETLT
3781     // case for now because that is what signed saturating add/sub need.
3782     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3783     // but we would probably want to swap the true/false values if the condition
3784     // is SETGE/SETLE to avoid an XORI.
3785     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3786         CCVal == ISD::SETLT) {
3787       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3788       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3789       if (TrueVal - 1 == FalseVal)
3790         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3791       if (TrueVal + 1 == FalseVal)
3792         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3793     }
3794 
3795     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3796 
3797     SDValue TargetCC = DAG.getCondCode(CCVal);
3798     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3799     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3800   }
3801 
3802   // Otherwise:
3803   // (select condv, truev, falsev)
3804   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3805   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3806   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3807 
3808   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3809 
3810   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3811 }
3812 
3813 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3814   SDValue CondV = Op.getOperand(1);
3815   SDLoc DL(Op);
3816   MVT XLenVT = Subtarget.getXLenVT();
3817 
3818   if (CondV.getOpcode() == ISD::SETCC &&
3819       CondV.getOperand(0).getValueType() == XLenVT) {
3820     SDValue LHS = CondV.getOperand(0);
3821     SDValue RHS = CondV.getOperand(1);
3822     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3823 
3824     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3825 
3826     SDValue TargetCC = DAG.getCondCode(CCVal);
3827     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3828                        LHS, RHS, TargetCC, Op.getOperand(2));
3829   }
3830 
3831   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3832                      CondV, DAG.getConstant(0, DL, XLenVT),
3833                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3834 }
3835 
3836 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3837   MachineFunction &MF = DAG.getMachineFunction();
3838   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3839 
3840   SDLoc DL(Op);
3841   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3842                                  getPointerTy(MF.getDataLayout()));
3843 
3844   // vastart just stores the address of the VarArgsFrameIndex slot into the
3845   // memory location argument.
3846   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3847   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3848                       MachinePointerInfo(SV));
3849 }
3850 
3851 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3852                                             SelectionDAG &DAG) const {
3853   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3854   MachineFunction &MF = DAG.getMachineFunction();
3855   MachineFrameInfo &MFI = MF.getFrameInfo();
3856   MFI.setFrameAddressIsTaken(true);
3857   Register FrameReg = RI.getFrameRegister(MF);
3858   int XLenInBytes = Subtarget.getXLen() / 8;
3859 
3860   EVT VT = Op.getValueType();
3861   SDLoc DL(Op);
3862   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3863   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3864   while (Depth--) {
3865     int Offset = -(XLenInBytes * 2);
3866     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3867                               DAG.getIntPtrConstant(Offset, DL));
3868     FrameAddr =
3869         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3870   }
3871   return FrameAddr;
3872 }
3873 
3874 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3875                                              SelectionDAG &DAG) const {
3876   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3877   MachineFunction &MF = DAG.getMachineFunction();
3878   MachineFrameInfo &MFI = MF.getFrameInfo();
3879   MFI.setReturnAddressIsTaken(true);
3880   MVT XLenVT = Subtarget.getXLenVT();
3881   int XLenInBytes = Subtarget.getXLen() / 8;
3882 
3883   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3884     return SDValue();
3885 
3886   EVT VT = Op.getValueType();
3887   SDLoc DL(Op);
3888   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3889   if (Depth) {
3890     int Off = -XLenInBytes;
3891     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3892     SDValue Offset = DAG.getConstant(Off, DL, VT);
3893     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3894                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3895                        MachinePointerInfo());
3896   }
3897 
3898   // Return the value of the return address register, marking it an implicit
3899   // live-in.
3900   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3901   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3902 }
3903 
3904 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3905                                                  SelectionDAG &DAG) const {
3906   SDLoc DL(Op);
3907   SDValue Lo = Op.getOperand(0);
3908   SDValue Hi = Op.getOperand(1);
3909   SDValue Shamt = Op.getOperand(2);
3910   EVT VT = Lo.getValueType();
3911 
3912   // if Shamt-XLEN < 0: // Shamt < XLEN
3913   //   Lo = Lo << Shamt
3914   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3915   // else:
3916   //   Lo = 0
3917   //   Hi = Lo << (Shamt-XLEN)
3918 
3919   SDValue Zero = DAG.getConstant(0, DL, VT);
3920   SDValue One = DAG.getConstant(1, DL, VT);
3921   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3922   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3923   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3924   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3925 
3926   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3927   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3928   SDValue ShiftRightLo =
3929       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3930   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3931   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3932   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3933 
3934   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3935 
3936   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3937   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3938 
3939   SDValue Parts[2] = {Lo, Hi};
3940   return DAG.getMergeValues(Parts, DL);
3941 }
3942 
3943 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3944                                                   bool IsSRA) const {
3945   SDLoc DL(Op);
3946   SDValue Lo = Op.getOperand(0);
3947   SDValue Hi = Op.getOperand(1);
3948   SDValue Shamt = Op.getOperand(2);
3949   EVT VT = Lo.getValueType();
3950 
3951   // SRA expansion:
3952   //   if Shamt-XLEN < 0: // Shamt < XLEN
3953   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3954   //     Hi = Hi >>s Shamt
3955   //   else:
3956   //     Lo = Hi >>s (Shamt-XLEN);
3957   //     Hi = Hi >>s (XLEN-1)
3958   //
3959   // SRL expansion:
3960   //   if Shamt-XLEN < 0: // Shamt < XLEN
3961   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3962   //     Hi = Hi >>u Shamt
3963   //   else:
3964   //     Lo = Hi >>u (Shamt-XLEN);
3965   //     Hi = 0;
3966 
3967   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3968 
3969   SDValue Zero = DAG.getConstant(0, DL, VT);
3970   SDValue One = DAG.getConstant(1, DL, VT);
3971   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3972   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3973   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3974   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3975 
3976   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3977   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3978   SDValue ShiftLeftHi =
3979       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3980   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3981   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3982   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3983   SDValue HiFalse =
3984       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3985 
3986   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3987 
3988   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3989   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3990 
3991   SDValue Parts[2] = {Lo, Hi};
3992   return DAG.getMergeValues(Parts, DL);
3993 }
3994 
3995 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3996 // legal equivalently-sized i8 type, so we can use that as a go-between.
3997 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3998                                                   SelectionDAG &DAG) const {
3999   SDLoc DL(Op);
4000   MVT VT = Op.getSimpleValueType();
4001   SDValue SplatVal = Op.getOperand(0);
4002   // All-zeros or all-ones splats are handled specially.
4003   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4004     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4005     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4006   }
4007   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4008     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4009     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4010   }
4011   MVT XLenVT = Subtarget.getXLenVT();
4012   assert(SplatVal.getValueType() == XLenVT &&
4013          "Unexpected type for i1 splat value");
4014   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4015   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4016                          DAG.getConstant(1, DL, XLenVT));
4017   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4018   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4019   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4020 }
4021 
4022 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4023 // illegal (currently only vXi64 RV32).
4024 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4025 // them to SPLAT_VECTOR_I64
4026 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4027                                                      SelectionDAG &DAG) const {
4028   SDLoc DL(Op);
4029   MVT VecVT = Op.getSimpleValueType();
4030   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4031          "Unexpected SPLAT_VECTOR_PARTS lowering");
4032 
4033   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4034   SDValue Lo = Op.getOperand(0);
4035   SDValue Hi = Op.getOperand(1);
4036 
4037   if (VecVT.isFixedLengthVector()) {
4038     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4039     SDLoc DL(Op);
4040     SDValue Mask, VL;
4041     std::tie(Mask, VL) =
4042         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4043 
4044     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
4045     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4046   }
4047 
4048   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4049     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4050     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4051     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4052     // node in order to try and match RVV vector/scalar instructions.
4053     if ((LoC >> 31) == HiC)
4054       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4055   }
4056 
4057   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4058   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4059       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4060       Hi.getConstantOperandVal(1) == 31)
4061     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4062 
4063   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4064   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4065                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
4066 }
4067 
4068 // Custom-lower extensions from mask vectors by using a vselect either with 1
4069 // for zero/any-extension or -1 for sign-extension:
4070 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4071 // Note that any-extension is lowered identically to zero-extension.
4072 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4073                                                 int64_t ExtTrueVal) const {
4074   SDLoc DL(Op);
4075   MVT VecVT = Op.getSimpleValueType();
4076   SDValue Src = Op.getOperand(0);
4077   // Only custom-lower extensions from mask types
4078   assert(Src.getValueType().isVector() &&
4079          Src.getValueType().getVectorElementType() == MVT::i1);
4080 
4081   MVT XLenVT = Subtarget.getXLenVT();
4082   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4083   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4084 
4085   if (VecVT.isScalableVector()) {
4086     // Be careful not to introduce illegal scalar types at this stage, and be
4087     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4088     // illegal and must be expanded. Since we know that the constants are
4089     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
4090     bool IsRV32E64 =
4091         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4092 
4093     if (!IsRV32E64) {
4094       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4095       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4096     } else {
4097       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
4098       SplatTrueVal =
4099           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
4100     }
4101 
4102     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4103   }
4104 
4105   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4106   MVT I1ContainerVT =
4107       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4108 
4109   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4110 
4111   SDValue Mask, VL;
4112   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4113 
4114   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4115   SplatTrueVal =
4116       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4117   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4118                                SplatTrueVal, SplatZero, VL);
4119 
4120   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4121 }
4122 
4123 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4124     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4125   MVT ExtVT = Op.getSimpleValueType();
4126   // Only custom-lower extensions from fixed-length vector types.
4127   if (!ExtVT.isFixedLengthVector())
4128     return Op;
4129   MVT VT = Op.getOperand(0).getSimpleValueType();
4130   // Grab the canonical container type for the extended type. Infer the smaller
4131   // type from that to ensure the same number of vector elements, as we know
4132   // the LMUL will be sufficient to hold the smaller type.
4133   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4134   // Get the extended container type manually to ensure the same number of
4135   // vector elements between source and dest.
4136   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4137                                      ContainerExtVT.getVectorElementCount());
4138 
4139   SDValue Op1 =
4140       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4141 
4142   SDLoc DL(Op);
4143   SDValue Mask, VL;
4144   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4145 
4146   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4147 
4148   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4149 }
4150 
4151 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4152 // setcc operation:
4153 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4154 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4155                                                   SelectionDAG &DAG) const {
4156   SDLoc DL(Op);
4157   EVT MaskVT = Op.getValueType();
4158   // Only expect to custom-lower truncations to mask types
4159   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4160          "Unexpected type for vector mask lowering");
4161   SDValue Src = Op.getOperand(0);
4162   MVT VecVT = Src.getSimpleValueType();
4163 
4164   // If this is a fixed vector, we need to convert it to a scalable vector.
4165   MVT ContainerVT = VecVT;
4166   if (VecVT.isFixedLengthVector()) {
4167     ContainerVT = getContainerForFixedLengthVector(VecVT);
4168     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4169   }
4170 
4171   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4172   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4173 
4174   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4175   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4176 
4177   if (VecVT.isScalableVector()) {
4178     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4179     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4180   }
4181 
4182   SDValue Mask, VL;
4183   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4184 
4185   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4186   SDValue Trunc =
4187       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4188   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4189                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4190   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4191 }
4192 
4193 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4194 // first position of a vector, and that vector is slid up to the insert index.
4195 // By limiting the active vector length to index+1 and merging with the
4196 // original vector (with an undisturbed tail policy for elements >= VL), we
4197 // achieve the desired result of leaving all elements untouched except the one
4198 // at VL-1, which is replaced with the desired value.
4199 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4200                                                     SelectionDAG &DAG) const {
4201   SDLoc DL(Op);
4202   MVT VecVT = Op.getSimpleValueType();
4203   SDValue Vec = Op.getOperand(0);
4204   SDValue Val = Op.getOperand(1);
4205   SDValue Idx = Op.getOperand(2);
4206 
4207   if (VecVT.getVectorElementType() == MVT::i1) {
4208     // FIXME: For now we just promote to an i8 vector and insert into that,
4209     // but this is probably not optimal.
4210     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4211     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4212     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4213     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4214   }
4215 
4216   MVT ContainerVT = VecVT;
4217   // If the operand is a fixed-length vector, convert to a scalable one.
4218   if (VecVT.isFixedLengthVector()) {
4219     ContainerVT = getContainerForFixedLengthVector(VecVT);
4220     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4221   }
4222 
4223   MVT XLenVT = Subtarget.getXLenVT();
4224 
4225   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4226   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4227   // Even i64-element vectors on RV32 can be lowered without scalar
4228   // legalization if the most-significant 32 bits of the value are not affected
4229   // by the sign-extension of the lower 32 bits.
4230   // TODO: We could also catch sign extensions of a 32-bit value.
4231   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4232     const auto *CVal = cast<ConstantSDNode>(Val);
4233     if (isInt<32>(CVal->getSExtValue())) {
4234       IsLegalInsert = true;
4235       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4236     }
4237   }
4238 
4239   SDValue Mask, VL;
4240   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4241 
4242   SDValue ValInVec;
4243 
4244   if (IsLegalInsert) {
4245     unsigned Opc =
4246         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4247     if (isNullConstant(Idx)) {
4248       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4249       if (!VecVT.isFixedLengthVector())
4250         return Vec;
4251       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4252     }
4253     ValInVec =
4254         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4255   } else {
4256     // On RV32, i64-element vectors must be specially handled to place the
4257     // value at element 0, by using two vslide1up instructions in sequence on
4258     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4259     // this.
4260     SDValue One = DAG.getConstant(1, DL, XLenVT);
4261     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4262     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4263     MVT I32ContainerVT =
4264         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4265     SDValue I32Mask =
4266         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4267     // Limit the active VL to two.
4268     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4269     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4270     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4271     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4272                            InsertI64VL);
4273     // First slide in the hi value, then the lo in underneath it.
4274     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4275                            ValHi, I32Mask, InsertI64VL);
4276     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4277                            ValLo, I32Mask, InsertI64VL);
4278     // Bitcast back to the right container type.
4279     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4280   }
4281 
4282   // Now that the value is in a vector, slide it into position.
4283   SDValue InsertVL =
4284       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4285   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4286                                 ValInVec, Idx, Mask, InsertVL);
4287   if (!VecVT.isFixedLengthVector())
4288     return Slideup;
4289   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4290 }
4291 
4292 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4293 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4294 // types this is done using VMV_X_S to allow us to glean information about the
4295 // sign bits of the result.
4296 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4297                                                      SelectionDAG &DAG) const {
4298   SDLoc DL(Op);
4299   SDValue Idx = Op.getOperand(1);
4300   SDValue Vec = Op.getOperand(0);
4301   EVT EltVT = Op.getValueType();
4302   MVT VecVT = Vec.getSimpleValueType();
4303   MVT XLenVT = Subtarget.getXLenVT();
4304 
4305   if (VecVT.getVectorElementType() == MVT::i1) {
4306     if (VecVT.isFixedLengthVector()) {
4307       unsigned NumElts = VecVT.getVectorNumElements();
4308       if (NumElts >= 8) {
4309         MVT WideEltVT;
4310         unsigned WidenVecLen;
4311         SDValue ExtractElementIdx;
4312         SDValue ExtractBitIdx;
4313         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4314         MVT LargestEltVT = MVT::getIntegerVT(
4315             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4316         if (NumElts <= LargestEltVT.getSizeInBits()) {
4317           assert(isPowerOf2_32(NumElts) &&
4318                  "the number of elements should be power of 2");
4319           WideEltVT = MVT::getIntegerVT(NumElts);
4320           WidenVecLen = 1;
4321           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4322           ExtractBitIdx = Idx;
4323         } else {
4324           WideEltVT = LargestEltVT;
4325           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4326           // extract element index = index / element width
4327           ExtractElementIdx = DAG.getNode(
4328               ISD::SRL, DL, XLenVT, Idx,
4329               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4330           // mask bit index = index % element width
4331           ExtractBitIdx = DAG.getNode(
4332               ISD::AND, DL, XLenVT, Idx,
4333               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4334         }
4335         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4336         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4337         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4338                                          Vec, ExtractElementIdx);
4339         // Extract the bit from GPR.
4340         SDValue ShiftRight =
4341             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4342         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4343                            DAG.getConstant(1, DL, XLenVT));
4344       }
4345     }
4346     // Otherwise, promote to an i8 vector and extract from that.
4347     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4348     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4349     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4350   }
4351 
4352   // If this is a fixed vector, we need to convert it to a scalable vector.
4353   MVT ContainerVT = VecVT;
4354   if (VecVT.isFixedLengthVector()) {
4355     ContainerVT = getContainerForFixedLengthVector(VecVT);
4356     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4357   }
4358 
4359   // If the index is 0, the vector is already in the right position.
4360   if (!isNullConstant(Idx)) {
4361     // Use a VL of 1 to avoid processing more elements than we need.
4362     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4363     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4364     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4365     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4366                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4367   }
4368 
4369   if (!EltVT.isInteger()) {
4370     // Floating-point extracts are handled in TableGen.
4371     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4372                        DAG.getConstant(0, DL, XLenVT));
4373   }
4374 
4375   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4376   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4377 }
4378 
4379 // Some RVV intrinsics may claim that they want an integer operand to be
4380 // promoted or expanded.
4381 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4382                                           const RISCVSubtarget &Subtarget) {
4383   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4384           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4385          "Unexpected opcode");
4386 
4387   if (!Subtarget.hasVInstructions())
4388     return SDValue();
4389 
4390   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4391   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4392   SDLoc DL(Op);
4393 
4394   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4395       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4396   if (!II || !II->hasSplatOperand())
4397     return SDValue();
4398 
4399   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4400   assert(SplatOp < Op.getNumOperands());
4401 
4402   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4403   SDValue &ScalarOp = Operands[SplatOp];
4404   MVT OpVT = ScalarOp.getSimpleValueType();
4405   MVT XLenVT = Subtarget.getXLenVT();
4406 
4407   // If this isn't a scalar, or its type is XLenVT we're done.
4408   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4409     return SDValue();
4410 
4411   // Simplest case is that the operand needs to be promoted to XLenVT.
4412   if (OpVT.bitsLT(XLenVT)) {
4413     // If the operand is a constant, sign extend to increase our chances
4414     // of being able to use a .vi instruction. ANY_EXTEND would become a
4415     // a zero extend and the simm5 check in isel would fail.
4416     // FIXME: Should we ignore the upper bits in isel instead?
4417     unsigned ExtOpc =
4418         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4419     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4420     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4421   }
4422 
4423   // Use the previous operand to get the vXi64 VT. The result might be a mask
4424   // VT for compares. Using the previous operand assumes that the previous
4425   // operand will never have a smaller element size than a scalar operand and
4426   // that a widening operation never uses SEW=64.
4427   // NOTE: If this fails the below assert, we can probably just find the
4428   // element count from any operand or result and use it to construct the VT.
4429   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4430   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4431 
4432   // The more complex case is when the scalar is larger than XLenVT.
4433   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4434          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4435 
4436   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4437   // on the instruction to sign-extend since SEW>XLEN.
4438   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4439     if (isInt<32>(CVal->getSExtValue())) {
4440       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4441       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4442     }
4443   }
4444 
4445   // We need to convert the scalar to a splat vector.
4446   // FIXME: Can we implicitly truncate the scalar if it is known to
4447   // be sign extended?
4448   SDValue VL = getVLOperand(Op);
4449   assert(VL.getValueType() == XLenVT);
4450   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4451   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4452 }
4453 
4454 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4455                                                      SelectionDAG &DAG) const {
4456   unsigned IntNo = Op.getConstantOperandVal(0);
4457   SDLoc DL(Op);
4458   MVT XLenVT = Subtarget.getXLenVT();
4459 
4460   switch (IntNo) {
4461   default:
4462     break; // Don't custom lower most intrinsics.
4463   case Intrinsic::thread_pointer: {
4464     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4465     return DAG.getRegister(RISCV::X4, PtrVT);
4466   }
4467   case Intrinsic::riscv_orc_b:
4468   case Intrinsic::riscv_brev8: {
4469     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4470     unsigned Opc =
4471         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4472     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4473                        DAG.getConstant(7, DL, XLenVT));
4474   }
4475   case Intrinsic::riscv_grev:
4476   case Intrinsic::riscv_gorc: {
4477     unsigned Opc =
4478         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4479     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4480   }
4481   case Intrinsic::riscv_zip:
4482   case Intrinsic::riscv_unzip: {
4483     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4484     // For i32 the immdiate is 15. For i64 the immediate is 31.
4485     unsigned Opc =
4486         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4487     unsigned BitWidth = Op.getValueSizeInBits();
4488     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4489     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4490                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4491   }
4492   case Intrinsic::riscv_shfl:
4493   case Intrinsic::riscv_unshfl: {
4494     unsigned Opc =
4495         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4496     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4497   }
4498   case Intrinsic::riscv_bcompress:
4499   case Intrinsic::riscv_bdecompress: {
4500     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4501                                                        : RISCVISD::BDECOMPRESS;
4502     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4503   }
4504   case Intrinsic::riscv_bfp:
4505     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4506                        Op.getOperand(2));
4507   case Intrinsic::riscv_fsl:
4508     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4509                        Op.getOperand(2), Op.getOperand(3));
4510   case Intrinsic::riscv_fsr:
4511     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4512                        Op.getOperand(2), Op.getOperand(3));
4513   case Intrinsic::riscv_vmv_x_s:
4514     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4515     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4516                        Op.getOperand(1));
4517   case Intrinsic::riscv_vmv_v_x:
4518     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4519                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4520   case Intrinsic::riscv_vfmv_v_f:
4521     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4522                        Op.getOperand(1), Op.getOperand(2));
4523   case Intrinsic::riscv_vmv_s_x: {
4524     SDValue Scalar = Op.getOperand(2);
4525 
4526     if (Scalar.getValueType().bitsLE(XLenVT)) {
4527       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4528       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4529                          Op.getOperand(1), Scalar, Op.getOperand(3));
4530     }
4531 
4532     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4533 
4534     // This is an i64 value that lives in two scalar registers. We have to
4535     // insert this in a convoluted way. First we build vXi64 splat containing
4536     // the/ two values that we assemble using some bit math. Next we'll use
4537     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4538     // to merge element 0 from our splat into the source vector.
4539     // FIXME: This is probably not the best way to do this, but it is
4540     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4541     // point.
4542     //   sw lo, (a0)
4543     //   sw hi, 4(a0)
4544     //   vlse vX, (a0)
4545     //
4546     //   vid.v      vVid
4547     //   vmseq.vx   mMask, vVid, 0
4548     //   vmerge.vvm vDest, vSrc, vVal, mMask
4549     MVT VT = Op.getSimpleValueType();
4550     SDValue Vec = Op.getOperand(1);
4551     SDValue VL = getVLOperand(Op);
4552 
4553     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4554     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4555                                       DAG.getConstant(0, DL, MVT::i32), VL);
4556 
4557     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4558     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4559     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4560     SDValue SelectCond =
4561         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4562                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4563     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4564                        Vec, VL);
4565   }
4566   case Intrinsic::riscv_vslide1up:
4567   case Intrinsic::riscv_vslide1down:
4568   case Intrinsic::riscv_vslide1up_mask:
4569   case Intrinsic::riscv_vslide1down_mask: {
4570     // We need to special case these when the scalar is larger than XLen.
4571     unsigned NumOps = Op.getNumOperands();
4572     bool IsMasked = NumOps == 7;
4573     unsigned OpOffset = IsMasked ? 1 : 0;
4574     SDValue Scalar = Op.getOperand(2 + OpOffset);
4575     if (Scalar.getValueType().bitsLE(XLenVT))
4576       break;
4577 
4578     // Splatting a sign extended constant is fine.
4579     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4580       if (isInt<32>(CVal->getSExtValue()))
4581         break;
4582 
4583     MVT VT = Op.getSimpleValueType();
4584     assert(VT.getVectorElementType() == MVT::i64 &&
4585            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4586 
4587     // Convert the vector source to the equivalent nxvXi32 vector.
4588     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4589     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4590 
4591     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4592                                    DAG.getConstant(0, DL, XLenVT));
4593     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4594                                    DAG.getConstant(1, DL, XLenVT));
4595 
4596     // Double the VL since we halved SEW.
4597     SDValue VL = getVLOperand(Op);
4598     SDValue I32VL =
4599         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4600 
4601     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4602     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4603 
4604     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4605     // instructions.
4606     if (IntNo == Intrinsic::riscv_vslide1up ||
4607         IntNo == Intrinsic::riscv_vslide1up_mask) {
4608       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4609                         I32Mask, I32VL);
4610       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4611                         I32Mask, I32VL);
4612     } else {
4613       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4614                         I32Mask, I32VL);
4615       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4616                         I32Mask, I32VL);
4617     }
4618 
4619     // Convert back to nxvXi64.
4620     Vec = DAG.getBitcast(VT, Vec);
4621 
4622     if (!IsMasked)
4623       return Vec;
4624 
4625     // Apply mask after the operation.
4626     SDValue Mask = Op.getOperand(NumOps - 3);
4627     SDValue MaskedOff = Op.getOperand(1);
4628     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4629   }
4630   }
4631 
4632   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4633 }
4634 
4635 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4636                                                     SelectionDAG &DAG) const {
4637   unsigned IntNo = Op.getConstantOperandVal(1);
4638   switch (IntNo) {
4639   default:
4640     break;
4641   case Intrinsic::riscv_masked_strided_load: {
4642     SDLoc DL(Op);
4643     MVT XLenVT = Subtarget.getXLenVT();
4644 
4645     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4646     // the selection of the masked intrinsics doesn't do this for us.
4647     SDValue Mask = Op.getOperand(5);
4648     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4649 
4650     MVT VT = Op->getSimpleValueType(0);
4651     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4652 
4653     SDValue PassThru = Op.getOperand(2);
4654     if (!IsUnmasked) {
4655       MVT MaskVT =
4656           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4657       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4658       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4659     }
4660 
4661     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4662 
4663     SDValue IntID = DAG.getTargetConstant(
4664         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4665         XLenVT);
4666 
4667     auto *Load = cast<MemIntrinsicSDNode>(Op);
4668     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4669     if (IsUnmasked)
4670       Ops.push_back(DAG.getUNDEF(ContainerVT));
4671     else
4672       Ops.push_back(PassThru);
4673     Ops.push_back(Op.getOperand(3)); // Ptr
4674     Ops.push_back(Op.getOperand(4)); // Stride
4675     if (!IsUnmasked)
4676       Ops.push_back(Mask);
4677     Ops.push_back(VL);
4678     if (!IsUnmasked) {
4679       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4680       Ops.push_back(Policy);
4681     }
4682 
4683     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4684     SDValue Result =
4685         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4686                                 Load->getMemoryVT(), Load->getMemOperand());
4687     SDValue Chain = Result.getValue(1);
4688     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4689     return DAG.getMergeValues({Result, Chain}, DL);
4690   }
4691   }
4692 
4693   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4694 }
4695 
4696 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4697                                                  SelectionDAG &DAG) const {
4698   unsigned IntNo = Op.getConstantOperandVal(1);
4699   switch (IntNo) {
4700   default:
4701     break;
4702   case Intrinsic::riscv_masked_strided_store: {
4703     SDLoc DL(Op);
4704     MVT XLenVT = Subtarget.getXLenVT();
4705 
4706     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4707     // the selection of the masked intrinsics doesn't do this for us.
4708     SDValue Mask = Op.getOperand(5);
4709     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4710 
4711     SDValue Val = Op.getOperand(2);
4712     MVT VT = Val.getSimpleValueType();
4713     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4714 
4715     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4716     if (!IsUnmasked) {
4717       MVT MaskVT =
4718           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4719       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4720     }
4721 
4722     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4723 
4724     SDValue IntID = DAG.getTargetConstant(
4725         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4726         XLenVT);
4727 
4728     auto *Store = cast<MemIntrinsicSDNode>(Op);
4729     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4730     Ops.push_back(Val);
4731     Ops.push_back(Op.getOperand(3)); // Ptr
4732     Ops.push_back(Op.getOperand(4)); // Stride
4733     if (!IsUnmasked)
4734       Ops.push_back(Mask);
4735     Ops.push_back(VL);
4736 
4737     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4738                                    Ops, Store->getMemoryVT(),
4739                                    Store->getMemOperand());
4740   }
4741   }
4742 
4743   return SDValue();
4744 }
4745 
4746 static MVT getLMUL1VT(MVT VT) {
4747   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4748          "Unexpected vector MVT");
4749   return MVT::getScalableVectorVT(
4750       VT.getVectorElementType(),
4751       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4752 }
4753 
4754 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4755   switch (ISDOpcode) {
4756   default:
4757     llvm_unreachable("Unhandled reduction");
4758   case ISD::VECREDUCE_ADD:
4759     return RISCVISD::VECREDUCE_ADD_VL;
4760   case ISD::VECREDUCE_UMAX:
4761     return RISCVISD::VECREDUCE_UMAX_VL;
4762   case ISD::VECREDUCE_SMAX:
4763     return RISCVISD::VECREDUCE_SMAX_VL;
4764   case ISD::VECREDUCE_UMIN:
4765     return RISCVISD::VECREDUCE_UMIN_VL;
4766   case ISD::VECREDUCE_SMIN:
4767     return RISCVISD::VECREDUCE_SMIN_VL;
4768   case ISD::VECREDUCE_AND:
4769     return RISCVISD::VECREDUCE_AND_VL;
4770   case ISD::VECREDUCE_OR:
4771     return RISCVISD::VECREDUCE_OR_VL;
4772   case ISD::VECREDUCE_XOR:
4773     return RISCVISD::VECREDUCE_XOR_VL;
4774   }
4775 }
4776 
4777 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4778                                                          SelectionDAG &DAG,
4779                                                          bool IsVP) const {
4780   SDLoc DL(Op);
4781   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4782   MVT VecVT = Vec.getSimpleValueType();
4783   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4784           Op.getOpcode() == ISD::VECREDUCE_OR ||
4785           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4786           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4787           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4788           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4789          "Unexpected reduction lowering");
4790 
4791   MVT XLenVT = Subtarget.getXLenVT();
4792   assert(Op.getValueType() == XLenVT &&
4793          "Expected reduction output to be legalized to XLenVT");
4794 
4795   MVT ContainerVT = VecVT;
4796   if (VecVT.isFixedLengthVector()) {
4797     ContainerVT = getContainerForFixedLengthVector(VecVT);
4798     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4799   }
4800 
4801   SDValue Mask, VL;
4802   if (IsVP) {
4803     Mask = Op.getOperand(2);
4804     VL = Op.getOperand(3);
4805   } else {
4806     std::tie(Mask, VL) =
4807         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4808   }
4809 
4810   unsigned BaseOpc;
4811   ISD::CondCode CC;
4812   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4813 
4814   switch (Op.getOpcode()) {
4815   default:
4816     llvm_unreachable("Unhandled reduction");
4817   case ISD::VECREDUCE_AND:
4818   case ISD::VP_REDUCE_AND: {
4819     // vcpop ~x == 0
4820     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4821     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4822     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4823     CC = ISD::SETEQ;
4824     BaseOpc = ISD::AND;
4825     break;
4826   }
4827   case ISD::VECREDUCE_OR:
4828   case ISD::VP_REDUCE_OR:
4829     // vcpop x != 0
4830     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4831     CC = ISD::SETNE;
4832     BaseOpc = ISD::OR;
4833     break;
4834   case ISD::VECREDUCE_XOR:
4835   case ISD::VP_REDUCE_XOR: {
4836     // ((vcpop x) & 1) != 0
4837     SDValue One = DAG.getConstant(1, DL, XLenVT);
4838     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4839     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4840     CC = ISD::SETNE;
4841     BaseOpc = ISD::XOR;
4842     break;
4843   }
4844   }
4845 
4846   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4847 
4848   if (!IsVP)
4849     return SetCC;
4850 
4851   // Now include the start value in the operation.
4852   // Note that we must return the start value when no elements are operated
4853   // upon. The vcpop instructions we've emitted in each case above will return
4854   // 0 for an inactive vector, and so we've already received the neutral value:
4855   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4856   // can simply include the start value.
4857   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4858 }
4859 
4860 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4861                                             SelectionDAG &DAG) const {
4862   SDLoc DL(Op);
4863   SDValue Vec = Op.getOperand(0);
4864   EVT VecEVT = Vec.getValueType();
4865 
4866   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4867 
4868   // Due to ordering in legalize types we may have a vector type that needs to
4869   // be split. Do that manually so we can get down to a legal type.
4870   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4871          TargetLowering::TypeSplitVector) {
4872     SDValue Lo, Hi;
4873     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4874     VecEVT = Lo.getValueType();
4875     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4876   }
4877 
4878   // TODO: The type may need to be widened rather than split. Or widened before
4879   // it can be split.
4880   if (!isTypeLegal(VecEVT))
4881     return SDValue();
4882 
4883   MVT VecVT = VecEVT.getSimpleVT();
4884   MVT VecEltVT = VecVT.getVectorElementType();
4885   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4886 
4887   MVT ContainerVT = VecVT;
4888   if (VecVT.isFixedLengthVector()) {
4889     ContainerVT = getContainerForFixedLengthVector(VecVT);
4890     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4891   }
4892 
4893   MVT M1VT = getLMUL1VT(ContainerVT);
4894   MVT XLenVT = Subtarget.getXLenVT();
4895 
4896   SDValue Mask, VL;
4897   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4898 
4899   SDValue NeutralElem =
4900       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4901   SDValue IdentitySplat = lowerScalarSplat(
4902       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4903   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4904                                   IdentitySplat, Mask, VL);
4905   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4906                              DAG.getConstant(0, DL, XLenVT));
4907   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4908 }
4909 
4910 // Given a reduction op, this function returns the matching reduction opcode,
4911 // the vector SDValue and the scalar SDValue required to lower this to a
4912 // RISCVISD node.
4913 static std::tuple<unsigned, SDValue, SDValue>
4914 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4915   SDLoc DL(Op);
4916   auto Flags = Op->getFlags();
4917   unsigned Opcode = Op.getOpcode();
4918   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4919   switch (Opcode) {
4920   default:
4921     llvm_unreachable("Unhandled reduction");
4922   case ISD::VECREDUCE_FADD: {
4923     // Use positive zero if we can. It is cheaper to materialize.
4924     SDValue Zero =
4925         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4926     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4927   }
4928   case ISD::VECREDUCE_SEQ_FADD:
4929     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4930                            Op.getOperand(0));
4931   case ISD::VECREDUCE_FMIN:
4932     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4933                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4934   case ISD::VECREDUCE_FMAX:
4935     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4936                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4937   }
4938 }
4939 
4940 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4941                                               SelectionDAG &DAG) const {
4942   SDLoc DL(Op);
4943   MVT VecEltVT = Op.getSimpleValueType();
4944 
4945   unsigned RVVOpcode;
4946   SDValue VectorVal, ScalarVal;
4947   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4948       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4949   MVT VecVT = VectorVal.getSimpleValueType();
4950 
4951   MVT ContainerVT = VecVT;
4952   if (VecVT.isFixedLengthVector()) {
4953     ContainerVT = getContainerForFixedLengthVector(VecVT);
4954     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4955   }
4956 
4957   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4958   MVT XLenVT = Subtarget.getXLenVT();
4959 
4960   SDValue Mask, VL;
4961   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4962 
4963   SDValue ScalarSplat = lowerScalarSplat(
4964       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4965   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4966                                   VectorVal, ScalarSplat, Mask, VL);
4967   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4968                      DAG.getConstant(0, DL, XLenVT));
4969 }
4970 
4971 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4972   switch (ISDOpcode) {
4973   default:
4974     llvm_unreachable("Unhandled reduction");
4975   case ISD::VP_REDUCE_ADD:
4976     return RISCVISD::VECREDUCE_ADD_VL;
4977   case ISD::VP_REDUCE_UMAX:
4978     return RISCVISD::VECREDUCE_UMAX_VL;
4979   case ISD::VP_REDUCE_SMAX:
4980     return RISCVISD::VECREDUCE_SMAX_VL;
4981   case ISD::VP_REDUCE_UMIN:
4982     return RISCVISD::VECREDUCE_UMIN_VL;
4983   case ISD::VP_REDUCE_SMIN:
4984     return RISCVISD::VECREDUCE_SMIN_VL;
4985   case ISD::VP_REDUCE_AND:
4986     return RISCVISD::VECREDUCE_AND_VL;
4987   case ISD::VP_REDUCE_OR:
4988     return RISCVISD::VECREDUCE_OR_VL;
4989   case ISD::VP_REDUCE_XOR:
4990     return RISCVISD::VECREDUCE_XOR_VL;
4991   case ISD::VP_REDUCE_FADD:
4992     return RISCVISD::VECREDUCE_FADD_VL;
4993   case ISD::VP_REDUCE_SEQ_FADD:
4994     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4995   case ISD::VP_REDUCE_FMAX:
4996     return RISCVISD::VECREDUCE_FMAX_VL;
4997   case ISD::VP_REDUCE_FMIN:
4998     return RISCVISD::VECREDUCE_FMIN_VL;
4999   }
5000 }
5001 
5002 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5003                                            SelectionDAG &DAG) const {
5004   SDLoc DL(Op);
5005   SDValue Vec = Op.getOperand(1);
5006   EVT VecEVT = Vec.getValueType();
5007 
5008   // TODO: The type may need to be widened rather than split. Or widened before
5009   // it can be split.
5010   if (!isTypeLegal(VecEVT))
5011     return SDValue();
5012 
5013   MVT VecVT = VecEVT.getSimpleVT();
5014   MVT VecEltVT = VecVT.getVectorElementType();
5015   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5016 
5017   MVT ContainerVT = VecVT;
5018   if (VecVT.isFixedLengthVector()) {
5019     ContainerVT = getContainerForFixedLengthVector(VecVT);
5020     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5021   }
5022 
5023   SDValue VL = Op.getOperand(3);
5024   SDValue Mask = Op.getOperand(2);
5025 
5026   MVT M1VT = getLMUL1VT(ContainerVT);
5027   MVT XLenVT = Subtarget.getXLenVT();
5028   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5029 
5030   SDValue StartSplat =
5031       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
5032                        DL, DAG, Subtarget);
5033   SDValue Reduction =
5034       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5035   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5036                              DAG.getConstant(0, DL, XLenVT));
5037   if (!VecVT.isInteger())
5038     return Elt0;
5039   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5040 }
5041 
5042 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5043                                                    SelectionDAG &DAG) const {
5044   SDValue Vec = Op.getOperand(0);
5045   SDValue SubVec = Op.getOperand(1);
5046   MVT VecVT = Vec.getSimpleValueType();
5047   MVT SubVecVT = SubVec.getSimpleValueType();
5048 
5049   SDLoc DL(Op);
5050   MVT XLenVT = Subtarget.getXLenVT();
5051   unsigned OrigIdx = Op.getConstantOperandVal(2);
5052   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5053 
5054   // We don't have the ability to slide mask vectors up indexed by their i1
5055   // elements; the smallest we can do is i8. Often we are able to bitcast to
5056   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5057   // into a scalable one, we might not necessarily have enough scalable
5058   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5059   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5060       (OrigIdx != 0 || !Vec.isUndef())) {
5061     if (VecVT.getVectorMinNumElements() >= 8 &&
5062         SubVecVT.getVectorMinNumElements() >= 8) {
5063       assert(OrigIdx % 8 == 0 && "Invalid index");
5064       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5065              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5066              "Unexpected mask vector lowering");
5067       OrigIdx /= 8;
5068       SubVecVT =
5069           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5070                            SubVecVT.isScalableVector());
5071       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5072                                VecVT.isScalableVector());
5073       Vec = DAG.getBitcast(VecVT, Vec);
5074       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5075     } else {
5076       // We can't slide this mask vector up indexed by its i1 elements.
5077       // This poses a problem when we wish to insert a scalable vector which
5078       // can't be re-expressed as a larger type. Just choose the slow path and
5079       // extend to a larger type, then truncate back down.
5080       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5081       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5082       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5083       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5084       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5085                         Op.getOperand(2));
5086       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5087       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5088     }
5089   }
5090 
5091   // If the subvector vector is a fixed-length type, we cannot use subregister
5092   // manipulation to simplify the codegen; we don't know which register of a
5093   // LMUL group contains the specific subvector as we only know the minimum
5094   // register size. Therefore we must slide the vector group up the full
5095   // amount.
5096   if (SubVecVT.isFixedLengthVector()) {
5097     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5098       return Op;
5099     MVT ContainerVT = VecVT;
5100     if (VecVT.isFixedLengthVector()) {
5101       ContainerVT = getContainerForFixedLengthVector(VecVT);
5102       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5103     }
5104     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5105                          DAG.getUNDEF(ContainerVT), SubVec,
5106                          DAG.getConstant(0, DL, XLenVT));
5107     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5108       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5109       return DAG.getBitcast(Op.getValueType(), SubVec);
5110     }
5111     SDValue Mask =
5112         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5113     // Set the vector length to only the number of elements we care about. Note
5114     // that for slideup this includes the offset.
5115     SDValue VL =
5116         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5117     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5118     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5119                                   SubVec, SlideupAmt, Mask, VL);
5120     if (VecVT.isFixedLengthVector())
5121       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5122     return DAG.getBitcast(Op.getValueType(), Slideup);
5123   }
5124 
5125   unsigned SubRegIdx, RemIdx;
5126   std::tie(SubRegIdx, RemIdx) =
5127       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5128           VecVT, SubVecVT, OrigIdx, TRI);
5129 
5130   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5131   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5132                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5133                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5134 
5135   // 1. If the Idx has been completely eliminated and this subvector's size is
5136   // a vector register or a multiple thereof, or the surrounding elements are
5137   // undef, then this is a subvector insert which naturally aligns to a vector
5138   // register. These can easily be handled using subregister manipulation.
5139   // 2. If the subvector is smaller than a vector register, then the insertion
5140   // must preserve the undisturbed elements of the register. We do this by
5141   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5142   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5143   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5144   // LMUL=1 type back into the larger vector (resolving to another subregister
5145   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5146   // to avoid allocating a large register group to hold our subvector.
5147   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5148     return Op;
5149 
5150   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5151   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5152   // (in our case undisturbed). This means we can set up a subvector insertion
5153   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5154   // size of the subvector.
5155   MVT InterSubVT = VecVT;
5156   SDValue AlignedExtract = Vec;
5157   unsigned AlignedIdx = OrigIdx - RemIdx;
5158   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5159     InterSubVT = getLMUL1VT(VecVT);
5160     // Extract a subvector equal to the nearest full vector register type. This
5161     // should resolve to a EXTRACT_SUBREG instruction.
5162     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5163                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5164   }
5165 
5166   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5167   // For scalable vectors this must be further multiplied by vscale.
5168   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5169 
5170   SDValue Mask, VL;
5171   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5172 
5173   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5174   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5175   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5176   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5177 
5178   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5179                        DAG.getUNDEF(InterSubVT), SubVec,
5180                        DAG.getConstant(0, DL, XLenVT));
5181 
5182   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5183                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5184 
5185   // If required, insert this subvector back into the correct vector register.
5186   // This should resolve to an INSERT_SUBREG instruction.
5187   if (VecVT.bitsGT(InterSubVT))
5188     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5189                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5190 
5191   // We might have bitcast from a mask type: cast back to the original type if
5192   // required.
5193   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5194 }
5195 
5196 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5197                                                     SelectionDAG &DAG) const {
5198   SDValue Vec = Op.getOperand(0);
5199   MVT SubVecVT = Op.getSimpleValueType();
5200   MVT VecVT = Vec.getSimpleValueType();
5201 
5202   SDLoc DL(Op);
5203   MVT XLenVT = Subtarget.getXLenVT();
5204   unsigned OrigIdx = Op.getConstantOperandVal(1);
5205   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5206 
5207   // We don't have the ability to slide mask vectors down indexed by their i1
5208   // elements; the smallest we can do is i8. Often we are able to bitcast to
5209   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5210   // from a scalable one, we might not necessarily have enough scalable
5211   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5212   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5213     if (VecVT.getVectorMinNumElements() >= 8 &&
5214         SubVecVT.getVectorMinNumElements() >= 8) {
5215       assert(OrigIdx % 8 == 0 && "Invalid index");
5216       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5217              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5218              "Unexpected mask vector lowering");
5219       OrigIdx /= 8;
5220       SubVecVT =
5221           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5222                            SubVecVT.isScalableVector());
5223       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5224                                VecVT.isScalableVector());
5225       Vec = DAG.getBitcast(VecVT, Vec);
5226     } else {
5227       // We can't slide this mask vector down, indexed by its i1 elements.
5228       // This poses a problem when we wish to extract a scalable vector which
5229       // can't be re-expressed as a larger type. Just choose the slow path and
5230       // extend to a larger type, then truncate back down.
5231       // TODO: We could probably improve this when extracting certain fixed
5232       // from fixed, where we can extract as i8 and shift the correct element
5233       // right to reach the desired subvector?
5234       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5235       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5236       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5237       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5238                         Op.getOperand(1));
5239       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5240       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5241     }
5242   }
5243 
5244   // If the subvector vector is a fixed-length type, we cannot use subregister
5245   // manipulation to simplify the codegen; we don't know which register of a
5246   // LMUL group contains the specific subvector as we only know the minimum
5247   // register size. Therefore we must slide the vector group down the full
5248   // amount.
5249   if (SubVecVT.isFixedLengthVector()) {
5250     // With an index of 0 this is a cast-like subvector, which can be performed
5251     // with subregister operations.
5252     if (OrigIdx == 0)
5253       return Op;
5254     MVT ContainerVT = VecVT;
5255     if (VecVT.isFixedLengthVector()) {
5256       ContainerVT = getContainerForFixedLengthVector(VecVT);
5257       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5258     }
5259     SDValue Mask =
5260         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5261     // Set the vector length to only the number of elements we care about. This
5262     // avoids sliding down elements we're going to discard straight away.
5263     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5264     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5265     SDValue Slidedown =
5266         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5267                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5268     // Now we can use a cast-like subvector extract to get the result.
5269     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5270                             DAG.getConstant(0, DL, XLenVT));
5271     return DAG.getBitcast(Op.getValueType(), Slidedown);
5272   }
5273 
5274   unsigned SubRegIdx, RemIdx;
5275   std::tie(SubRegIdx, RemIdx) =
5276       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5277           VecVT, SubVecVT, OrigIdx, TRI);
5278 
5279   // If the Idx has been completely eliminated then this is a subvector extract
5280   // which naturally aligns to a vector register. These can easily be handled
5281   // using subregister manipulation.
5282   if (RemIdx == 0)
5283     return Op;
5284 
5285   // Else we must shift our vector register directly to extract the subvector.
5286   // Do this using VSLIDEDOWN.
5287 
5288   // If the vector type is an LMUL-group type, extract a subvector equal to the
5289   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5290   // instruction.
5291   MVT InterSubVT = VecVT;
5292   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5293     InterSubVT = getLMUL1VT(VecVT);
5294     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5295                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5296   }
5297 
5298   // Slide this vector register down by the desired number of elements in order
5299   // to place the desired subvector starting at element 0.
5300   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5301   // For scalable vectors this must be further multiplied by vscale.
5302   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5303 
5304   SDValue Mask, VL;
5305   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5306   SDValue Slidedown =
5307       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5308                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5309 
5310   // Now the vector is in the right position, extract our final subvector. This
5311   // should resolve to a COPY.
5312   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5313                           DAG.getConstant(0, DL, XLenVT));
5314 
5315   // We might have bitcast from a mask type: cast back to the original type if
5316   // required.
5317   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5318 }
5319 
5320 // Lower step_vector to the vid instruction. Any non-identity step value must
5321 // be accounted for my manual expansion.
5322 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5323                                               SelectionDAG &DAG) const {
5324   SDLoc DL(Op);
5325   MVT VT = Op.getSimpleValueType();
5326   MVT XLenVT = Subtarget.getXLenVT();
5327   SDValue Mask, VL;
5328   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5329   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5330   uint64_t StepValImm = Op.getConstantOperandVal(0);
5331   if (StepValImm != 1) {
5332     if (isPowerOf2_64(StepValImm)) {
5333       SDValue StepVal =
5334           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5335                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5336       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5337     } else {
5338       SDValue StepVal = lowerScalarSplat(
5339           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5340           DL, DAG, Subtarget);
5341       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5342     }
5343   }
5344   return StepVec;
5345 }
5346 
5347 // Implement vector_reverse using vrgather.vv with indices determined by
5348 // subtracting the id of each element from (VLMAX-1). This will convert
5349 // the indices like so:
5350 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5351 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5352 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5353                                                  SelectionDAG &DAG) const {
5354   SDLoc DL(Op);
5355   MVT VecVT = Op.getSimpleValueType();
5356   unsigned EltSize = VecVT.getScalarSizeInBits();
5357   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5358 
5359   unsigned MaxVLMAX = 0;
5360   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5361   if (VectorBitsMax != 0)
5362     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5363 
5364   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5365   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5366 
5367   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5368   // to use vrgatherei16.vv.
5369   // TODO: It's also possible to use vrgatherei16.vv for other types to
5370   // decrease register width for the index calculation.
5371   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5372     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5373     // Reverse each half, then reassemble them in reverse order.
5374     // NOTE: It's also possible that after splitting that VLMAX no longer
5375     // requires vrgatherei16.vv.
5376     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5377       SDValue Lo, Hi;
5378       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5379       EVT LoVT, HiVT;
5380       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5381       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5382       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5383       // Reassemble the low and high pieces reversed.
5384       // FIXME: This is a CONCAT_VECTORS.
5385       SDValue Res =
5386           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5387                       DAG.getIntPtrConstant(0, DL));
5388       return DAG.getNode(
5389           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5390           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5391     }
5392 
5393     // Just promote the int type to i16 which will double the LMUL.
5394     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5395     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5396   }
5397 
5398   MVT XLenVT = Subtarget.getXLenVT();
5399   SDValue Mask, VL;
5400   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5401 
5402   // Calculate VLMAX-1 for the desired SEW.
5403   unsigned MinElts = VecVT.getVectorMinNumElements();
5404   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5405                               DAG.getConstant(MinElts, DL, XLenVT));
5406   SDValue VLMinus1 =
5407       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5408 
5409   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5410   bool IsRV32E64 =
5411       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5412   SDValue SplatVL;
5413   if (!IsRV32E64)
5414     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5415   else
5416     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5417 
5418   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5419   SDValue Indices =
5420       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5421 
5422   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5423 }
5424 
5425 SDValue
5426 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5427                                                      SelectionDAG &DAG) const {
5428   SDLoc DL(Op);
5429   auto *Load = cast<LoadSDNode>(Op);
5430 
5431   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5432                                         Load->getMemoryVT(),
5433                                         *Load->getMemOperand()) &&
5434          "Expecting a correctly-aligned load");
5435 
5436   MVT VT = Op.getSimpleValueType();
5437   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5438 
5439   SDValue VL =
5440       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5441 
5442   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5443   SDValue NewLoad = DAG.getMemIntrinsicNode(
5444       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5445       Load->getMemoryVT(), Load->getMemOperand());
5446 
5447   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5448   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5449 }
5450 
5451 SDValue
5452 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5453                                                       SelectionDAG &DAG) const {
5454   SDLoc DL(Op);
5455   auto *Store = cast<StoreSDNode>(Op);
5456 
5457   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5458                                         Store->getMemoryVT(),
5459                                         *Store->getMemOperand()) &&
5460          "Expecting a correctly-aligned store");
5461 
5462   SDValue StoreVal = Store->getValue();
5463   MVT VT = StoreVal.getSimpleValueType();
5464 
5465   // If the size less than a byte, we need to pad with zeros to make a byte.
5466   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5467     VT = MVT::v8i1;
5468     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5469                            DAG.getConstant(0, DL, VT), StoreVal,
5470                            DAG.getIntPtrConstant(0, DL));
5471   }
5472 
5473   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5474 
5475   SDValue VL =
5476       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5477 
5478   SDValue NewValue =
5479       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5480   return DAG.getMemIntrinsicNode(
5481       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5482       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5483       Store->getMemoryVT(), Store->getMemOperand());
5484 }
5485 
5486 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5487                                              SelectionDAG &DAG) const {
5488   SDLoc DL(Op);
5489   MVT VT = Op.getSimpleValueType();
5490 
5491   const auto *MemSD = cast<MemSDNode>(Op);
5492   EVT MemVT = MemSD->getMemoryVT();
5493   MachineMemOperand *MMO = MemSD->getMemOperand();
5494   SDValue Chain = MemSD->getChain();
5495   SDValue BasePtr = MemSD->getBasePtr();
5496 
5497   SDValue Mask, PassThru, VL;
5498   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5499     Mask = VPLoad->getMask();
5500     PassThru = DAG.getUNDEF(VT);
5501     VL = VPLoad->getVectorLength();
5502   } else {
5503     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5504     Mask = MLoad->getMask();
5505     PassThru = MLoad->getPassThru();
5506   }
5507 
5508   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5509 
5510   MVT XLenVT = Subtarget.getXLenVT();
5511 
5512   MVT ContainerVT = VT;
5513   if (VT.isFixedLengthVector()) {
5514     ContainerVT = getContainerForFixedLengthVector(VT);
5515     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5516     if (!IsUnmasked) {
5517       MVT MaskVT =
5518           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5519       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5520     }
5521   }
5522 
5523   if (!VL)
5524     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5525 
5526   unsigned IntID =
5527       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5528   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5529   if (IsUnmasked)
5530     Ops.push_back(DAG.getUNDEF(ContainerVT));
5531   else
5532     Ops.push_back(PassThru);
5533   Ops.push_back(BasePtr);
5534   if (!IsUnmasked)
5535     Ops.push_back(Mask);
5536   Ops.push_back(VL);
5537   if (!IsUnmasked)
5538     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5539 
5540   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5541 
5542   SDValue Result =
5543       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5544   Chain = Result.getValue(1);
5545 
5546   if (VT.isFixedLengthVector())
5547     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5548 
5549   return DAG.getMergeValues({Result, Chain}, DL);
5550 }
5551 
5552 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5553                                               SelectionDAG &DAG) const {
5554   SDLoc DL(Op);
5555 
5556   const auto *MemSD = cast<MemSDNode>(Op);
5557   EVT MemVT = MemSD->getMemoryVT();
5558   MachineMemOperand *MMO = MemSD->getMemOperand();
5559   SDValue Chain = MemSD->getChain();
5560   SDValue BasePtr = MemSD->getBasePtr();
5561   SDValue Val, Mask, VL;
5562 
5563   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5564     Val = VPStore->getValue();
5565     Mask = VPStore->getMask();
5566     VL = VPStore->getVectorLength();
5567   } else {
5568     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5569     Val = MStore->getValue();
5570     Mask = MStore->getMask();
5571   }
5572 
5573   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5574 
5575   MVT VT = Val.getSimpleValueType();
5576   MVT XLenVT = Subtarget.getXLenVT();
5577 
5578   MVT ContainerVT = VT;
5579   if (VT.isFixedLengthVector()) {
5580     ContainerVT = getContainerForFixedLengthVector(VT);
5581 
5582     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5583     if (!IsUnmasked) {
5584       MVT MaskVT =
5585           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5586       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5587     }
5588   }
5589 
5590   if (!VL)
5591     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5592 
5593   unsigned IntID =
5594       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5595   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5596   Ops.push_back(Val);
5597   Ops.push_back(BasePtr);
5598   if (!IsUnmasked)
5599     Ops.push_back(Mask);
5600   Ops.push_back(VL);
5601 
5602   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5603                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5604 }
5605 
5606 SDValue
5607 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5608                                                       SelectionDAG &DAG) const {
5609   MVT InVT = Op.getOperand(0).getSimpleValueType();
5610   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5611 
5612   MVT VT = Op.getSimpleValueType();
5613 
5614   SDValue Op1 =
5615       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5616   SDValue Op2 =
5617       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5618 
5619   SDLoc DL(Op);
5620   SDValue VL =
5621       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5622 
5623   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5624   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5625 
5626   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5627                             Op.getOperand(2), Mask, VL);
5628 
5629   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5630 }
5631 
5632 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5633     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5634   MVT VT = Op.getSimpleValueType();
5635 
5636   if (VT.getVectorElementType() == MVT::i1)
5637     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5638 
5639   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5640 }
5641 
5642 SDValue
5643 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5644                                                       SelectionDAG &DAG) const {
5645   unsigned Opc;
5646   switch (Op.getOpcode()) {
5647   default: llvm_unreachable("Unexpected opcode!");
5648   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5649   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5650   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5651   }
5652 
5653   return lowerToScalableOp(Op, DAG, Opc);
5654 }
5655 
5656 // Lower vector ABS to smax(X, sub(0, X)).
5657 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5658   SDLoc DL(Op);
5659   MVT VT = Op.getSimpleValueType();
5660   SDValue X = Op.getOperand(0);
5661 
5662   assert(VT.isFixedLengthVector() && "Unexpected type");
5663 
5664   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5665   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5666 
5667   SDValue Mask, VL;
5668   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5669 
5670   SDValue SplatZero =
5671       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5672                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5673   SDValue NegX =
5674       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5675   SDValue Max =
5676       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5677 
5678   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5679 }
5680 
5681 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5682     SDValue Op, SelectionDAG &DAG) const {
5683   SDLoc DL(Op);
5684   MVT VT = Op.getSimpleValueType();
5685   SDValue Mag = Op.getOperand(0);
5686   SDValue Sign = Op.getOperand(1);
5687   assert(Mag.getValueType() == Sign.getValueType() &&
5688          "Can only handle COPYSIGN with matching types.");
5689 
5690   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5691   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5692   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5693 
5694   SDValue Mask, VL;
5695   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5696 
5697   SDValue CopySign =
5698       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5699 
5700   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5701 }
5702 
5703 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5704     SDValue Op, SelectionDAG &DAG) const {
5705   MVT VT = Op.getSimpleValueType();
5706   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5707 
5708   MVT I1ContainerVT =
5709       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5710 
5711   SDValue CC =
5712       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5713   SDValue Op1 =
5714       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5715   SDValue Op2 =
5716       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5717 
5718   SDLoc DL(Op);
5719   SDValue Mask, VL;
5720   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5721 
5722   SDValue Select =
5723       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5724 
5725   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5726 }
5727 
5728 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5729                                                unsigned NewOpc,
5730                                                bool HasMask) const {
5731   MVT VT = Op.getSimpleValueType();
5732   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5733 
5734   // Create list of operands by converting existing ones to scalable types.
5735   SmallVector<SDValue, 6> Ops;
5736   for (const SDValue &V : Op->op_values()) {
5737     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5738 
5739     // Pass through non-vector operands.
5740     if (!V.getValueType().isVector()) {
5741       Ops.push_back(V);
5742       continue;
5743     }
5744 
5745     // "cast" fixed length vector to a scalable vector.
5746     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5747            "Only fixed length vectors are supported!");
5748     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5749   }
5750 
5751   SDLoc DL(Op);
5752   SDValue Mask, VL;
5753   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5754   if (HasMask)
5755     Ops.push_back(Mask);
5756   Ops.push_back(VL);
5757 
5758   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5759   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5760 }
5761 
5762 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5763 // * Operands of each node are assumed to be in the same order.
5764 // * The EVL operand is promoted from i32 to i64 on RV64.
5765 // * Fixed-length vectors are converted to their scalable-vector container
5766 //   types.
5767 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5768                                        unsigned RISCVISDOpc) const {
5769   SDLoc DL(Op);
5770   MVT VT = Op.getSimpleValueType();
5771   SmallVector<SDValue, 4> Ops;
5772 
5773   for (const auto &OpIdx : enumerate(Op->ops())) {
5774     SDValue V = OpIdx.value();
5775     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5776     // Pass through operands which aren't fixed-length vectors.
5777     if (!V.getValueType().isFixedLengthVector()) {
5778       Ops.push_back(V);
5779       continue;
5780     }
5781     // "cast" fixed length vector to a scalable vector.
5782     MVT OpVT = V.getSimpleValueType();
5783     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5784     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5785            "Only fixed length vectors are supported!");
5786     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5787   }
5788 
5789   if (!VT.isFixedLengthVector())
5790     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5791 
5792   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5793 
5794   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5795 
5796   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5797 }
5798 
5799 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5800                                             unsigned MaskOpc,
5801                                             unsigned VecOpc) const {
5802   MVT VT = Op.getSimpleValueType();
5803   if (VT.getVectorElementType() != MVT::i1)
5804     return lowerVPOp(Op, DAG, VecOpc);
5805 
5806   // It is safe to drop mask parameter as masked-off elements are undef.
5807   SDValue Op1 = Op->getOperand(0);
5808   SDValue Op2 = Op->getOperand(1);
5809   SDValue VL = Op->getOperand(3);
5810 
5811   MVT ContainerVT = VT;
5812   const bool IsFixed = VT.isFixedLengthVector();
5813   if (IsFixed) {
5814     ContainerVT = getContainerForFixedLengthVector(VT);
5815     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5816     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5817   }
5818 
5819   SDLoc DL(Op);
5820   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5821   if (!IsFixed)
5822     return Val;
5823   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5824 }
5825 
5826 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5827 // matched to a RVV indexed load. The RVV indexed load instructions only
5828 // support the "unsigned unscaled" addressing mode; indices are implicitly
5829 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5830 // signed or scaled indexing is extended to the XLEN value type and scaled
5831 // accordingly.
5832 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5833                                                SelectionDAG &DAG) const {
5834   SDLoc DL(Op);
5835   MVT VT = Op.getSimpleValueType();
5836 
5837   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5838   EVT MemVT = MemSD->getMemoryVT();
5839   MachineMemOperand *MMO = MemSD->getMemOperand();
5840   SDValue Chain = MemSD->getChain();
5841   SDValue BasePtr = MemSD->getBasePtr();
5842 
5843   ISD::LoadExtType LoadExtType;
5844   SDValue Index, Mask, PassThru, VL;
5845 
5846   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5847     Index = VPGN->getIndex();
5848     Mask = VPGN->getMask();
5849     PassThru = DAG.getUNDEF(VT);
5850     VL = VPGN->getVectorLength();
5851     // VP doesn't support extending loads.
5852     LoadExtType = ISD::NON_EXTLOAD;
5853   } else {
5854     // Else it must be a MGATHER.
5855     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5856     Index = MGN->getIndex();
5857     Mask = MGN->getMask();
5858     PassThru = MGN->getPassThru();
5859     LoadExtType = MGN->getExtensionType();
5860   }
5861 
5862   MVT IndexVT = Index.getSimpleValueType();
5863   MVT XLenVT = Subtarget.getXLenVT();
5864 
5865   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5866          "Unexpected VTs!");
5867   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5868   // Targets have to explicitly opt-in for extending vector loads.
5869   assert(LoadExtType == ISD::NON_EXTLOAD &&
5870          "Unexpected extending MGATHER/VP_GATHER");
5871   (void)LoadExtType;
5872 
5873   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5874   // the selection of the masked intrinsics doesn't do this for us.
5875   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5876 
5877   MVT ContainerVT = VT;
5878   if (VT.isFixedLengthVector()) {
5879     // We need to use the larger of the result and index type to determine the
5880     // scalable type to use so we don't increase LMUL for any operand/result.
5881     if (VT.bitsGE(IndexVT)) {
5882       ContainerVT = getContainerForFixedLengthVector(VT);
5883       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5884                                  ContainerVT.getVectorElementCount());
5885     } else {
5886       IndexVT = getContainerForFixedLengthVector(IndexVT);
5887       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5888                                      IndexVT.getVectorElementCount());
5889     }
5890 
5891     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5892 
5893     if (!IsUnmasked) {
5894       MVT MaskVT =
5895           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5896       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5897       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5898     }
5899   }
5900 
5901   if (!VL)
5902     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5903 
5904   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5905     IndexVT = IndexVT.changeVectorElementType(XLenVT);
5906     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
5907                                    VL);
5908     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
5909                         TrueMask, VL);
5910   }
5911 
5912   unsigned IntID =
5913       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5914   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5915   if (IsUnmasked)
5916     Ops.push_back(DAG.getUNDEF(ContainerVT));
5917   else
5918     Ops.push_back(PassThru);
5919   Ops.push_back(BasePtr);
5920   Ops.push_back(Index);
5921   if (!IsUnmasked)
5922     Ops.push_back(Mask);
5923   Ops.push_back(VL);
5924   if (!IsUnmasked)
5925     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5926 
5927   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5928   SDValue Result =
5929       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5930   Chain = Result.getValue(1);
5931 
5932   if (VT.isFixedLengthVector())
5933     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5934 
5935   return DAG.getMergeValues({Result, Chain}, DL);
5936 }
5937 
5938 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5939 // matched to a RVV indexed store. The RVV indexed store instructions only
5940 // support the "unsigned unscaled" addressing mode; indices are implicitly
5941 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5942 // signed or scaled indexing is extended to the XLEN value type and scaled
5943 // accordingly.
5944 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5945                                                 SelectionDAG &DAG) const {
5946   SDLoc DL(Op);
5947   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5948   EVT MemVT = MemSD->getMemoryVT();
5949   MachineMemOperand *MMO = MemSD->getMemOperand();
5950   SDValue Chain = MemSD->getChain();
5951   SDValue BasePtr = MemSD->getBasePtr();
5952 
5953   bool IsTruncatingStore = false;
5954   SDValue Index, Mask, Val, VL;
5955 
5956   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5957     Index = VPSN->getIndex();
5958     Mask = VPSN->getMask();
5959     Val = VPSN->getValue();
5960     VL = VPSN->getVectorLength();
5961     // VP doesn't support truncating stores.
5962     IsTruncatingStore = false;
5963   } else {
5964     // Else it must be a MSCATTER.
5965     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5966     Index = MSN->getIndex();
5967     Mask = MSN->getMask();
5968     Val = MSN->getValue();
5969     IsTruncatingStore = MSN->isTruncatingStore();
5970   }
5971 
5972   MVT VT = Val.getSimpleValueType();
5973   MVT IndexVT = Index.getSimpleValueType();
5974   MVT XLenVT = Subtarget.getXLenVT();
5975 
5976   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5977          "Unexpected VTs!");
5978   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5979   // Targets have to explicitly opt-in for extending vector loads and
5980   // truncating vector stores.
5981   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5982   (void)IsTruncatingStore;
5983 
5984   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5985   // the selection of the masked intrinsics doesn't do this for us.
5986   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5987 
5988   MVT ContainerVT = VT;
5989   if (VT.isFixedLengthVector()) {
5990     // We need to use the larger of the value and index type to determine the
5991     // scalable type to use so we don't increase LMUL for any operand/result.
5992     if (VT.bitsGE(IndexVT)) {
5993       ContainerVT = getContainerForFixedLengthVector(VT);
5994       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5995                                  ContainerVT.getVectorElementCount());
5996     } else {
5997       IndexVT = getContainerForFixedLengthVector(IndexVT);
5998       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5999                                      IndexVT.getVectorElementCount());
6000     }
6001 
6002     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6003     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6004 
6005     if (!IsUnmasked) {
6006       MVT MaskVT =
6007           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6008       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6009     }
6010   }
6011 
6012   if (!VL)
6013     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6014 
6015   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6016     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6017     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6018                                    VL);
6019     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6020                         TrueMask, VL);
6021   }
6022 
6023   unsigned IntID =
6024       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6025   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6026   Ops.push_back(Val);
6027   Ops.push_back(BasePtr);
6028   Ops.push_back(Index);
6029   if (!IsUnmasked)
6030     Ops.push_back(Mask);
6031   Ops.push_back(VL);
6032 
6033   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6034                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6035 }
6036 
6037 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6038                                                SelectionDAG &DAG) const {
6039   const MVT XLenVT = Subtarget.getXLenVT();
6040   SDLoc DL(Op);
6041   SDValue Chain = Op->getOperand(0);
6042   SDValue SysRegNo = DAG.getTargetConstant(
6043       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6044   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6045   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6046 
6047   // Encoding used for rounding mode in RISCV differs from that used in
6048   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6049   // table, which consists of a sequence of 4-bit fields, each representing
6050   // corresponding FLT_ROUNDS mode.
6051   static const int Table =
6052       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6053       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6054       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6055       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6056       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6057 
6058   SDValue Shift =
6059       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6060   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6061                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6062   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6063                                DAG.getConstant(7, DL, XLenVT));
6064 
6065   return DAG.getMergeValues({Masked, Chain}, DL);
6066 }
6067 
6068 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6069                                                SelectionDAG &DAG) const {
6070   const MVT XLenVT = Subtarget.getXLenVT();
6071   SDLoc DL(Op);
6072   SDValue Chain = Op->getOperand(0);
6073   SDValue RMValue = Op->getOperand(1);
6074   SDValue SysRegNo = DAG.getTargetConstant(
6075       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6076 
6077   // Encoding used for rounding mode in RISCV differs from that used in
6078   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6079   // a table, which consists of a sequence of 4-bit fields, each representing
6080   // corresponding RISCV mode.
6081   static const unsigned Table =
6082       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6083       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6084       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6085       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6086       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6087 
6088   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6089                               DAG.getConstant(2, DL, XLenVT));
6090   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6091                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6092   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6093                         DAG.getConstant(0x7, DL, XLenVT));
6094   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6095                      RMValue);
6096 }
6097 
6098 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6099   switch (IntNo) {
6100   default:
6101     llvm_unreachable("Unexpected Intrinsic");
6102   case Intrinsic::riscv_grev:
6103     return RISCVISD::GREVW;
6104   case Intrinsic::riscv_gorc:
6105     return RISCVISD::GORCW;
6106   case Intrinsic::riscv_bcompress:
6107     return RISCVISD::BCOMPRESSW;
6108   case Intrinsic::riscv_bdecompress:
6109     return RISCVISD::BDECOMPRESSW;
6110   case Intrinsic::riscv_bfp:
6111     return RISCVISD::BFPW;
6112   case Intrinsic::riscv_fsl:
6113     return RISCVISD::FSLW;
6114   case Intrinsic::riscv_fsr:
6115     return RISCVISD::FSRW;
6116   }
6117 }
6118 
6119 // Converts the given intrinsic to a i64 operation with any extension.
6120 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6121                                          unsigned IntNo) {
6122   SDLoc DL(N);
6123   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6124   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6125   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6126   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6127   // ReplaceNodeResults requires we maintain the same type for the return value.
6128   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6129 }
6130 
6131 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6132 // form of the given Opcode.
6133 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6134   switch (Opcode) {
6135   default:
6136     llvm_unreachable("Unexpected opcode");
6137   case ISD::SHL:
6138     return RISCVISD::SLLW;
6139   case ISD::SRA:
6140     return RISCVISD::SRAW;
6141   case ISD::SRL:
6142     return RISCVISD::SRLW;
6143   case ISD::SDIV:
6144     return RISCVISD::DIVW;
6145   case ISD::UDIV:
6146     return RISCVISD::DIVUW;
6147   case ISD::UREM:
6148     return RISCVISD::REMUW;
6149   case ISD::ROTL:
6150     return RISCVISD::ROLW;
6151   case ISD::ROTR:
6152     return RISCVISD::RORW;
6153   case RISCVISD::GREV:
6154     return RISCVISD::GREVW;
6155   case RISCVISD::GORC:
6156     return RISCVISD::GORCW;
6157   }
6158 }
6159 
6160 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6161 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6162 // otherwise be promoted to i64, making it difficult to select the
6163 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6164 // type i8/i16/i32 is lost.
6165 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6166                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6167   SDLoc DL(N);
6168   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6169   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6170   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6171   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6172   // ReplaceNodeResults requires we maintain the same type for the return value.
6173   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6174 }
6175 
6176 // Converts the given 32-bit operation to a i64 operation with signed extension
6177 // semantic to reduce the signed extension instructions.
6178 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6179   SDLoc DL(N);
6180   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6181   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6182   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6183   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6184                                DAG.getValueType(MVT::i32));
6185   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6186 }
6187 
6188 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6189                                              SmallVectorImpl<SDValue> &Results,
6190                                              SelectionDAG &DAG) const {
6191   SDLoc DL(N);
6192   switch (N->getOpcode()) {
6193   default:
6194     llvm_unreachable("Don't know how to custom type legalize this operation!");
6195   case ISD::STRICT_FP_TO_SINT:
6196   case ISD::STRICT_FP_TO_UINT:
6197   case ISD::FP_TO_SINT:
6198   case ISD::FP_TO_UINT: {
6199     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6200            "Unexpected custom legalisation");
6201     bool IsStrict = N->isStrictFPOpcode();
6202     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6203                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6204     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6205     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6206         TargetLowering::TypeSoftenFloat) {
6207       if (!isTypeLegal(Op0.getValueType()))
6208         return;
6209       if (IsStrict) {
6210         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6211                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6212         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6213         SDValue Res = DAG.getNode(
6214             Opc, DL, VTs, N->getOperand(0), Op0,
6215             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6216         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6217         Results.push_back(Res.getValue(1));
6218         return;
6219       }
6220       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6221       SDValue Res =
6222           DAG.getNode(Opc, DL, MVT::i64, Op0,
6223                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6224       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6225       return;
6226     }
6227     // If the FP type needs to be softened, emit a library call using the 'si'
6228     // version. If we left it to default legalization we'd end up with 'di'. If
6229     // the FP type doesn't need to be softened just let generic type
6230     // legalization promote the result type.
6231     RTLIB::Libcall LC;
6232     if (IsSigned)
6233       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6234     else
6235       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6236     MakeLibCallOptions CallOptions;
6237     EVT OpVT = Op0.getValueType();
6238     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6239     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6240     SDValue Result;
6241     std::tie(Result, Chain) =
6242         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6243     Results.push_back(Result);
6244     if (IsStrict)
6245       Results.push_back(Chain);
6246     break;
6247   }
6248   case ISD::READCYCLECOUNTER: {
6249     assert(!Subtarget.is64Bit() &&
6250            "READCYCLECOUNTER only has custom type legalization on riscv32");
6251 
6252     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6253     SDValue RCW =
6254         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6255 
6256     Results.push_back(
6257         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6258     Results.push_back(RCW.getValue(2));
6259     break;
6260   }
6261   case ISD::MUL: {
6262     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6263     unsigned XLen = Subtarget.getXLen();
6264     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6265     if (Size > XLen) {
6266       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6267       SDValue LHS = N->getOperand(0);
6268       SDValue RHS = N->getOperand(1);
6269       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6270 
6271       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6272       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6273       // We need exactly one side to be unsigned.
6274       if (LHSIsU == RHSIsU)
6275         return;
6276 
6277       auto MakeMULPair = [&](SDValue S, SDValue U) {
6278         MVT XLenVT = Subtarget.getXLenVT();
6279         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6280         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6281         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6282         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6283         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6284       };
6285 
6286       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6287       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6288 
6289       // The other operand should be signed, but still prefer MULH when
6290       // possible.
6291       if (RHSIsU && LHSIsS && !RHSIsS)
6292         Results.push_back(MakeMULPair(LHS, RHS));
6293       else if (LHSIsU && RHSIsS && !LHSIsS)
6294         Results.push_back(MakeMULPair(RHS, LHS));
6295 
6296       return;
6297     }
6298     LLVM_FALLTHROUGH;
6299   }
6300   case ISD::ADD:
6301   case ISD::SUB:
6302     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6303            "Unexpected custom legalisation");
6304     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6305     break;
6306   case ISD::SHL:
6307   case ISD::SRA:
6308   case ISD::SRL:
6309     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6310            "Unexpected custom legalisation");
6311     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6312       Results.push_back(customLegalizeToWOp(N, DAG));
6313       break;
6314     }
6315 
6316     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6317     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6318     // shift amount.
6319     if (N->getOpcode() == ISD::SHL) {
6320       SDLoc DL(N);
6321       SDValue NewOp0 =
6322           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6323       SDValue NewOp1 =
6324           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6325       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6326       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6327                                    DAG.getValueType(MVT::i32));
6328       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6329     }
6330 
6331     break;
6332   case ISD::ROTL:
6333   case ISD::ROTR:
6334     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6335            "Unexpected custom legalisation");
6336     Results.push_back(customLegalizeToWOp(N, DAG));
6337     break;
6338   case ISD::CTTZ:
6339   case ISD::CTTZ_ZERO_UNDEF:
6340   case ISD::CTLZ:
6341   case ISD::CTLZ_ZERO_UNDEF: {
6342     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6343            "Unexpected custom legalisation");
6344 
6345     SDValue NewOp0 =
6346         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6347     bool IsCTZ =
6348         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6349     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6350     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6351     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6352     return;
6353   }
6354   case ISD::SDIV:
6355   case ISD::UDIV:
6356   case ISD::UREM: {
6357     MVT VT = N->getSimpleValueType(0);
6358     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6359            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6360            "Unexpected custom legalisation");
6361     // Don't promote division/remainder by constant since we should expand those
6362     // to multiply by magic constant.
6363     // FIXME: What if the expansion is disabled for minsize.
6364     if (N->getOperand(1).getOpcode() == ISD::Constant)
6365       return;
6366 
6367     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6368     // the upper 32 bits. For other types we need to sign or zero extend
6369     // based on the opcode.
6370     unsigned ExtOpc = ISD::ANY_EXTEND;
6371     if (VT != MVT::i32)
6372       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6373                                            : ISD::ZERO_EXTEND;
6374 
6375     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6376     break;
6377   }
6378   case ISD::UADDO:
6379   case ISD::USUBO: {
6380     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6381            "Unexpected custom legalisation");
6382     bool IsAdd = N->getOpcode() == ISD::UADDO;
6383     // Create an ADDW or SUBW.
6384     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6385     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6386     SDValue Res =
6387         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6388     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6389                       DAG.getValueType(MVT::i32));
6390 
6391     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6392     // Since the inputs are sign extended from i32, this is equivalent to
6393     // comparing the lower 32 bits.
6394     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6395     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6396                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6397 
6398     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6399     Results.push_back(Overflow);
6400     return;
6401   }
6402   case ISD::UADDSAT:
6403   case ISD::USUBSAT: {
6404     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6405            "Unexpected custom legalisation");
6406     if (Subtarget.hasStdExtZbb()) {
6407       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6408       // sign extend allows overflow of the lower 32 bits to be detected on
6409       // the promoted size.
6410       SDValue LHS =
6411           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6412       SDValue RHS =
6413           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6414       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6415       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6416       return;
6417     }
6418 
6419     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6420     // promotion for UADDO/USUBO.
6421     Results.push_back(expandAddSubSat(N, DAG));
6422     return;
6423   }
6424   case ISD::BITCAST: {
6425     EVT VT = N->getValueType(0);
6426     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6427     SDValue Op0 = N->getOperand(0);
6428     EVT Op0VT = Op0.getValueType();
6429     MVT XLenVT = Subtarget.getXLenVT();
6430     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6431       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6432       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6433     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6434                Subtarget.hasStdExtF()) {
6435       SDValue FPConv =
6436           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6437       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6438     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6439                isTypeLegal(Op0VT)) {
6440       // Custom-legalize bitcasts from fixed-length vector types to illegal
6441       // scalar types in order to improve codegen. Bitcast the vector to a
6442       // one-element vector type whose element type is the same as the result
6443       // type, and extract the first element.
6444       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6445       if (isTypeLegal(BVT)) {
6446         SDValue BVec = DAG.getBitcast(BVT, Op0);
6447         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6448                                       DAG.getConstant(0, DL, XLenVT)));
6449       }
6450     }
6451     break;
6452   }
6453   case RISCVISD::GREV:
6454   case RISCVISD::GORC: {
6455     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6456            "Unexpected custom legalisation");
6457     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6458     // This is similar to customLegalizeToWOp, except that we pass the second
6459     // operand (a TargetConstant) straight through: it is already of type
6460     // XLenVT.
6461     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6462     SDValue NewOp0 =
6463         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6464     SDValue NewOp1 =
6465         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6466     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6467     // ReplaceNodeResults requires we maintain the same type for the return
6468     // value.
6469     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6470     break;
6471   }
6472   case RISCVISD::SHFL: {
6473     // There is no SHFLIW instruction, but we can just promote the operation.
6474     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6475            "Unexpected custom legalisation");
6476     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6477     SDValue NewOp0 =
6478         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6479     SDValue NewOp1 =
6480         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6481     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6482     // ReplaceNodeResults requires we maintain the same type for the return
6483     // value.
6484     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6485     break;
6486   }
6487   case ISD::BSWAP:
6488   case ISD::BITREVERSE: {
6489     MVT VT = N->getSimpleValueType(0);
6490     MVT XLenVT = Subtarget.getXLenVT();
6491     assert((VT == MVT::i8 || VT == MVT::i16 ||
6492             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6493            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6494     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6495     unsigned Imm = VT.getSizeInBits() - 1;
6496     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6497     if (N->getOpcode() == ISD::BSWAP)
6498       Imm &= ~0x7U;
6499     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6500     SDValue GREVI =
6501         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6502     // ReplaceNodeResults requires we maintain the same type for the return
6503     // value.
6504     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6505     break;
6506   }
6507   case ISD::FSHL:
6508   case ISD::FSHR: {
6509     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6510            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6511     SDValue NewOp0 =
6512         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6513     SDValue NewOp1 =
6514         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6515     SDValue NewShAmt =
6516         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6517     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6518     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6519     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6520                            DAG.getConstant(0x1f, DL, MVT::i64));
6521     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6522     // instruction use different orders. fshl will return its first operand for
6523     // shift of zero, fshr will return its second operand. fsl and fsr both
6524     // return rs1 so the ISD nodes need to have different operand orders.
6525     // Shift amount is in rs2.
6526     unsigned Opc = RISCVISD::FSLW;
6527     if (N->getOpcode() == ISD::FSHR) {
6528       std::swap(NewOp0, NewOp1);
6529       Opc = RISCVISD::FSRW;
6530     }
6531     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6532     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6533     break;
6534   }
6535   case ISD::EXTRACT_VECTOR_ELT: {
6536     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6537     // type is illegal (currently only vXi64 RV32).
6538     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6539     // transferred to the destination register. We issue two of these from the
6540     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6541     // first element.
6542     SDValue Vec = N->getOperand(0);
6543     SDValue Idx = N->getOperand(1);
6544 
6545     // The vector type hasn't been legalized yet so we can't issue target
6546     // specific nodes if it needs legalization.
6547     // FIXME: We would manually legalize if it's important.
6548     if (!isTypeLegal(Vec.getValueType()))
6549       return;
6550 
6551     MVT VecVT = Vec.getSimpleValueType();
6552 
6553     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6554            VecVT.getVectorElementType() == MVT::i64 &&
6555            "Unexpected EXTRACT_VECTOR_ELT legalization");
6556 
6557     // If this is a fixed vector, we need to convert it to a scalable vector.
6558     MVT ContainerVT = VecVT;
6559     if (VecVT.isFixedLengthVector()) {
6560       ContainerVT = getContainerForFixedLengthVector(VecVT);
6561       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6562     }
6563 
6564     MVT XLenVT = Subtarget.getXLenVT();
6565 
6566     // Use a VL of 1 to avoid processing more elements than we need.
6567     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6568     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6569     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6570 
6571     // Unless the index is known to be 0, we must slide the vector down to get
6572     // the desired element into index 0.
6573     if (!isNullConstant(Idx)) {
6574       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6575                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6576     }
6577 
6578     // Extract the lower XLEN bits of the correct vector element.
6579     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6580 
6581     // To extract the upper XLEN bits of the vector element, shift the first
6582     // element right by 32 bits and re-extract the lower XLEN bits.
6583     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6584                                      DAG.getConstant(32, DL, XLenVT), VL);
6585     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6586                                  ThirtyTwoV, Mask, VL);
6587 
6588     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6589 
6590     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6591     break;
6592   }
6593   case ISD::INTRINSIC_WO_CHAIN: {
6594     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6595     switch (IntNo) {
6596     default:
6597       llvm_unreachable(
6598           "Don't know how to custom type legalize this intrinsic!");
6599     case Intrinsic::riscv_grev:
6600     case Intrinsic::riscv_gorc:
6601     case Intrinsic::riscv_bcompress:
6602     case Intrinsic::riscv_bdecompress:
6603     case Intrinsic::riscv_bfp: {
6604       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6605              "Unexpected custom legalisation");
6606       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6607       break;
6608     }
6609     case Intrinsic::riscv_fsl:
6610     case Intrinsic::riscv_fsr: {
6611       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6612              "Unexpected custom legalisation");
6613       SDValue NewOp1 =
6614           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6615       SDValue NewOp2 =
6616           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6617       SDValue NewOp3 =
6618           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6619       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6620       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6621       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6622       break;
6623     }
6624     case Intrinsic::riscv_orc_b: {
6625       // Lower to the GORCI encoding for orc.b with the operand extended.
6626       SDValue NewOp =
6627           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6628       // If Zbp is enabled, use GORCIW which will sign extend the result.
6629       unsigned Opc =
6630           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6631       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6632                                 DAG.getConstant(7, DL, MVT::i64));
6633       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6634       return;
6635     }
6636     case Intrinsic::riscv_shfl:
6637     case Intrinsic::riscv_unshfl: {
6638       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6639              "Unexpected custom legalisation");
6640       SDValue NewOp1 =
6641           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6642       SDValue NewOp2 =
6643           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6644       unsigned Opc =
6645           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6646       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6647       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6648       // will be shuffled the same way as the lower 32 bit half, but the two
6649       // halves won't cross.
6650       if (isa<ConstantSDNode>(NewOp2)) {
6651         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6652                              DAG.getConstant(0xf, DL, MVT::i64));
6653         Opc =
6654             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6655       }
6656       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6657       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6658       break;
6659     }
6660     case Intrinsic::riscv_vmv_x_s: {
6661       EVT VT = N->getValueType(0);
6662       MVT XLenVT = Subtarget.getXLenVT();
6663       if (VT.bitsLT(XLenVT)) {
6664         // Simple case just extract using vmv.x.s and truncate.
6665         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6666                                       Subtarget.getXLenVT(), N->getOperand(1));
6667         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6668         return;
6669       }
6670 
6671       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6672              "Unexpected custom legalization");
6673 
6674       // We need to do the move in two steps.
6675       SDValue Vec = N->getOperand(1);
6676       MVT VecVT = Vec.getSimpleValueType();
6677 
6678       // First extract the lower XLEN bits of the element.
6679       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6680 
6681       // To extract the upper XLEN bits of the vector element, shift the first
6682       // element right by 32 bits and re-extract the lower XLEN bits.
6683       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6684       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6685       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6686       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6687                                        DAG.getConstant(32, DL, XLenVT), VL);
6688       SDValue LShr32 =
6689           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6690       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6691 
6692       Results.push_back(
6693           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6694       break;
6695     }
6696     }
6697     break;
6698   }
6699   case ISD::VECREDUCE_ADD:
6700   case ISD::VECREDUCE_AND:
6701   case ISD::VECREDUCE_OR:
6702   case ISD::VECREDUCE_XOR:
6703   case ISD::VECREDUCE_SMAX:
6704   case ISD::VECREDUCE_UMAX:
6705   case ISD::VECREDUCE_SMIN:
6706   case ISD::VECREDUCE_UMIN:
6707     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6708       Results.push_back(V);
6709     break;
6710   case ISD::VP_REDUCE_ADD:
6711   case ISD::VP_REDUCE_AND:
6712   case ISD::VP_REDUCE_OR:
6713   case ISD::VP_REDUCE_XOR:
6714   case ISD::VP_REDUCE_SMAX:
6715   case ISD::VP_REDUCE_UMAX:
6716   case ISD::VP_REDUCE_SMIN:
6717   case ISD::VP_REDUCE_UMIN:
6718     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6719       Results.push_back(V);
6720     break;
6721   case ISD::FLT_ROUNDS_: {
6722     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6723     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6724     Results.push_back(Res.getValue(0));
6725     Results.push_back(Res.getValue(1));
6726     break;
6727   }
6728   }
6729 }
6730 
6731 // A structure to hold one of the bit-manipulation patterns below. Together, a
6732 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6733 //   (or (and (shl x, 1), 0xAAAAAAAA),
6734 //       (and (srl x, 1), 0x55555555))
6735 struct RISCVBitmanipPat {
6736   SDValue Op;
6737   unsigned ShAmt;
6738   bool IsSHL;
6739 
6740   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6741     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6742   }
6743 };
6744 
6745 // Matches patterns of the form
6746 //   (and (shl x, C2), (C1 << C2))
6747 //   (and (srl x, C2), C1)
6748 //   (shl (and x, C1), C2)
6749 //   (srl (and x, (C1 << C2)), C2)
6750 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6751 // The expected masks for each shift amount are specified in BitmanipMasks where
6752 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6753 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6754 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6755 // XLen is 64.
6756 static Optional<RISCVBitmanipPat>
6757 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6758   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6759          "Unexpected number of masks");
6760   Optional<uint64_t> Mask;
6761   // Optionally consume a mask around the shift operation.
6762   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6763     Mask = Op.getConstantOperandVal(1);
6764     Op = Op.getOperand(0);
6765   }
6766   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6767     return None;
6768   bool IsSHL = Op.getOpcode() == ISD::SHL;
6769 
6770   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6771     return None;
6772   uint64_t ShAmt = Op.getConstantOperandVal(1);
6773 
6774   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6775   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6776     return None;
6777   // If we don't have enough masks for 64 bit, then we must be trying to
6778   // match SHFL so we're only allowed to shift 1/4 of the width.
6779   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6780     return None;
6781 
6782   SDValue Src = Op.getOperand(0);
6783 
6784   // The expected mask is shifted left when the AND is found around SHL
6785   // patterns.
6786   //   ((x >> 1) & 0x55555555)
6787   //   ((x << 1) & 0xAAAAAAAA)
6788   bool SHLExpMask = IsSHL;
6789 
6790   if (!Mask) {
6791     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6792     // the mask is all ones: consume that now.
6793     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6794       Mask = Src.getConstantOperandVal(1);
6795       Src = Src.getOperand(0);
6796       // The expected mask is now in fact shifted left for SRL, so reverse the
6797       // decision.
6798       //   ((x & 0xAAAAAAAA) >> 1)
6799       //   ((x & 0x55555555) << 1)
6800       SHLExpMask = !SHLExpMask;
6801     } else {
6802       // Use a default shifted mask of all-ones if there's no AND, truncated
6803       // down to the expected width. This simplifies the logic later on.
6804       Mask = maskTrailingOnes<uint64_t>(Width);
6805       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6806     }
6807   }
6808 
6809   unsigned MaskIdx = Log2_32(ShAmt);
6810   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6811 
6812   if (SHLExpMask)
6813     ExpMask <<= ShAmt;
6814 
6815   if (Mask != ExpMask)
6816     return None;
6817 
6818   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6819 }
6820 
6821 // Matches any of the following bit-manipulation patterns:
6822 //   (and (shl x, 1), (0x55555555 << 1))
6823 //   (and (srl x, 1), 0x55555555)
6824 //   (shl (and x, 0x55555555), 1)
6825 //   (srl (and x, (0x55555555 << 1)), 1)
6826 // where the shift amount and mask may vary thus:
6827 //   [1]  = 0x55555555 / 0xAAAAAAAA
6828 //   [2]  = 0x33333333 / 0xCCCCCCCC
6829 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6830 //   [8]  = 0x00FF00FF / 0xFF00FF00
6831 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6832 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6833 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6834   // These are the unshifted masks which we use to match bit-manipulation
6835   // patterns. They may be shifted left in certain circumstances.
6836   static const uint64_t BitmanipMasks[] = {
6837       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6838       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6839 
6840   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6841 }
6842 
6843 // Match the following pattern as a GREVI(W) operation
6844 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6845 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6846                                const RISCVSubtarget &Subtarget) {
6847   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6848   EVT VT = Op.getValueType();
6849 
6850   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6851     auto LHS = matchGREVIPat(Op.getOperand(0));
6852     auto RHS = matchGREVIPat(Op.getOperand(1));
6853     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6854       SDLoc DL(Op);
6855       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6856                          DAG.getConstant(LHS->ShAmt, DL, VT));
6857     }
6858   }
6859   return SDValue();
6860 }
6861 
6862 // Matches any the following pattern as a GORCI(W) operation
6863 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6864 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6865 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6866 // Note that with the variant of 3.,
6867 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6868 // the inner pattern will first be matched as GREVI and then the outer
6869 // pattern will be matched to GORC via the first rule above.
6870 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6871 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6872                                const RISCVSubtarget &Subtarget) {
6873   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6874   EVT VT = Op.getValueType();
6875 
6876   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6877     SDLoc DL(Op);
6878     SDValue Op0 = Op.getOperand(0);
6879     SDValue Op1 = Op.getOperand(1);
6880 
6881     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6882       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6883           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6884           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6885         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6886       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6887       if ((Reverse.getOpcode() == ISD::ROTL ||
6888            Reverse.getOpcode() == ISD::ROTR) &&
6889           Reverse.getOperand(0) == X &&
6890           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6891         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6892         if (RotAmt == (VT.getSizeInBits() / 2))
6893           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6894                              DAG.getConstant(RotAmt, DL, VT));
6895       }
6896       return SDValue();
6897     };
6898 
6899     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6900     if (SDValue V = MatchOROfReverse(Op0, Op1))
6901       return V;
6902     if (SDValue V = MatchOROfReverse(Op1, Op0))
6903       return V;
6904 
6905     // OR is commutable so canonicalize its OR operand to the left
6906     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6907       std::swap(Op0, Op1);
6908     if (Op0.getOpcode() != ISD::OR)
6909       return SDValue();
6910     SDValue OrOp0 = Op0.getOperand(0);
6911     SDValue OrOp1 = Op0.getOperand(1);
6912     auto LHS = matchGREVIPat(OrOp0);
6913     // OR is commutable so swap the operands and try again: x might have been
6914     // on the left
6915     if (!LHS) {
6916       std::swap(OrOp0, OrOp1);
6917       LHS = matchGREVIPat(OrOp0);
6918     }
6919     auto RHS = matchGREVIPat(Op1);
6920     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6921       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6922                          DAG.getConstant(LHS->ShAmt, DL, VT));
6923     }
6924   }
6925   return SDValue();
6926 }
6927 
6928 // Matches any of the following bit-manipulation patterns:
6929 //   (and (shl x, 1), (0x22222222 << 1))
6930 //   (and (srl x, 1), 0x22222222)
6931 //   (shl (and x, 0x22222222), 1)
6932 //   (srl (and x, (0x22222222 << 1)), 1)
6933 // where the shift amount and mask may vary thus:
6934 //   [1]  = 0x22222222 / 0x44444444
6935 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6936 //   [4]  = 0x00F000F0 / 0x0F000F00
6937 //   [8]  = 0x0000FF00 / 0x00FF0000
6938 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6939 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6940   // These are the unshifted masks which we use to match bit-manipulation
6941   // patterns. They may be shifted left in certain circumstances.
6942   static const uint64_t BitmanipMasks[] = {
6943       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6944       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6945 
6946   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6947 }
6948 
6949 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6950 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6951                                const RISCVSubtarget &Subtarget) {
6952   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6953   EVT VT = Op.getValueType();
6954 
6955   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6956     return SDValue();
6957 
6958   SDValue Op0 = Op.getOperand(0);
6959   SDValue Op1 = Op.getOperand(1);
6960 
6961   // Or is commutable so canonicalize the second OR to the LHS.
6962   if (Op0.getOpcode() != ISD::OR)
6963     std::swap(Op0, Op1);
6964   if (Op0.getOpcode() != ISD::OR)
6965     return SDValue();
6966 
6967   // We found an inner OR, so our operands are the operands of the inner OR
6968   // and the other operand of the outer OR.
6969   SDValue A = Op0.getOperand(0);
6970   SDValue B = Op0.getOperand(1);
6971   SDValue C = Op1;
6972 
6973   auto Match1 = matchSHFLPat(A);
6974   auto Match2 = matchSHFLPat(B);
6975 
6976   // If neither matched, we failed.
6977   if (!Match1 && !Match2)
6978     return SDValue();
6979 
6980   // We had at least one match. if one failed, try the remaining C operand.
6981   if (!Match1) {
6982     std::swap(A, C);
6983     Match1 = matchSHFLPat(A);
6984     if (!Match1)
6985       return SDValue();
6986   } else if (!Match2) {
6987     std::swap(B, C);
6988     Match2 = matchSHFLPat(B);
6989     if (!Match2)
6990       return SDValue();
6991   }
6992   assert(Match1 && Match2);
6993 
6994   // Make sure our matches pair up.
6995   if (!Match1->formsPairWith(*Match2))
6996     return SDValue();
6997 
6998   // All the remains is to make sure C is an AND with the same input, that masks
6999   // out the bits that are being shuffled.
7000   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7001       C.getOperand(0) != Match1->Op)
7002     return SDValue();
7003 
7004   uint64_t Mask = C.getConstantOperandVal(1);
7005 
7006   static const uint64_t BitmanipMasks[] = {
7007       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7008       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7009   };
7010 
7011   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7012   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7013   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7014 
7015   if (Mask != ExpMask)
7016     return SDValue();
7017 
7018   SDLoc DL(Op);
7019   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7020                      DAG.getConstant(Match1->ShAmt, DL, VT));
7021 }
7022 
7023 // Optimize (add (shl x, c0), (shl y, c1)) ->
7024 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7025 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7026                                   const RISCVSubtarget &Subtarget) {
7027   // Perform this optimization only in the zba extension.
7028   if (!Subtarget.hasStdExtZba())
7029     return SDValue();
7030 
7031   // Skip for vector types and larger types.
7032   EVT VT = N->getValueType(0);
7033   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7034     return SDValue();
7035 
7036   // The two operand nodes must be SHL and have no other use.
7037   SDValue N0 = N->getOperand(0);
7038   SDValue N1 = N->getOperand(1);
7039   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7040       !N0->hasOneUse() || !N1->hasOneUse())
7041     return SDValue();
7042 
7043   // Check c0 and c1.
7044   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7045   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7046   if (!N0C || !N1C)
7047     return SDValue();
7048   int64_t C0 = N0C->getSExtValue();
7049   int64_t C1 = N1C->getSExtValue();
7050   if (C0 <= 0 || C1 <= 0)
7051     return SDValue();
7052 
7053   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7054   int64_t Bits = std::min(C0, C1);
7055   int64_t Diff = std::abs(C0 - C1);
7056   if (Diff != 1 && Diff != 2 && Diff != 3)
7057     return SDValue();
7058 
7059   // Build nodes.
7060   SDLoc DL(N);
7061   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7062   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7063   SDValue NA0 =
7064       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7065   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7066   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7067 }
7068 
7069 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7070 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7071 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7072 // not undo itself, but they are redundant.
7073 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7074   SDValue Src = N->getOperand(0);
7075 
7076   if (Src.getOpcode() != N->getOpcode())
7077     return SDValue();
7078 
7079   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7080       !isa<ConstantSDNode>(Src.getOperand(1)))
7081     return SDValue();
7082 
7083   unsigned ShAmt1 = N->getConstantOperandVal(1);
7084   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7085   Src = Src.getOperand(0);
7086 
7087   unsigned CombinedShAmt;
7088   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7089     CombinedShAmt = ShAmt1 | ShAmt2;
7090   else
7091     CombinedShAmt = ShAmt1 ^ ShAmt2;
7092 
7093   if (CombinedShAmt == 0)
7094     return Src;
7095 
7096   SDLoc DL(N);
7097   return DAG.getNode(
7098       N->getOpcode(), DL, N->getValueType(0), Src,
7099       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7100 }
7101 
7102 // Combine a constant select operand into its use:
7103 //
7104 // (and (select cond, -1, c), x)
7105 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7106 // (or  (select cond, 0, c), x)
7107 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7108 // (xor (select cond, 0, c), x)
7109 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7110 // (add (select cond, 0, c), x)
7111 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7112 // (sub x, (select cond, 0, c))
7113 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7114 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7115                                    SelectionDAG &DAG, bool AllOnes) {
7116   EVT VT = N->getValueType(0);
7117 
7118   // Skip vectors.
7119   if (VT.isVector())
7120     return SDValue();
7121 
7122   if ((Slct.getOpcode() != ISD::SELECT &&
7123        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7124       !Slct.hasOneUse())
7125     return SDValue();
7126 
7127   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7128     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7129   };
7130 
7131   bool SwapSelectOps;
7132   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7133   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7134   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7135   SDValue NonConstantVal;
7136   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7137     SwapSelectOps = false;
7138     NonConstantVal = FalseVal;
7139   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7140     SwapSelectOps = true;
7141     NonConstantVal = TrueVal;
7142   } else
7143     return SDValue();
7144 
7145   // Slct is now know to be the desired identity constant when CC is true.
7146   TrueVal = OtherOp;
7147   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7148   // Unless SwapSelectOps says the condition should be false.
7149   if (SwapSelectOps)
7150     std::swap(TrueVal, FalseVal);
7151 
7152   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7153     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7154                        {Slct.getOperand(0), Slct.getOperand(1),
7155                         Slct.getOperand(2), TrueVal, FalseVal});
7156 
7157   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7158                      {Slct.getOperand(0), TrueVal, FalseVal});
7159 }
7160 
7161 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7162 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7163                                               bool AllOnes) {
7164   SDValue N0 = N->getOperand(0);
7165   SDValue N1 = N->getOperand(1);
7166   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7167     return Result;
7168   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7169     return Result;
7170   return SDValue();
7171 }
7172 
7173 // Transform (add (mul x, c0), c1) ->
7174 //           (add (mul (add x, c1/c0), c0), c1%c0).
7175 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7176 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7177 // to an infinite loop in DAGCombine if transformed.
7178 // Or transform (add (mul x, c0), c1) ->
7179 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7180 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7181 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7182 // lead to an infinite loop in DAGCombine if transformed.
7183 // Or transform (add (mul x, c0), c1) ->
7184 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7185 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7186 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7187 // lead to an infinite loop in DAGCombine if transformed.
7188 // Or transform (add (mul x, c0), c1) ->
7189 //              (mul (add x, c1/c0), c0).
7190 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7191 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7192                                      const RISCVSubtarget &Subtarget) {
7193   // Skip for vector types and larger types.
7194   EVT VT = N->getValueType(0);
7195   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7196     return SDValue();
7197   // The first operand node must be a MUL and has no other use.
7198   SDValue N0 = N->getOperand(0);
7199   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7200     return SDValue();
7201   // Check if c0 and c1 match above conditions.
7202   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7203   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7204   if (!N0C || !N1C)
7205     return SDValue();
7206   int64_t C0 = N0C->getSExtValue();
7207   int64_t C1 = N1C->getSExtValue();
7208   int64_t CA, CB;
7209   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7210     return SDValue();
7211   // Search for proper CA (non-zero) and CB that both are simm12.
7212   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7213       !isInt<12>(C0 * (C1 / C0))) {
7214     CA = C1 / C0;
7215     CB = C1 % C0;
7216   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7217              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7218     CA = C1 / C0 + 1;
7219     CB = C1 % C0 - C0;
7220   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7221              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7222     CA = C1 / C0 - 1;
7223     CB = C1 % C0 + C0;
7224   } else
7225     return SDValue();
7226   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7227   SDLoc DL(N);
7228   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7229                              DAG.getConstant(CA, DL, VT));
7230   SDValue New1 =
7231       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7232   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7233 }
7234 
7235 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7236                                  const RISCVSubtarget &Subtarget) {
7237   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7238     return V;
7239   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7240     return V;
7241   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7242   //      (select lhs, rhs, cc, x, (add x, y))
7243   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7244 }
7245 
7246 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7247   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7248   //      (select lhs, rhs, cc, x, (sub x, y))
7249   SDValue N0 = N->getOperand(0);
7250   SDValue N1 = N->getOperand(1);
7251   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7252 }
7253 
7254 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7255   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7256   //      (select lhs, rhs, cc, x, (and x, y))
7257   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7258 }
7259 
7260 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7261                                 const RISCVSubtarget &Subtarget) {
7262   if (Subtarget.hasStdExtZbp()) {
7263     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7264       return GREV;
7265     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7266       return GORC;
7267     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7268       return SHFL;
7269   }
7270 
7271   // fold (or (select cond, 0, y), x) ->
7272   //      (select cond, x, (or x, y))
7273   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7274 }
7275 
7276 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7277   // fold (xor (select cond, 0, y), x) ->
7278   //      (select cond, x, (xor x, y))
7279   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7280 }
7281 
7282 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7283 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7284 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7285 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7286 // ADDW/SUBW/MULW.
7287 static SDValue performANY_EXTENDCombine(SDNode *N,
7288                                         TargetLowering::DAGCombinerInfo &DCI,
7289                                         const RISCVSubtarget &Subtarget) {
7290   if (!Subtarget.is64Bit())
7291     return SDValue();
7292 
7293   SelectionDAG &DAG = DCI.DAG;
7294 
7295   SDValue Src = N->getOperand(0);
7296   EVT VT = N->getValueType(0);
7297   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7298     return SDValue();
7299 
7300   // The opcode must be one that can implicitly sign_extend.
7301   // FIXME: Additional opcodes.
7302   switch (Src.getOpcode()) {
7303   default:
7304     return SDValue();
7305   case ISD::MUL:
7306     if (!Subtarget.hasStdExtM())
7307       return SDValue();
7308     LLVM_FALLTHROUGH;
7309   case ISD::ADD:
7310   case ISD::SUB:
7311     break;
7312   }
7313 
7314   // Only handle cases where the result is used by a CopyToReg. That likely
7315   // means the value is a liveout of the basic block. This helps prevent
7316   // infinite combine loops like PR51206.
7317   if (none_of(N->uses(),
7318               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7319     return SDValue();
7320 
7321   SmallVector<SDNode *, 4> SetCCs;
7322   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7323                             UE = Src.getNode()->use_end();
7324        UI != UE; ++UI) {
7325     SDNode *User = *UI;
7326     if (User == N)
7327       continue;
7328     if (UI.getUse().getResNo() != Src.getResNo())
7329       continue;
7330     // All i32 setccs are legalized by sign extending operands.
7331     if (User->getOpcode() == ISD::SETCC) {
7332       SetCCs.push_back(User);
7333       continue;
7334     }
7335     // We don't know if we can extend this user.
7336     break;
7337   }
7338 
7339   // If we don't have any SetCCs, this isn't worthwhile.
7340   if (SetCCs.empty())
7341     return SDValue();
7342 
7343   SDLoc DL(N);
7344   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7345   DCI.CombineTo(N, SExt);
7346 
7347   // Promote all the setccs.
7348   for (SDNode *SetCC : SetCCs) {
7349     SmallVector<SDValue, 4> Ops;
7350 
7351     for (unsigned j = 0; j != 2; ++j) {
7352       SDValue SOp = SetCC->getOperand(j);
7353       if (SOp == Src)
7354         Ops.push_back(SExt);
7355       else
7356         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7357     }
7358 
7359     Ops.push_back(SetCC->getOperand(2));
7360     DCI.CombineTo(SetCC,
7361                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7362   }
7363   return SDValue(N, 0);
7364 }
7365 
7366 // Try to form VWMUL, VWMULU or VWMULSU.
7367 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7368 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7369                                        bool Commute) {
7370   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7371   SDValue Op0 = N->getOperand(0);
7372   SDValue Op1 = N->getOperand(1);
7373   if (Commute)
7374     std::swap(Op0, Op1);
7375 
7376   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7377   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7378   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7379   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7380     return SDValue();
7381 
7382   SDValue Mask = N->getOperand(2);
7383   SDValue VL = N->getOperand(3);
7384 
7385   // Make sure the mask and VL match.
7386   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7387     return SDValue();
7388 
7389   MVT VT = N->getSimpleValueType(0);
7390 
7391   // Determine the narrow size for a widening multiply.
7392   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7393   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7394                                   VT.getVectorElementCount());
7395 
7396   SDLoc DL(N);
7397 
7398   // See if the other operand is the same opcode.
7399   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7400     if (!Op1.hasOneUse())
7401       return SDValue();
7402 
7403     // Make sure the mask and VL match.
7404     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7405       return SDValue();
7406 
7407     Op1 = Op1.getOperand(0);
7408   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7409     // The operand is a splat of a scalar.
7410 
7411     // The VL must be the same.
7412     if (Op1.getOperand(1) != VL)
7413       return SDValue();
7414 
7415     // Get the scalar value.
7416     Op1 = Op1.getOperand(0);
7417 
7418     // See if have enough sign bits or zero bits in the scalar to use a
7419     // widening multiply by splatting to smaller element size.
7420     unsigned EltBits = VT.getScalarSizeInBits();
7421     unsigned ScalarBits = Op1.getValueSizeInBits();
7422     // Make sure we're getting all element bits from the scalar register.
7423     // FIXME: Support implicit sign extension of vmv.v.x?
7424     if (ScalarBits < EltBits)
7425       return SDValue();
7426 
7427     if (IsSignExt) {
7428       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7429         return SDValue();
7430     } else {
7431       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7432       if (!DAG.MaskedValueIsZero(Op1, Mask))
7433         return SDValue();
7434     }
7435 
7436     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7437   } else
7438     return SDValue();
7439 
7440   Op0 = Op0.getOperand(0);
7441 
7442   // Re-introduce narrower extends if needed.
7443   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7444   if (Op0.getValueType() != NarrowVT)
7445     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7446   if (Op1.getValueType() != NarrowVT)
7447     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7448 
7449   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7450   if (!IsVWMULSU)
7451     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7452   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7453 }
7454 
7455 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7456   switch (Op.getOpcode()) {
7457   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7458   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7459   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7460   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7461   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7462   }
7463 
7464   return RISCVFPRndMode::Invalid;
7465 }
7466 
7467 // Fold
7468 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7469 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7470 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7471 //   (fp_to_int (fceil X))      -> fcvt X, rup
7472 //   (fp_to_int (fround X))     -> fcvt X, rmm
7473 static SDValue performFP_TO_INTCombine(SDNode *N,
7474                                        TargetLowering::DAGCombinerInfo &DCI,
7475                                        const RISCVSubtarget &Subtarget) {
7476   SelectionDAG &DAG = DCI.DAG;
7477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7478   MVT XLenVT = Subtarget.getXLenVT();
7479 
7480   // Only handle XLen or i32 types. Other types narrower than XLen will
7481   // eventually be legalized to XLenVT.
7482   EVT VT = N->getValueType(0);
7483   if (VT != MVT::i32 && VT != XLenVT)
7484     return SDValue();
7485 
7486   SDValue Src = N->getOperand(0);
7487 
7488   // Ensure the FP type is also legal.
7489   if (!TLI.isTypeLegal(Src.getValueType()))
7490     return SDValue();
7491 
7492   // Don't do this for f16 with Zfhmin and not Zfh.
7493   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7494     return SDValue();
7495 
7496   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7497   if (FRM == RISCVFPRndMode::Invalid)
7498     return SDValue();
7499 
7500   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7501 
7502   unsigned Opc;
7503   if (VT == XLenVT)
7504     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7505   else
7506     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7507 
7508   SDLoc DL(N);
7509   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7510                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7511   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7512 }
7513 
7514 // Fold
7515 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7516 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7517 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7518 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7519 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7520 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7521                                        TargetLowering::DAGCombinerInfo &DCI,
7522                                        const RISCVSubtarget &Subtarget) {
7523   SelectionDAG &DAG = DCI.DAG;
7524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7525   MVT XLenVT = Subtarget.getXLenVT();
7526 
7527   // Only handle XLen types. Other types narrower than XLen will eventually be
7528   // legalized to XLenVT.
7529   EVT DstVT = N->getValueType(0);
7530   if (DstVT != XLenVT)
7531     return SDValue();
7532 
7533   SDValue Src = N->getOperand(0);
7534 
7535   // Ensure the FP type is also legal.
7536   if (!TLI.isTypeLegal(Src.getValueType()))
7537     return SDValue();
7538 
7539   // Don't do this for f16 with Zfhmin and not Zfh.
7540   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7541     return SDValue();
7542 
7543   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7544 
7545   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7546   if (FRM == RISCVFPRndMode::Invalid)
7547     return SDValue();
7548 
7549   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7550 
7551   unsigned Opc;
7552   if (SatVT == DstVT)
7553     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7554   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7555     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7556   else
7557     return SDValue();
7558   // FIXME: Support other SatVTs by clamping before or after the conversion.
7559 
7560   Src = Src.getOperand(0);
7561 
7562   SDLoc DL(N);
7563   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7564                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7565 
7566   // RISCV FP-to-int conversions saturate to the destination register size, but
7567   // don't produce 0 for nan.
7568   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7569   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7570 }
7571 
7572 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7573                                                DAGCombinerInfo &DCI) const {
7574   SelectionDAG &DAG = DCI.DAG;
7575 
7576   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7577   // bits are demanded. N will be added to the Worklist if it was not deleted.
7578   // Caller should return SDValue(N, 0) if this returns true.
7579   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7580     SDValue Op = N->getOperand(OpNo);
7581     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7582     if (!SimplifyDemandedBits(Op, Mask, DCI))
7583       return false;
7584 
7585     if (N->getOpcode() != ISD::DELETED_NODE)
7586       DCI.AddToWorklist(N);
7587     return true;
7588   };
7589 
7590   switch (N->getOpcode()) {
7591   default:
7592     break;
7593   case RISCVISD::SplitF64: {
7594     SDValue Op0 = N->getOperand(0);
7595     // If the input to SplitF64 is just BuildPairF64 then the operation is
7596     // redundant. Instead, use BuildPairF64's operands directly.
7597     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7598       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7599 
7600     SDLoc DL(N);
7601 
7602     // It's cheaper to materialise two 32-bit integers than to load a double
7603     // from the constant pool and transfer it to integer registers through the
7604     // stack.
7605     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7606       APInt V = C->getValueAPF().bitcastToAPInt();
7607       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7608       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7609       return DCI.CombineTo(N, Lo, Hi);
7610     }
7611 
7612     // This is a target-specific version of a DAGCombine performed in
7613     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7614     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7615     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7616     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7617         !Op0.getNode()->hasOneUse())
7618       break;
7619     SDValue NewSplitF64 =
7620         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7621                     Op0.getOperand(0));
7622     SDValue Lo = NewSplitF64.getValue(0);
7623     SDValue Hi = NewSplitF64.getValue(1);
7624     APInt SignBit = APInt::getSignMask(32);
7625     if (Op0.getOpcode() == ISD::FNEG) {
7626       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7627                                   DAG.getConstant(SignBit, DL, MVT::i32));
7628       return DCI.CombineTo(N, Lo, NewHi);
7629     }
7630     assert(Op0.getOpcode() == ISD::FABS);
7631     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7632                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7633     return DCI.CombineTo(N, Lo, NewHi);
7634   }
7635   case RISCVISD::SLLW:
7636   case RISCVISD::SRAW:
7637   case RISCVISD::SRLW:
7638   case RISCVISD::ROLW:
7639   case RISCVISD::RORW: {
7640     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7641     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7642         SimplifyDemandedLowBitsHelper(1, 5))
7643       return SDValue(N, 0);
7644     break;
7645   }
7646   case RISCVISD::CLZW:
7647   case RISCVISD::CTZW: {
7648     // Only the lower 32 bits of the first operand are read
7649     if (SimplifyDemandedLowBitsHelper(0, 32))
7650       return SDValue(N, 0);
7651     break;
7652   }
7653   case RISCVISD::GREV:
7654   case RISCVISD::GORC: {
7655     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7656     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7657     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7658     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7659       return SDValue(N, 0);
7660 
7661     return combineGREVI_GORCI(N, DAG);
7662   }
7663   case RISCVISD::GREVW:
7664   case RISCVISD::GORCW: {
7665     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7666     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7667         SimplifyDemandedLowBitsHelper(1, 5))
7668       return SDValue(N, 0);
7669 
7670     return combineGREVI_GORCI(N, DAG);
7671   }
7672   case RISCVISD::SHFL:
7673   case RISCVISD::UNSHFL: {
7674     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7675     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7676     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7677     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7678       return SDValue(N, 0);
7679 
7680     break;
7681   }
7682   case RISCVISD::SHFLW:
7683   case RISCVISD::UNSHFLW: {
7684     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7685     SDValue LHS = N->getOperand(0);
7686     SDValue RHS = N->getOperand(1);
7687     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7688     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7689     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7690         SimplifyDemandedLowBitsHelper(1, 4))
7691       return SDValue(N, 0);
7692 
7693     break;
7694   }
7695   case RISCVISD::BCOMPRESSW:
7696   case RISCVISD::BDECOMPRESSW: {
7697     // Only the lower 32 bits of LHS and RHS are read.
7698     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7699         SimplifyDemandedLowBitsHelper(1, 32))
7700       return SDValue(N, 0);
7701 
7702     break;
7703   }
7704   case RISCVISD::FMV_X_ANYEXTH:
7705   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7706     SDLoc DL(N);
7707     SDValue Op0 = N->getOperand(0);
7708     MVT VT = N->getSimpleValueType(0);
7709     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7710     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7711     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7712     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7713          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7714         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7715          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7716       assert(Op0.getOperand(0).getValueType() == VT &&
7717              "Unexpected value type!");
7718       return Op0.getOperand(0);
7719     }
7720 
7721     // This is a target-specific version of a DAGCombine performed in
7722     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7723     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7724     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7725     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7726         !Op0.getNode()->hasOneUse())
7727       break;
7728     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7729     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7730     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7731     if (Op0.getOpcode() == ISD::FNEG)
7732       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7733                          DAG.getConstant(SignBit, DL, VT));
7734 
7735     assert(Op0.getOpcode() == ISD::FABS);
7736     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7737                        DAG.getConstant(~SignBit, DL, VT));
7738   }
7739   case ISD::ADD:
7740     return performADDCombine(N, DAG, Subtarget);
7741   case ISD::SUB:
7742     return performSUBCombine(N, DAG);
7743   case ISD::AND:
7744     return performANDCombine(N, DAG);
7745   case ISD::OR:
7746     return performORCombine(N, DAG, Subtarget);
7747   case ISD::XOR:
7748     return performXORCombine(N, DAG);
7749   case ISD::ANY_EXTEND:
7750     return performANY_EXTENDCombine(N, DCI, Subtarget);
7751   case ISD::ZERO_EXTEND:
7752     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7753     // type legalization. This is safe because fp_to_uint produces poison if
7754     // it overflows.
7755     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7756       SDValue Src = N->getOperand(0);
7757       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7758           isTypeLegal(Src.getOperand(0).getValueType()))
7759         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7760                            Src.getOperand(0));
7761       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7762           isTypeLegal(Src.getOperand(1).getValueType())) {
7763         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7764         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7765                                   Src.getOperand(0), Src.getOperand(1));
7766         DCI.CombineTo(N, Res);
7767         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7768         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7769         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7770       }
7771     }
7772     return SDValue();
7773   case RISCVISD::SELECT_CC: {
7774     // Transform
7775     SDValue LHS = N->getOperand(0);
7776     SDValue RHS = N->getOperand(1);
7777     SDValue TrueV = N->getOperand(3);
7778     SDValue FalseV = N->getOperand(4);
7779 
7780     // If the True and False values are the same, we don't need a select_cc.
7781     if (TrueV == FalseV)
7782       return TrueV;
7783 
7784     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7785     if (!ISD::isIntEqualitySetCC(CCVal))
7786       break;
7787 
7788     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7789     //      (select_cc X, Y, lt, trueV, falseV)
7790     // Sometimes the setcc is introduced after select_cc has been formed.
7791     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7792         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7793       // If we're looking for eq 0 instead of ne 0, we need to invert the
7794       // condition.
7795       bool Invert = CCVal == ISD::SETEQ;
7796       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7797       if (Invert)
7798         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7799 
7800       SDLoc DL(N);
7801       RHS = LHS.getOperand(1);
7802       LHS = LHS.getOperand(0);
7803       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7804 
7805       SDValue TargetCC = DAG.getCondCode(CCVal);
7806       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7807                          {LHS, RHS, TargetCC, TrueV, FalseV});
7808     }
7809 
7810     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7811     //      (select_cc X, Y, eq/ne, trueV, falseV)
7812     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7813       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7814                          {LHS.getOperand(0), LHS.getOperand(1),
7815                           N->getOperand(2), TrueV, FalseV});
7816     // (select_cc X, 1, setne, trueV, falseV) ->
7817     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7818     // This can occur when legalizing some floating point comparisons.
7819     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7820     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7821       SDLoc DL(N);
7822       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7823       SDValue TargetCC = DAG.getCondCode(CCVal);
7824       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7825       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7826                          {LHS, RHS, TargetCC, TrueV, FalseV});
7827     }
7828 
7829     break;
7830   }
7831   case RISCVISD::BR_CC: {
7832     SDValue LHS = N->getOperand(1);
7833     SDValue RHS = N->getOperand(2);
7834     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7835     if (!ISD::isIntEqualitySetCC(CCVal))
7836       break;
7837 
7838     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7839     //      (br_cc X, Y, lt, dest)
7840     // Sometimes the setcc is introduced after br_cc has been formed.
7841     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7842         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7843       // If we're looking for eq 0 instead of ne 0, we need to invert the
7844       // condition.
7845       bool Invert = CCVal == ISD::SETEQ;
7846       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7847       if (Invert)
7848         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7849 
7850       SDLoc DL(N);
7851       RHS = LHS.getOperand(1);
7852       LHS = LHS.getOperand(0);
7853       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7854 
7855       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7856                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7857                          N->getOperand(4));
7858     }
7859 
7860     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7861     //      (br_cc X, Y, eq/ne, trueV, falseV)
7862     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7863       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7864                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7865                          N->getOperand(3), N->getOperand(4));
7866 
7867     // (br_cc X, 1, setne, br_cc) ->
7868     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7869     // This can occur when legalizing some floating point comparisons.
7870     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7871     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7872       SDLoc DL(N);
7873       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7874       SDValue TargetCC = DAG.getCondCode(CCVal);
7875       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7876       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7877                          N->getOperand(0), LHS, RHS, TargetCC,
7878                          N->getOperand(4));
7879     }
7880     break;
7881   }
7882   case ISD::FP_TO_SINT:
7883   case ISD::FP_TO_UINT:
7884     return performFP_TO_INTCombine(N, DCI, Subtarget);
7885   case ISD::FP_TO_SINT_SAT:
7886   case ISD::FP_TO_UINT_SAT:
7887     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
7888   case ISD::FCOPYSIGN: {
7889     EVT VT = N->getValueType(0);
7890     if (!VT.isVector())
7891       break;
7892     // There is a form of VFSGNJ which injects the negated sign of its second
7893     // operand. Try and bubble any FNEG up after the extend/round to produce
7894     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7895     // TRUNC=1.
7896     SDValue In2 = N->getOperand(1);
7897     // Avoid cases where the extend/round has multiple uses, as duplicating
7898     // those is typically more expensive than removing a fneg.
7899     if (!In2.hasOneUse())
7900       break;
7901     if (In2.getOpcode() != ISD::FP_EXTEND &&
7902         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7903       break;
7904     In2 = In2.getOperand(0);
7905     if (In2.getOpcode() != ISD::FNEG)
7906       break;
7907     SDLoc DL(N);
7908     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7909     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7910                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7911   }
7912   case ISD::MGATHER:
7913   case ISD::MSCATTER:
7914   case ISD::VP_GATHER:
7915   case ISD::VP_SCATTER: {
7916     if (!DCI.isBeforeLegalize())
7917       break;
7918     SDValue Index, ScaleOp;
7919     bool IsIndexScaled = false;
7920     bool IsIndexSigned = false;
7921     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7922       Index = VPGSN->getIndex();
7923       ScaleOp = VPGSN->getScale();
7924       IsIndexScaled = VPGSN->isIndexScaled();
7925       IsIndexSigned = VPGSN->isIndexSigned();
7926     } else {
7927       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7928       Index = MGSN->getIndex();
7929       ScaleOp = MGSN->getScale();
7930       IsIndexScaled = MGSN->isIndexScaled();
7931       IsIndexSigned = MGSN->isIndexSigned();
7932     }
7933     EVT IndexVT = Index.getValueType();
7934     MVT XLenVT = Subtarget.getXLenVT();
7935     // RISCV indexed loads only support the "unsigned unscaled" addressing
7936     // mode, so anything else must be manually legalized.
7937     bool NeedsIdxLegalization =
7938         IsIndexScaled ||
7939         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7940     if (!NeedsIdxLegalization)
7941       break;
7942 
7943     SDLoc DL(N);
7944 
7945     // Any index legalization should first promote to XLenVT, so we don't lose
7946     // bits when scaling. This may create an illegal index type so we let
7947     // LLVM's legalization take care of the splitting.
7948     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7949     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7950       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7951       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7952                           DL, IndexVT, Index);
7953     }
7954 
7955     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7956     if (IsIndexScaled && Scale != 1) {
7957       // Manually scale the indices by the element size.
7958       // TODO: Sanitize the scale operand here?
7959       // TODO: For VP nodes, should we use VP_SHL here?
7960       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7961       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7962       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7963     }
7964 
7965     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7966     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7967       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7968                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7969                               VPGN->getScale(), VPGN->getMask(),
7970                               VPGN->getVectorLength()},
7971                              VPGN->getMemOperand(), NewIndexTy);
7972     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7973       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7974                               {VPSN->getChain(), VPSN->getValue(),
7975                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7976                                VPSN->getMask(), VPSN->getVectorLength()},
7977                               VPSN->getMemOperand(), NewIndexTy);
7978     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7979       return DAG.getMaskedGather(
7980           N->getVTList(), MGN->getMemoryVT(), DL,
7981           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7982            MGN->getBasePtr(), Index, MGN->getScale()},
7983           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7984     const auto *MSN = cast<MaskedScatterSDNode>(N);
7985     return DAG.getMaskedScatter(
7986         N->getVTList(), MSN->getMemoryVT(), DL,
7987         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7988          Index, MSN->getScale()},
7989         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7990   }
7991   case RISCVISD::SRA_VL:
7992   case RISCVISD::SRL_VL:
7993   case RISCVISD::SHL_VL: {
7994     SDValue ShAmt = N->getOperand(1);
7995     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
7996       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
7997       SDLoc DL(N);
7998       SDValue VL = N->getOperand(3);
7999       EVT VT = N->getValueType(0);
8000       ShAmt =
8001           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
8002       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8003                          N->getOperand(2), N->getOperand(3));
8004     }
8005     break;
8006   }
8007   case ISD::SRA:
8008   case ISD::SRL:
8009   case ISD::SHL: {
8010     SDValue ShAmt = N->getOperand(1);
8011     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8012       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8013       SDLoc DL(N);
8014       EVT VT = N->getValueType(0);
8015       ShAmt =
8016           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
8017       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8018     }
8019     break;
8020   }
8021   case RISCVISD::MUL_VL:
8022     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8023       return V;
8024     // Mul is commutative.
8025     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8026   case ISD::STORE: {
8027     auto *Store = cast<StoreSDNode>(N);
8028     SDValue Val = Store->getValue();
8029     // Combine store of vmv.x.s to vse with VL of 1.
8030     // FIXME: Support FP.
8031     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8032       SDValue Src = Val.getOperand(0);
8033       EVT VecVT = Src.getValueType();
8034       EVT MemVT = Store->getMemoryVT();
8035       // The memory VT and the element type must match.
8036       if (VecVT.getVectorElementType() == MemVT) {
8037         SDLoc DL(N);
8038         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8039         return DAG.getStoreVP(
8040             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8041             DAG.getConstant(1, DL, MaskVT),
8042             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8043             Store->getMemOperand(), Store->getAddressingMode(),
8044             Store->isTruncatingStore(), /*IsCompress*/ false);
8045       }
8046     }
8047 
8048     break;
8049   }
8050   }
8051 
8052   return SDValue();
8053 }
8054 
8055 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8056     const SDNode *N, CombineLevel Level) const {
8057   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8058   // materialised in fewer instructions than `(OP _, c1)`:
8059   //
8060   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8061   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8062   SDValue N0 = N->getOperand(0);
8063   EVT Ty = N0.getValueType();
8064   if (Ty.isScalarInteger() &&
8065       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8066     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8067     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8068     if (C1 && C2) {
8069       const APInt &C1Int = C1->getAPIntValue();
8070       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8071 
8072       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8073       // and the combine should happen, to potentially allow further combines
8074       // later.
8075       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8076           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8077         return true;
8078 
8079       // We can materialise `c1` in an add immediate, so it's "free", and the
8080       // combine should be prevented.
8081       if (C1Int.getMinSignedBits() <= 64 &&
8082           isLegalAddImmediate(C1Int.getSExtValue()))
8083         return false;
8084 
8085       // Neither constant will fit into an immediate, so find materialisation
8086       // costs.
8087       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8088                                               Subtarget.getFeatureBits(),
8089                                               /*CompressionCost*/true);
8090       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8091           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8092           /*CompressionCost*/true);
8093 
8094       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8095       // combine should be prevented.
8096       if (C1Cost < ShiftedC1Cost)
8097         return false;
8098     }
8099   }
8100   return true;
8101 }
8102 
8103 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8104     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8105     TargetLoweringOpt &TLO) const {
8106   // Delay this optimization as late as possible.
8107   if (!TLO.LegalOps)
8108     return false;
8109 
8110   EVT VT = Op.getValueType();
8111   if (VT.isVector())
8112     return false;
8113 
8114   // Only handle AND for now.
8115   if (Op.getOpcode() != ISD::AND)
8116     return false;
8117 
8118   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8119   if (!C)
8120     return false;
8121 
8122   const APInt &Mask = C->getAPIntValue();
8123 
8124   // Clear all non-demanded bits initially.
8125   APInt ShrunkMask = Mask & DemandedBits;
8126 
8127   // Try to make a smaller immediate by setting undemanded bits.
8128 
8129   APInt ExpandedMask = Mask | ~DemandedBits;
8130 
8131   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8132     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8133   };
8134   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8135     if (NewMask == Mask)
8136       return true;
8137     SDLoc DL(Op);
8138     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8139     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8140     return TLO.CombineTo(Op, NewOp);
8141   };
8142 
8143   // If the shrunk mask fits in sign extended 12 bits, let the target
8144   // independent code apply it.
8145   if (ShrunkMask.isSignedIntN(12))
8146     return false;
8147 
8148   // Preserve (and X, 0xffff) when zext.h is supported.
8149   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8150     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8151     if (IsLegalMask(NewMask))
8152       return UseMask(NewMask);
8153   }
8154 
8155   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8156   if (VT == MVT::i64) {
8157     APInt NewMask = APInt(64, 0xffffffff);
8158     if (IsLegalMask(NewMask))
8159       return UseMask(NewMask);
8160   }
8161 
8162   // For the remaining optimizations, we need to be able to make a negative
8163   // number through a combination of mask and undemanded bits.
8164   if (!ExpandedMask.isNegative())
8165     return false;
8166 
8167   // What is the fewest number of bits we need to represent the negative number.
8168   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8169 
8170   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8171   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8172   APInt NewMask = ShrunkMask;
8173   if (MinSignedBits <= 12)
8174     NewMask.setBitsFrom(11);
8175   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8176     NewMask.setBitsFrom(31);
8177   else
8178     return false;
8179 
8180   // Check that our new mask is a subset of the demanded mask.
8181   assert(IsLegalMask(NewMask));
8182   return UseMask(NewMask);
8183 }
8184 
8185 static void computeGREV(APInt &Src, unsigned ShAmt) {
8186   ShAmt &= Src.getBitWidth() - 1;
8187   uint64_t x = Src.getZExtValue();
8188   if (ShAmt & 1)
8189     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8190   if (ShAmt & 2)
8191     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8192   if (ShAmt & 4)
8193     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8194   if (ShAmt & 8)
8195     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8196   if (ShAmt & 16)
8197     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8198   if (ShAmt & 32)
8199     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8200   Src = x;
8201 }
8202 
8203 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8204                                                         KnownBits &Known,
8205                                                         const APInt &DemandedElts,
8206                                                         const SelectionDAG &DAG,
8207                                                         unsigned Depth) const {
8208   unsigned BitWidth = Known.getBitWidth();
8209   unsigned Opc = Op.getOpcode();
8210   assert((Opc >= ISD::BUILTIN_OP_END ||
8211           Opc == ISD::INTRINSIC_WO_CHAIN ||
8212           Opc == ISD::INTRINSIC_W_CHAIN ||
8213           Opc == ISD::INTRINSIC_VOID) &&
8214          "Should use MaskedValueIsZero if you don't know whether Op"
8215          " is a target node!");
8216 
8217   Known.resetAll();
8218   switch (Opc) {
8219   default: break;
8220   case RISCVISD::SELECT_CC: {
8221     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8222     // If we don't know any bits, early out.
8223     if (Known.isUnknown())
8224       break;
8225     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8226 
8227     // Only known if known in both the LHS and RHS.
8228     Known = KnownBits::commonBits(Known, Known2);
8229     break;
8230   }
8231   case RISCVISD::REMUW: {
8232     KnownBits Known2;
8233     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8234     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8235     // We only care about the lower 32 bits.
8236     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8237     // Restore the original width by sign extending.
8238     Known = Known.sext(BitWidth);
8239     break;
8240   }
8241   case RISCVISD::DIVUW: {
8242     KnownBits Known2;
8243     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8244     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8245     // We only care about the lower 32 bits.
8246     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8247     // Restore the original width by sign extending.
8248     Known = Known.sext(BitWidth);
8249     break;
8250   }
8251   case RISCVISD::CTZW: {
8252     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8253     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8254     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8255     Known.Zero.setBitsFrom(LowBits);
8256     break;
8257   }
8258   case RISCVISD::CLZW: {
8259     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8260     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8261     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8262     Known.Zero.setBitsFrom(LowBits);
8263     break;
8264   }
8265   case RISCVISD::GREV:
8266   case RISCVISD::GREVW: {
8267     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8268       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8269       if (Opc == RISCVISD::GREVW)
8270         Known = Known.trunc(32);
8271       unsigned ShAmt = C->getZExtValue();
8272       computeGREV(Known.Zero, ShAmt);
8273       computeGREV(Known.One, ShAmt);
8274       if (Opc == RISCVISD::GREVW)
8275         Known = Known.sext(BitWidth);
8276     }
8277     break;
8278   }
8279   case RISCVISD::READ_VLENB: {
8280     // If we know the minimum VLen from Zvl extensions, we can use that to
8281     // determine the trailing zeros of VLENB.
8282     // FIXME: Limit to 128 bit vectors until we have more testing.
8283     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8284     if (MinVLenB > 0)
8285       Known.Zero.setLowBits(Log2_32(MinVLenB));
8286     // We assume VLENB is no more than 65536 / 8 bytes.
8287     Known.Zero.setBitsFrom(14);
8288     break;
8289   }
8290   case ISD::INTRINSIC_W_CHAIN:
8291   case ISD::INTRINSIC_WO_CHAIN: {
8292     unsigned IntNo =
8293         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8294     switch (IntNo) {
8295     default:
8296       // We can't do anything for most intrinsics.
8297       break;
8298     case Intrinsic::riscv_vsetvli:
8299     case Intrinsic::riscv_vsetvlimax:
8300     case Intrinsic::riscv_vsetvli_opt:
8301     case Intrinsic::riscv_vsetvlimax_opt:
8302       // Assume that VL output is positive and would fit in an int32_t.
8303       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8304       if (BitWidth >= 32)
8305         Known.Zero.setBitsFrom(31);
8306       break;
8307     }
8308     break;
8309   }
8310   }
8311 }
8312 
8313 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8314     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8315     unsigned Depth) const {
8316   switch (Op.getOpcode()) {
8317   default:
8318     break;
8319   case RISCVISD::SELECT_CC: {
8320     unsigned Tmp =
8321         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8322     if (Tmp == 1) return 1;  // Early out.
8323     unsigned Tmp2 =
8324         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8325     return std::min(Tmp, Tmp2);
8326   }
8327   case RISCVISD::SLLW:
8328   case RISCVISD::SRAW:
8329   case RISCVISD::SRLW:
8330   case RISCVISD::DIVW:
8331   case RISCVISD::DIVUW:
8332   case RISCVISD::REMUW:
8333   case RISCVISD::ROLW:
8334   case RISCVISD::RORW:
8335   case RISCVISD::GREVW:
8336   case RISCVISD::GORCW:
8337   case RISCVISD::FSLW:
8338   case RISCVISD::FSRW:
8339   case RISCVISD::SHFLW:
8340   case RISCVISD::UNSHFLW:
8341   case RISCVISD::BCOMPRESSW:
8342   case RISCVISD::BDECOMPRESSW:
8343   case RISCVISD::BFPW:
8344   case RISCVISD::FCVT_W_RV64:
8345   case RISCVISD::FCVT_WU_RV64:
8346   case RISCVISD::STRICT_FCVT_W_RV64:
8347   case RISCVISD::STRICT_FCVT_WU_RV64:
8348     // TODO: As the result is sign-extended, this is conservatively correct. A
8349     // more precise answer could be calculated for SRAW depending on known
8350     // bits in the shift amount.
8351     return 33;
8352   case RISCVISD::SHFL:
8353   case RISCVISD::UNSHFL: {
8354     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8355     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8356     // will stay within the upper 32 bits. If there were more than 32 sign bits
8357     // before there will be at least 33 sign bits after.
8358     if (Op.getValueType() == MVT::i64 &&
8359         isa<ConstantSDNode>(Op.getOperand(1)) &&
8360         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8361       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8362       if (Tmp > 32)
8363         return 33;
8364     }
8365     break;
8366   }
8367   case RISCVISD::VMV_X_S: {
8368     // The number of sign bits of the scalar result is computed by obtaining the
8369     // element type of the input vector operand, subtracting its width from the
8370     // XLEN, and then adding one (sign bit within the element type). If the
8371     // element type is wider than XLen, the least-significant XLEN bits are
8372     // taken.
8373     unsigned XLen = Subtarget.getXLen();
8374     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8375     if (EltBits <= XLen)
8376       return XLen - EltBits + 1;
8377     break;
8378   }
8379   }
8380 
8381   return 1;
8382 }
8383 
8384 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8385                                                   MachineBasicBlock *BB) {
8386   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8387 
8388   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8389   // Should the count have wrapped while it was being read, we need to try
8390   // again.
8391   // ...
8392   // read:
8393   // rdcycleh x3 # load high word of cycle
8394   // rdcycle  x2 # load low word of cycle
8395   // rdcycleh x4 # load high word of cycle
8396   // bne x3, x4, read # check if high word reads match, otherwise try again
8397   // ...
8398 
8399   MachineFunction &MF = *BB->getParent();
8400   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8401   MachineFunction::iterator It = ++BB->getIterator();
8402 
8403   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8404   MF.insert(It, LoopMBB);
8405 
8406   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8407   MF.insert(It, DoneMBB);
8408 
8409   // Transfer the remainder of BB and its successor edges to DoneMBB.
8410   DoneMBB->splice(DoneMBB->begin(), BB,
8411                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8412   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8413 
8414   BB->addSuccessor(LoopMBB);
8415 
8416   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8417   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8418   Register LoReg = MI.getOperand(0).getReg();
8419   Register HiReg = MI.getOperand(1).getReg();
8420   DebugLoc DL = MI.getDebugLoc();
8421 
8422   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8423   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8424       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8425       .addReg(RISCV::X0);
8426   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8427       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8428       .addReg(RISCV::X0);
8429   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8430       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8431       .addReg(RISCV::X0);
8432 
8433   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8434       .addReg(HiReg)
8435       .addReg(ReadAgainReg)
8436       .addMBB(LoopMBB);
8437 
8438   LoopMBB->addSuccessor(LoopMBB);
8439   LoopMBB->addSuccessor(DoneMBB);
8440 
8441   MI.eraseFromParent();
8442 
8443   return DoneMBB;
8444 }
8445 
8446 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8447                                              MachineBasicBlock *BB) {
8448   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8449 
8450   MachineFunction &MF = *BB->getParent();
8451   DebugLoc DL = MI.getDebugLoc();
8452   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8453   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8454   Register LoReg = MI.getOperand(0).getReg();
8455   Register HiReg = MI.getOperand(1).getReg();
8456   Register SrcReg = MI.getOperand(2).getReg();
8457   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8458   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8459 
8460   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8461                           RI);
8462   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8463   MachineMemOperand *MMOLo =
8464       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8465   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8466       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8467   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8468       .addFrameIndex(FI)
8469       .addImm(0)
8470       .addMemOperand(MMOLo);
8471   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8472       .addFrameIndex(FI)
8473       .addImm(4)
8474       .addMemOperand(MMOHi);
8475   MI.eraseFromParent(); // The pseudo instruction is gone now.
8476   return BB;
8477 }
8478 
8479 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8480                                                  MachineBasicBlock *BB) {
8481   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8482          "Unexpected instruction");
8483 
8484   MachineFunction &MF = *BB->getParent();
8485   DebugLoc DL = MI.getDebugLoc();
8486   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8487   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8488   Register DstReg = MI.getOperand(0).getReg();
8489   Register LoReg = MI.getOperand(1).getReg();
8490   Register HiReg = MI.getOperand(2).getReg();
8491   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8492   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8493 
8494   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8495   MachineMemOperand *MMOLo =
8496       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8497   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8498       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8499   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8500       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8501       .addFrameIndex(FI)
8502       .addImm(0)
8503       .addMemOperand(MMOLo);
8504   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8505       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8506       .addFrameIndex(FI)
8507       .addImm(4)
8508       .addMemOperand(MMOHi);
8509   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8510   MI.eraseFromParent(); // The pseudo instruction is gone now.
8511   return BB;
8512 }
8513 
8514 static bool isSelectPseudo(MachineInstr &MI) {
8515   switch (MI.getOpcode()) {
8516   default:
8517     return false;
8518   case RISCV::Select_GPR_Using_CC_GPR:
8519   case RISCV::Select_FPR16_Using_CC_GPR:
8520   case RISCV::Select_FPR32_Using_CC_GPR:
8521   case RISCV::Select_FPR64_Using_CC_GPR:
8522     return true;
8523   }
8524 }
8525 
8526 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8527                                         unsigned RelOpcode, unsigned EqOpcode,
8528                                         const RISCVSubtarget &Subtarget) {
8529   DebugLoc DL = MI.getDebugLoc();
8530   Register DstReg = MI.getOperand(0).getReg();
8531   Register Src1Reg = MI.getOperand(1).getReg();
8532   Register Src2Reg = MI.getOperand(2).getReg();
8533   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8534   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8535   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8536 
8537   // Save the current FFLAGS.
8538   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8539 
8540   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8541                  .addReg(Src1Reg)
8542                  .addReg(Src2Reg);
8543   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8544     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8545 
8546   // Restore the FFLAGS.
8547   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8548       .addReg(SavedFFlags, RegState::Kill);
8549 
8550   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8551   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8552                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8553                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8554   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8555     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8556 
8557   // Erase the pseudoinstruction.
8558   MI.eraseFromParent();
8559   return BB;
8560 }
8561 
8562 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8563                                            MachineBasicBlock *BB,
8564                                            const RISCVSubtarget &Subtarget) {
8565   // To "insert" Select_* instructions, we actually have to insert the triangle
8566   // control-flow pattern.  The incoming instructions know the destination vreg
8567   // to set, the condition code register to branch on, the true/false values to
8568   // select between, and the condcode to use to select the appropriate branch.
8569   //
8570   // We produce the following control flow:
8571   //     HeadMBB
8572   //     |  \
8573   //     |  IfFalseMBB
8574   //     | /
8575   //    TailMBB
8576   //
8577   // When we find a sequence of selects we attempt to optimize their emission
8578   // by sharing the control flow. Currently we only handle cases where we have
8579   // multiple selects with the exact same condition (same LHS, RHS and CC).
8580   // The selects may be interleaved with other instructions if the other
8581   // instructions meet some requirements we deem safe:
8582   // - They are debug instructions. Otherwise,
8583   // - They do not have side-effects, do not access memory and their inputs do
8584   //   not depend on the results of the select pseudo-instructions.
8585   // The TrueV/FalseV operands of the selects cannot depend on the result of
8586   // previous selects in the sequence.
8587   // These conditions could be further relaxed. See the X86 target for a
8588   // related approach and more information.
8589   Register LHS = MI.getOperand(1).getReg();
8590   Register RHS = MI.getOperand(2).getReg();
8591   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8592 
8593   SmallVector<MachineInstr *, 4> SelectDebugValues;
8594   SmallSet<Register, 4> SelectDests;
8595   SelectDests.insert(MI.getOperand(0).getReg());
8596 
8597   MachineInstr *LastSelectPseudo = &MI;
8598 
8599   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8600        SequenceMBBI != E; ++SequenceMBBI) {
8601     if (SequenceMBBI->isDebugInstr())
8602       continue;
8603     else if (isSelectPseudo(*SequenceMBBI)) {
8604       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8605           SequenceMBBI->getOperand(2).getReg() != RHS ||
8606           SequenceMBBI->getOperand(3).getImm() != CC ||
8607           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8608           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8609         break;
8610       LastSelectPseudo = &*SequenceMBBI;
8611       SequenceMBBI->collectDebugValues(SelectDebugValues);
8612       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8613     } else {
8614       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8615           SequenceMBBI->mayLoadOrStore())
8616         break;
8617       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8618             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8619           }))
8620         break;
8621     }
8622   }
8623 
8624   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8625   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8626   DebugLoc DL = MI.getDebugLoc();
8627   MachineFunction::iterator I = ++BB->getIterator();
8628 
8629   MachineBasicBlock *HeadMBB = BB;
8630   MachineFunction *F = BB->getParent();
8631   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8632   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8633 
8634   F->insert(I, IfFalseMBB);
8635   F->insert(I, TailMBB);
8636 
8637   // Transfer debug instructions associated with the selects to TailMBB.
8638   for (MachineInstr *DebugInstr : SelectDebugValues) {
8639     TailMBB->push_back(DebugInstr->removeFromParent());
8640   }
8641 
8642   // Move all instructions after the sequence to TailMBB.
8643   TailMBB->splice(TailMBB->end(), HeadMBB,
8644                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8645   // Update machine-CFG edges by transferring all successors of the current
8646   // block to the new block which will contain the Phi nodes for the selects.
8647   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8648   // Set the successors for HeadMBB.
8649   HeadMBB->addSuccessor(IfFalseMBB);
8650   HeadMBB->addSuccessor(TailMBB);
8651 
8652   // Insert appropriate branch.
8653   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8654     .addReg(LHS)
8655     .addReg(RHS)
8656     .addMBB(TailMBB);
8657 
8658   // IfFalseMBB just falls through to TailMBB.
8659   IfFalseMBB->addSuccessor(TailMBB);
8660 
8661   // Create PHIs for all of the select pseudo-instructions.
8662   auto SelectMBBI = MI.getIterator();
8663   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8664   auto InsertionPoint = TailMBB->begin();
8665   while (SelectMBBI != SelectEnd) {
8666     auto Next = std::next(SelectMBBI);
8667     if (isSelectPseudo(*SelectMBBI)) {
8668       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8669       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8670               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8671           .addReg(SelectMBBI->getOperand(4).getReg())
8672           .addMBB(HeadMBB)
8673           .addReg(SelectMBBI->getOperand(5).getReg())
8674           .addMBB(IfFalseMBB);
8675       SelectMBBI->eraseFromParent();
8676     }
8677     SelectMBBI = Next;
8678   }
8679 
8680   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8681   return TailMBB;
8682 }
8683 
8684 MachineBasicBlock *
8685 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8686                                                  MachineBasicBlock *BB) const {
8687   switch (MI.getOpcode()) {
8688   default:
8689     llvm_unreachable("Unexpected instr type to insert");
8690   case RISCV::ReadCycleWide:
8691     assert(!Subtarget.is64Bit() &&
8692            "ReadCycleWrite is only to be used on riscv32");
8693     return emitReadCycleWidePseudo(MI, BB);
8694   case RISCV::Select_GPR_Using_CC_GPR:
8695   case RISCV::Select_FPR16_Using_CC_GPR:
8696   case RISCV::Select_FPR32_Using_CC_GPR:
8697   case RISCV::Select_FPR64_Using_CC_GPR:
8698     return emitSelectPseudo(MI, BB, Subtarget);
8699   case RISCV::BuildPairF64Pseudo:
8700     return emitBuildPairF64Pseudo(MI, BB);
8701   case RISCV::SplitF64Pseudo:
8702     return emitSplitF64Pseudo(MI, BB);
8703   case RISCV::PseudoQuietFLE_H:
8704     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8705   case RISCV::PseudoQuietFLT_H:
8706     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8707   case RISCV::PseudoQuietFLE_S:
8708     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8709   case RISCV::PseudoQuietFLT_S:
8710     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8711   case RISCV::PseudoQuietFLE_D:
8712     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8713   case RISCV::PseudoQuietFLT_D:
8714     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8715   }
8716 }
8717 
8718 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8719                                                         SDNode *Node) const {
8720   // Add FRM dependency to any instructions with dynamic rounding mode.
8721   unsigned Opc = MI.getOpcode();
8722   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8723   if (Idx < 0)
8724     return;
8725   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8726     return;
8727   // If the instruction already reads FRM, don't add another read.
8728   if (MI.readsRegister(RISCV::FRM))
8729     return;
8730   MI.addOperand(
8731       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8732 }
8733 
8734 // Calling Convention Implementation.
8735 // The expectations for frontend ABI lowering vary from target to target.
8736 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8737 // details, but this is a longer term goal. For now, we simply try to keep the
8738 // role of the frontend as simple and well-defined as possible. The rules can
8739 // be summarised as:
8740 // * Never split up large scalar arguments. We handle them here.
8741 // * If a hardfloat calling convention is being used, and the struct may be
8742 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8743 // available, then pass as two separate arguments. If either the GPRs or FPRs
8744 // are exhausted, then pass according to the rule below.
8745 // * If a struct could never be passed in registers or directly in a stack
8746 // slot (as it is larger than 2*XLEN and the floating point rules don't
8747 // apply), then pass it using a pointer with the byval attribute.
8748 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8749 // word-sized array or a 2*XLEN scalar (depending on alignment).
8750 // * The frontend can determine whether a struct is returned by reference or
8751 // not based on its size and fields. If it will be returned by reference, the
8752 // frontend must modify the prototype so a pointer with the sret annotation is
8753 // passed as the first argument. This is not necessary for large scalar
8754 // returns.
8755 // * Struct return values and varargs should be coerced to structs containing
8756 // register-size fields in the same situations they would be for fixed
8757 // arguments.
8758 
8759 static const MCPhysReg ArgGPRs[] = {
8760   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8761   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8762 };
8763 static const MCPhysReg ArgFPR16s[] = {
8764   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8765   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8766 };
8767 static const MCPhysReg ArgFPR32s[] = {
8768   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8769   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8770 };
8771 static const MCPhysReg ArgFPR64s[] = {
8772   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8773   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8774 };
8775 // This is an interim calling convention and it may be changed in the future.
8776 static const MCPhysReg ArgVRs[] = {
8777     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8778     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8779     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8780 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8781                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8782                                      RISCV::V20M2, RISCV::V22M2};
8783 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8784                                      RISCV::V20M4};
8785 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8786 
8787 // Pass a 2*XLEN argument that has been split into two XLEN values through
8788 // registers or the stack as necessary.
8789 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8790                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8791                                 MVT ValVT2, MVT LocVT2,
8792                                 ISD::ArgFlagsTy ArgFlags2) {
8793   unsigned XLenInBytes = XLen / 8;
8794   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8795     // At least one half can be passed via register.
8796     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8797                                      VA1.getLocVT(), CCValAssign::Full));
8798   } else {
8799     // Both halves must be passed on the stack, with proper alignment.
8800     Align StackAlign =
8801         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8802     State.addLoc(
8803         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8804                             State.AllocateStack(XLenInBytes, StackAlign),
8805                             VA1.getLocVT(), CCValAssign::Full));
8806     State.addLoc(CCValAssign::getMem(
8807         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8808         LocVT2, CCValAssign::Full));
8809     return false;
8810   }
8811 
8812   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8813     // The second half can also be passed via register.
8814     State.addLoc(
8815         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8816   } else {
8817     // The second half is passed via the stack, without additional alignment.
8818     State.addLoc(CCValAssign::getMem(
8819         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8820         LocVT2, CCValAssign::Full));
8821   }
8822 
8823   return false;
8824 }
8825 
8826 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8827                                Optional<unsigned> FirstMaskArgument,
8828                                CCState &State, const RISCVTargetLowering &TLI) {
8829   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8830   if (RC == &RISCV::VRRegClass) {
8831     // Assign the first mask argument to V0.
8832     // This is an interim calling convention and it may be changed in the
8833     // future.
8834     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8835       return State.AllocateReg(RISCV::V0);
8836     return State.AllocateReg(ArgVRs);
8837   }
8838   if (RC == &RISCV::VRM2RegClass)
8839     return State.AllocateReg(ArgVRM2s);
8840   if (RC == &RISCV::VRM4RegClass)
8841     return State.AllocateReg(ArgVRM4s);
8842   if (RC == &RISCV::VRM8RegClass)
8843     return State.AllocateReg(ArgVRM8s);
8844   llvm_unreachable("Unhandled register class for ValueType");
8845 }
8846 
8847 // Implements the RISC-V calling convention. Returns true upon failure.
8848 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8849                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8850                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8851                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8852                      Optional<unsigned> FirstMaskArgument) {
8853   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8854   assert(XLen == 32 || XLen == 64);
8855   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8856 
8857   // Any return value split in to more than two values can't be returned
8858   // directly. Vectors are returned via the available vector registers.
8859   if (!LocVT.isVector() && IsRet && ValNo > 1)
8860     return true;
8861 
8862   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8863   // variadic argument, or if no F16/F32 argument registers are available.
8864   bool UseGPRForF16_F32 = true;
8865   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8866   // variadic argument, or if no F64 argument registers are available.
8867   bool UseGPRForF64 = true;
8868 
8869   switch (ABI) {
8870   default:
8871     llvm_unreachable("Unexpected ABI");
8872   case RISCVABI::ABI_ILP32:
8873   case RISCVABI::ABI_LP64:
8874     break;
8875   case RISCVABI::ABI_ILP32F:
8876   case RISCVABI::ABI_LP64F:
8877     UseGPRForF16_F32 = !IsFixed;
8878     break;
8879   case RISCVABI::ABI_ILP32D:
8880   case RISCVABI::ABI_LP64D:
8881     UseGPRForF16_F32 = !IsFixed;
8882     UseGPRForF64 = !IsFixed;
8883     break;
8884   }
8885 
8886   // FPR16, FPR32, and FPR64 alias each other.
8887   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8888     UseGPRForF16_F32 = true;
8889     UseGPRForF64 = true;
8890   }
8891 
8892   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8893   // similar local variables rather than directly checking against the target
8894   // ABI.
8895 
8896   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8897     LocVT = XLenVT;
8898     LocInfo = CCValAssign::BCvt;
8899   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8900     LocVT = MVT::i64;
8901     LocInfo = CCValAssign::BCvt;
8902   }
8903 
8904   // If this is a variadic argument, the RISC-V calling convention requires
8905   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8906   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8907   // be used regardless of whether the original argument was split during
8908   // legalisation or not. The argument will not be passed by registers if the
8909   // original type is larger than 2*XLEN, so the register alignment rule does
8910   // not apply.
8911   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8912   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8913       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8914     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8915     // Skip 'odd' register if necessary.
8916     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8917       State.AllocateReg(ArgGPRs);
8918   }
8919 
8920   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8921   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8922       State.getPendingArgFlags();
8923 
8924   assert(PendingLocs.size() == PendingArgFlags.size() &&
8925          "PendingLocs and PendingArgFlags out of sync");
8926 
8927   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8928   // registers are exhausted.
8929   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8930     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8931            "Can't lower f64 if it is split");
8932     // Depending on available argument GPRS, f64 may be passed in a pair of
8933     // GPRs, split between a GPR and the stack, or passed completely on the
8934     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8935     // cases.
8936     Register Reg = State.AllocateReg(ArgGPRs);
8937     LocVT = MVT::i32;
8938     if (!Reg) {
8939       unsigned StackOffset = State.AllocateStack(8, Align(8));
8940       State.addLoc(
8941           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8942       return false;
8943     }
8944     if (!State.AllocateReg(ArgGPRs))
8945       State.AllocateStack(4, Align(4));
8946     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8947     return false;
8948   }
8949 
8950   // Fixed-length vectors are located in the corresponding scalable-vector
8951   // container types.
8952   if (ValVT.isFixedLengthVector())
8953     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8954 
8955   // Split arguments might be passed indirectly, so keep track of the pending
8956   // values. Split vectors are passed via a mix of registers and indirectly, so
8957   // treat them as we would any other argument.
8958   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8959     LocVT = XLenVT;
8960     LocInfo = CCValAssign::Indirect;
8961     PendingLocs.push_back(
8962         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8963     PendingArgFlags.push_back(ArgFlags);
8964     if (!ArgFlags.isSplitEnd()) {
8965       return false;
8966     }
8967   }
8968 
8969   // If the split argument only had two elements, it should be passed directly
8970   // in registers or on the stack.
8971   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8972       PendingLocs.size() <= 2) {
8973     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8974     // Apply the normal calling convention rules to the first half of the
8975     // split argument.
8976     CCValAssign VA = PendingLocs[0];
8977     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8978     PendingLocs.clear();
8979     PendingArgFlags.clear();
8980     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8981                                ArgFlags);
8982   }
8983 
8984   // Allocate to a register if possible, or else a stack slot.
8985   Register Reg;
8986   unsigned StoreSizeBytes = XLen / 8;
8987   Align StackAlign = Align(XLen / 8);
8988 
8989   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8990     Reg = State.AllocateReg(ArgFPR16s);
8991   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8992     Reg = State.AllocateReg(ArgFPR32s);
8993   else if (ValVT == MVT::f64 && !UseGPRForF64)
8994     Reg = State.AllocateReg(ArgFPR64s);
8995   else if (ValVT.isVector()) {
8996     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
8997     if (!Reg) {
8998       // For return values, the vector must be passed fully via registers or
8999       // via the stack.
9000       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9001       // but we're using all of them.
9002       if (IsRet)
9003         return true;
9004       // Try using a GPR to pass the address
9005       if ((Reg = State.AllocateReg(ArgGPRs))) {
9006         LocVT = XLenVT;
9007         LocInfo = CCValAssign::Indirect;
9008       } else if (ValVT.isScalableVector()) {
9009         LocVT = XLenVT;
9010         LocInfo = CCValAssign::Indirect;
9011       } else {
9012         // Pass fixed-length vectors on the stack.
9013         LocVT = ValVT;
9014         StoreSizeBytes = ValVT.getStoreSize();
9015         // Align vectors to their element sizes, being careful for vXi1
9016         // vectors.
9017         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9018       }
9019     }
9020   } else {
9021     Reg = State.AllocateReg(ArgGPRs);
9022   }
9023 
9024   unsigned StackOffset =
9025       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9026 
9027   // If we reach this point and PendingLocs is non-empty, we must be at the
9028   // end of a split argument that must be passed indirectly.
9029   if (!PendingLocs.empty()) {
9030     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9031     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9032 
9033     for (auto &It : PendingLocs) {
9034       if (Reg)
9035         It.convertToReg(Reg);
9036       else
9037         It.convertToMem(StackOffset);
9038       State.addLoc(It);
9039     }
9040     PendingLocs.clear();
9041     PendingArgFlags.clear();
9042     return false;
9043   }
9044 
9045   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9046           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9047          "Expected an XLenVT or vector types at this stage");
9048 
9049   if (Reg) {
9050     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9051     return false;
9052   }
9053 
9054   // When a floating-point value is passed on the stack, no bit-conversion is
9055   // needed.
9056   if (ValVT.isFloatingPoint()) {
9057     LocVT = ValVT;
9058     LocInfo = CCValAssign::Full;
9059   }
9060   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9061   return false;
9062 }
9063 
9064 template <typename ArgTy>
9065 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9066   for (const auto &ArgIdx : enumerate(Args)) {
9067     MVT ArgVT = ArgIdx.value().VT;
9068     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9069       return ArgIdx.index();
9070   }
9071   return None;
9072 }
9073 
9074 void RISCVTargetLowering::analyzeInputArgs(
9075     MachineFunction &MF, CCState &CCInfo,
9076     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9077     RISCVCCAssignFn Fn) const {
9078   unsigned NumArgs = Ins.size();
9079   FunctionType *FType = MF.getFunction().getFunctionType();
9080 
9081   Optional<unsigned> FirstMaskArgument;
9082   if (Subtarget.hasVInstructions())
9083     FirstMaskArgument = preAssignMask(Ins);
9084 
9085   for (unsigned i = 0; i != NumArgs; ++i) {
9086     MVT ArgVT = Ins[i].VT;
9087     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9088 
9089     Type *ArgTy = nullptr;
9090     if (IsRet)
9091       ArgTy = FType->getReturnType();
9092     else if (Ins[i].isOrigArg())
9093       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9094 
9095     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9096     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9097            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9098            FirstMaskArgument)) {
9099       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9100                         << EVT(ArgVT).getEVTString() << '\n');
9101       llvm_unreachable(nullptr);
9102     }
9103   }
9104 }
9105 
9106 void RISCVTargetLowering::analyzeOutputArgs(
9107     MachineFunction &MF, CCState &CCInfo,
9108     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9109     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9110   unsigned NumArgs = Outs.size();
9111 
9112   Optional<unsigned> FirstMaskArgument;
9113   if (Subtarget.hasVInstructions())
9114     FirstMaskArgument = preAssignMask(Outs);
9115 
9116   for (unsigned i = 0; i != NumArgs; i++) {
9117     MVT ArgVT = Outs[i].VT;
9118     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9119     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9120 
9121     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9122     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9123            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9124            FirstMaskArgument)) {
9125       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9126                         << EVT(ArgVT).getEVTString() << "\n");
9127       llvm_unreachable(nullptr);
9128     }
9129   }
9130 }
9131 
9132 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9133 // values.
9134 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9135                                    const CCValAssign &VA, const SDLoc &DL,
9136                                    const RISCVSubtarget &Subtarget) {
9137   switch (VA.getLocInfo()) {
9138   default:
9139     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9140   case CCValAssign::Full:
9141     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9142       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9143     break;
9144   case CCValAssign::BCvt:
9145     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9146       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9147     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9148       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9149     else
9150       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9151     break;
9152   }
9153   return Val;
9154 }
9155 
9156 // The caller is responsible for loading the full value if the argument is
9157 // passed with CCValAssign::Indirect.
9158 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9159                                 const CCValAssign &VA, const SDLoc &DL,
9160                                 const RISCVTargetLowering &TLI) {
9161   MachineFunction &MF = DAG.getMachineFunction();
9162   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9163   EVT LocVT = VA.getLocVT();
9164   SDValue Val;
9165   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9166   Register VReg = RegInfo.createVirtualRegister(RC);
9167   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9168   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9169 
9170   if (VA.getLocInfo() == CCValAssign::Indirect)
9171     return Val;
9172 
9173   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9174 }
9175 
9176 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9177                                    const CCValAssign &VA, const SDLoc &DL,
9178                                    const RISCVSubtarget &Subtarget) {
9179   EVT LocVT = VA.getLocVT();
9180 
9181   switch (VA.getLocInfo()) {
9182   default:
9183     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9184   case CCValAssign::Full:
9185     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9186       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9187     break;
9188   case CCValAssign::BCvt:
9189     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9190       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9191     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9192       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9193     else
9194       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9195     break;
9196   }
9197   return Val;
9198 }
9199 
9200 // The caller is responsible for loading the full value if the argument is
9201 // passed with CCValAssign::Indirect.
9202 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9203                                 const CCValAssign &VA, const SDLoc &DL) {
9204   MachineFunction &MF = DAG.getMachineFunction();
9205   MachineFrameInfo &MFI = MF.getFrameInfo();
9206   EVT LocVT = VA.getLocVT();
9207   EVT ValVT = VA.getValVT();
9208   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9209   if (ValVT.isScalableVector()) {
9210     // When the value is a scalable vector, we save the pointer which points to
9211     // the scalable vector value in the stack. The ValVT will be the pointer
9212     // type, instead of the scalable vector type.
9213     ValVT = LocVT;
9214   }
9215   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9216                                  /*IsImmutable=*/true);
9217   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9218   SDValue Val;
9219 
9220   ISD::LoadExtType ExtType;
9221   switch (VA.getLocInfo()) {
9222   default:
9223     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9224   case CCValAssign::Full:
9225   case CCValAssign::Indirect:
9226   case CCValAssign::BCvt:
9227     ExtType = ISD::NON_EXTLOAD;
9228     break;
9229   }
9230   Val = DAG.getExtLoad(
9231       ExtType, DL, LocVT, Chain, FIN,
9232       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9233   return Val;
9234 }
9235 
9236 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9237                                        const CCValAssign &VA, const SDLoc &DL) {
9238   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9239          "Unexpected VA");
9240   MachineFunction &MF = DAG.getMachineFunction();
9241   MachineFrameInfo &MFI = MF.getFrameInfo();
9242   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9243 
9244   if (VA.isMemLoc()) {
9245     // f64 is passed on the stack.
9246     int FI =
9247         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9248     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9249     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9250                        MachinePointerInfo::getFixedStack(MF, FI));
9251   }
9252 
9253   assert(VA.isRegLoc() && "Expected register VA assignment");
9254 
9255   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9256   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9257   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9258   SDValue Hi;
9259   if (VA.getLocReg() == RISCV::X17) {
9260     // Second half of f64 is passed on the stack.
9261     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9262     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9263     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9264                      MachinePointerInfo::getFixedStack(MF, FI));
9265   } else {
9266     // Second half of f64 is passed in another GPR.
9267     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9268     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9269     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9270   }
9271   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9272 }
9273 
9274 // FastCC has less than 1% performance improvement for some particular
9275 // benchmark. But theoretically, it may has benenfit for some cases.
9276 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9277                             unsigned ValNo, MVT ValVT, MVT LocVT,
9278                             CCValAssign::LocInfo LocInfo,
9279                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9280                             bool IsFixed, bool IsRet, Type *OrigTy,
9281                             const RISCVTargetLowering &TLI,
9282                             Optional<unsigned> FirstMaskArgument) {
9283 
9284   // X5 and X6 might be used for save-restore libcall.
9285   static const MCPhysReg GPRList[] = {
9286       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9287       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9288       RISCV::X29, RISCV::X30, RISCV::X31};
9289 
9290   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9291     if (unsigned Reg = State.AllocateReg(GPRList)) {
9292       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9293       return false;
9294     }
9295   }
9296 
9297   if (LocVT == MVT::f16) {
9298     static const MCPhysReg FPR16List[] = {
9299         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9300         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9301         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9302         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9303     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9304       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9305       return false;
9306     }
9307   }
9308 
9309   if (LocVT == MVT::f32) {
9310     static const MCPhysReg FPR32List[] = {
9311         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9312         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9313         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9314         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9315     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9316       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9317       return false;
9318     }
9319   }
9320 
9321   if (LocVT == MVT::f64) {
9322     static const MCPhysReg FPR64List[] = {
9323         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9324         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9325         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9326         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9327     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9328       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9329       return false;
9330     }
9331   }
9332 
9333   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9334     unsigned Offset4 = State.AllocateStack(4, Align(4));
9335     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9336     return false;
9337   }
9338 
9339   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9340     unsigned Offset5 = State.AllocateStack(8, Align(8));
9341     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9342     return false;
9343   }
9344 
9345   if (LocVT.isVector()) {
9346     if (unsigned Reg =
9347             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9348       // Fixed-length vectors are located in the corresponding scalable-vector
9349       // container types.
9350       if (ValVT.isFixedLengthVector())
9351         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9352       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9353     } else {
9354       // Try and pass the address via a "fast" GPR.
9355       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9356         LocInfo = CCValAssign::Indirect;
9357         LocVT = TLI.getSubtarget().getXLenVT();
9358         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9359       } else if (ValVT.isFixedLengthVector()) {
9360         auto StackAlign =
9361             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9362         unsigned StackOffset =
9363             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9364         State.addLoc(
9365             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9366       } else {
9367         // Can't pass scalable vectors on the stack.
9368         return true;
9369       }
9370     }
9371 
9372     return false;
9373   }
9374 
9375   return true; // CC didn't match.
9376 }
9377 
9378 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9379                          CCValAssign::LocInfo LocInfo,
9380                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9381 
9382   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9383     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9384     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9385     static const MCPhysReg GPRList[] = {
9386         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9387         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9388     if (unsigned Reg = State.AllocateReg(GPRList)) {
9389       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9390       return false;
9391     }
9392   }
9393 
9394   if (LocVT == MVT::f32) {
9395     // Pass in STG registers: F1, ..., F6
9396     //                        fs0 ... fs5
9397     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9398                                           RISCV::F18_F, RISCV::F19_F,
9399                                           RISCV::F20_F, RISCV::F21_F};
9400     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9401       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9402       return false;
9403     }
9404   }
9405 
9406   if (LocVT == MVT::f64) {
9407     // Pass in STG registers: D1, ..., D6
9408     //                        fs6 ... fs11
9409     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9410                                           RISCV::F24_D, RISCV::F25_D,
9411                                           RISCV::F26_D, RISCV::F27_D};
9412     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9413       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9414       return false;
9415     }
9416   }
9417 
9418   report_fatal_error("No registers left in GHC calling convention");
9419   return true;
9420 }
9421 
9422 // Transform physical registers into virtual registers.
9423 SDValue RISCVTargetLowering::LowerFormalArguments(
9424     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9425     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9426     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9427 
9428   MachineFunction &MF = DAG.getMachineFunction();
9429 
9430   switch (CallConv) {
9431   default:
9432     report_fatal_error("Unsupported calling convention");
9433   case CallingConv::C:
9434   case CallingConv::Fast:
9435     break;
9436   case CallingConv::GHC:
9437     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9438         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9439       report_fatal_error(
9440         "GHC calling convention requires the F and D instruction set extensions");
9441   }
9442 
9443   const Function &Func = MF.getFunction();
9444   if (Func.hasFnAttribute("interrupt")) {
9445     if (!Func.arg_empty())
9446       report_fatal_error(
9447         "Functions with the interrupt attribute cannot have arguments!");
9448 
9449     StringRef Kind =
9450       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9451 
9452     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9453       report_fatal_error(
9454         "Function interrupt attribute argument not supported!");
9455   }
9456 
9457   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9458   MVT XLenVT = Subtarget.getXLenVT();
9459   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9460   // Used with vargs to acumulate store chains.
9461   std::vector<SDValue> OutChains;
9462 
9463   // Assign locations to all of the incoming arguments.
9464   SmallVector<CCValAssign, 16> ArgLocs;
9465   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9466 
9467   if (CallConv == CallingConv::GHC)
9468     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9469   else
9470     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9471                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9472                                                    : CC_RISCV);
9473 
9474   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9475     CCValAssign &VA = ArgLocs[i];
9476     SDValue ArgValue;
9477     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9478     // case.
9479     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9480       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9481     else if (VA.isRegLoc())
9482       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9483     else
9484       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9485 
9486     if (VA.getLocInfo() == CCValAssign::Indirect) {
9487       // If the original argument was split and passed by reference (e.g. i128
9488       // on RV32), we need to load all parts of it here (using the same
9489       // address). Vectors may be partly split to registers and partly to the
9490       // stack, in which case the base address is partly offset and subsequent
9491       // stores are relative to that.
9492       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9493                                    MachinePointerInfo()));
9494       unsigned ArgIndex = Ins[i].OrigArgIndex;
9495       unsigned ArgPartOffset = Ins[i].PartOffset;
9496       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9497       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9498         CCValAssign &PartVA = ArgLocs[i + 1];
9499         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9500         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9501         if (PartVA.getValVT().isScalableVector())
9502           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9503         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9504         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9505                                      MachinePointerInfo()));
9506         ++i;
9507       }
9508       continue;
9509     }
9510     InVals.push_back(ArgValue);
9511   }
9512 
9513   if (IsVarArg) {
9514     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9515     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9516     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9517     MachineFrameInfo &MFI = MF.getFrameInfo();
9518     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9519     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9520 
9521     // Offset of the first variable argument from stack pointer, and size of
9522     // the vararg save area. For now, the varargs save area is either zero or
9523     // large enough to hold a0-a7.
9524     int VaArgOffset, VarArgsSaveSize;
9525 
9526     // If all registers are allocated, then all varargs must be passed on the
9527     // stack and we don't need to save any argregs.
9528     if (ArgRegs.size() == Idx) {
9529       VaArgOffset = CCInfo.getNextStackOffset();
9530       VarArgsSaveSize = 0;
9531     } else {
9532       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9533       VaArgOffset = -VarArgsSaveSize;
9534     }
9535 
9536     // Record the frame index of the first variable argument
9537     // which is a value necessary to VASTART.
9538     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9539     RVFI->setVarArgsFrameIndex(FI);
9540 
9541     // If saving an odd number of registers then create an extra stack slot to
9542     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9543     // offsets to even-numbered registered remain 2*XLEN-aligned.
9544     if (Idx % 2) {
9545       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9546       VarArgsSaveSize += XLenInBytes;
9547     }
9548 
9549     // Copy the integer registers that may have been used for passing varargs
9550     // to the vararg save area.
9551     for (unsigned I = Idx; I < ArgRegs.size();
9552          ++I, VaArgOffset += XLenInBytes) {
9553       const Register Reg = RegInfo.createVirtualRegister(RC);
9554       RegInfo.addLiveIn(ArgRegs[I], Reg);
9555       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9556       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9557       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9558       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9559                                    MachinePointerInfo::getFixedStack(MF, FI));
9560       cast<StoreSDNode>(Store.getNode())
9561           ->getMemOperand()
9562           ->setValue((Value *)nullptr);
9563       OutChains.push_back(Store);
9564     }
9565     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9566   }
9567 
9568   // All stores are grouped in one node to allow the matching between
9569   // the size of Ins and InVals. This only happens for vararg functions.
9570   if (!OutChains.empty()) {
9571     OutChains.push_back(Chain);
9572     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9573   }
9574 
9575   return Chain;
9576 }
9577 
9578 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9579 /// for tail call optimization.
9580 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9581 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9582     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9583     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9584 
9585   auto &Callee = CLI.Callee;
9586   auto CalleeCC = CLI.CallConv;
9587   auto &Outs = CLI.Outs;
9588   auto &Caller = MF.getFunction();
9589   auto CallerCC = Caller.getCallingConv();
9590 
9591   // Exception-handling functions need a special set of instructions to
9592   // indicate a return to the hardware. Tail-calling another function would
9593   // probably break this.
9594   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9595   // should be expanded as new function attributes are introduced.
9596   if (Caller.hasFnAttribute("interrupt"))
9597     return false;
9598 
9599   // Do not tail call opt if the stack is used to pass parameters.
9600   if (CCInfo.getNextStackOffset() != 0)
9601     return false;
9602 
9603   // Do not tail call opt if any parameters need to be passed indirectly.
9604   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9605   // passed indirectly. So the address of the value will be passed in a
9606   // register, or if not available, then the address is put on the stack. In
9607   // order to pass indirectly, space on the stack often needs to be allocated
9608   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9609   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9610   // are passed CCValAssign::Indirect.
9611   for (auto &VA : ArgLocs)
9612     if (VA.getLocInfo() == CCValAssign::Indirect)
9613       return false;
9614 
9615   // Do not tail call opt if either caller or callee uses struct return
9616   // semantics.
9617   auto IsCallerStructRet = Caller.hasStructRetAttr();
9618   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9619   if (IsCallerStructRet || IsCalleeStructRet)
9620     return false;
9621 
9622   // Externally-defined functions with weak linkage should not be
9623   // tail-called. The behaviour of branch instructions in this situation (as
9624   // used for tail calls) is implementation-defined, so we cannot rely on the
9625   // linker replacing the tail call with a return.
9626   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9627     const GlobalValue *GV = G->getGlobal();
9628     if (GV->hasExternalWeakLinkage())
9629       return false;
9630   }
9631 
9632   // The callee has to preserve all registers the caller needs to preserve.
9633   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9634   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9635   if (CalleeCC != CallerCC) {
9636     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9637     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9638       return false;
9639   }
9640 
9641   // Byval parameters hand the function a pointer directly into the stack area
9642   // we want to reuse during a tail call. Working around this *is* possible
9643   // but less efficient and uglier in LowerCall.
9644   for (auto &Arg : Outs)
9645     if (Arg.Flags.isByVal())
9646       return false;
9647 
9648   return true;
9649 }
9650 
9651 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9652   return DAG.getDataLayout().getPrefTypeAlign(
9653       VT.getTypeForEVT(*DAG.getContext()));
9654 }
9655 
9656 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9657 // and output parameter nodes.
9658 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9659                                        SmallVectorImpl<SDValue> &InVals) const {
9660   SelectionDAG &DAG = CLI.DAG;
9661   SDLoc &DL = CLI.DL;
9662   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9663   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9664   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9665   SDValue Chain = CLI.Chain;
9666   SDValue Callee = CLI.Callee;
9667   bool &IsTailCall = CLI.IsTailCall;
9668   CallingConv::ID CallConv = CLI.CallConv;
9669   bool IsVarArg = CLI.IsVarArg;
9670   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9671   MVT XLenVT = Subtarget.getXLenVT();
9672 
9673   MachineFunction &MF = DAG.getMachineFunction();
9674 
9675   // Analyze the operands of the call, assigning locations to each operand.
9676   SmallVector<CCValAssign, 16> ArgLocs;
9677   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9678 
9679   if (CallConv == CallingConv::GHC)
9680     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9681   else
9682     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9683                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9684                                                     : CC_RISCV);
9685 
9686   // Check if it's really possible to do a tail call.
9687   if (IsTailCall)
9688     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9689 
9690   if (IsTailCall)
9691     ++NumTailCalls;
9692   else if (CLI.CB && CLI.CB->isMustTailCall())
9693     report_fatal_error("failed to perform tail call elimination on a call "
9694                        "site marked musttail");
9695 
9696   // Get a count of how many bytes are to be pushed on the stack.
9697   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9698 
9699   // Create local copies for byval args
9700   SmallVector<SDValue, 8> ByValArgs;
9701   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9702     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9703     if (!Flags.isByVal())
9704       continue;
9705 
9706     SDValue Arg = OutVals[i];
9707     unsigned Size = Flags.getByValSize();
9708     Align Alignment = Flags.getNonZeroByValAlign();
9709 
9710     int FI =
9711         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9712     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9713     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9714 
9715     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9716                           /*IsVolatile=*/false,
9717                           /*AlwaysInline=*/false, IsTailCall,
9718                           MachinePointerInfo(), MachinePointerInfo());
9719     ByValArgs.push_back(FIPtr);
9720   }
9721 
9722   if (!IsTailCall)
9723     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9724 
9725   // Copy argument values to their designated locations.
9726   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9727   SmallVector<SDValue, 8> MemOpChains;
9728   SDValue StackPtr;
9729   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9730     CCValAssign &VA = ArgLocs[i];
9731     SDValue ArgValue = OutVals[i];
9732     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9733 
9734     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9735     bool IsF64OnRV32DSoftABI =
9736         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9737     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9738       SDValue SplitF64 = DAG.getNode(
9739           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9740       SDValue Lo = SplitF64.getValue(0);
9741       SDValue Hi = SplitF64.getValue(1);
9742 
9743       Register RegLo = VA.getLocReg();
9744       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9745 
9746       if (RegLo == RISCV::X17) {
9747         // Second half of f64 is passed on the stack.
9748         // Work out the address of the stack slot.
9749         if (!StackPtr.getNode())
9750           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9751         // Emit the store.
9752         MemOpChains.push_back(
9753             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9754       } else {
9755         // Second half of f64 is passed in another GPR.
9756         assert(RegLo < RISCV::X31 && "Invalid register pair");
9757         Register RegHigh = RegLo + 1;
9758         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9759       }
9760       continue;
9761     }
9762 
9763     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9764     // as any other MemLoc.
9765 
9766     // Promote the value if needed.
9767     // For now, only handle fully promoted and indirect arguments.
9768     if (VA.getLocInfo() == CCValAssign::Indirect) {
9769       // Store the argument in a stack slot and pass its address.
9770       Align StackAlign =
9771           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9772                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9773       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9774       // If the original argument was split (e.g. i128), we need
9775       // to store the required parts of it here (and pass just one address).
9776       // Vectors may be partly split to registers and partly to the stack, in
9777       // which case the base address is partly offset and subsequent stores are
9778       // relative to that.
9779       unsigned ArgIndex = Outs[i].OrigArgIndex;
9780       unsigned ArgPartOffset = Outs[i].PartOffset;
9781       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9782       // Calculate the total size to store. We don't have access to what we're
9783       // actually storing other than performing the loop and collecting the
9784       // info.
9785       SmallVector<std::pair<SDValue, SDValue>> Parts;
9786       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9787         SDValue PartValue = OutVals[i + 1];
9788         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9789         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9790         EVT PartVT = PartValue.getValueType();
9791         if (PartVT.isScalableVector())
9792           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9793         StoredSize += PartVT.getStoreSize();
9794         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9795         Parts.push_back(std::make_pair(PartValue, Offset));
9796         ++i;
9797       }
9798       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9799       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9800       MemOpChains.push_back(
9801           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9802                        MachinePointerInfo::getFixedStack(MF, FI)));
9803       for (const auto &Part : Parts) {
9804         SDValue PartValue = Part.first;
9805         SDValue PartOffset = Part.second;
9806         SDValue Address =
9807             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9808         MemOpChains.push_back(
9809             DAG.getStore(Chain, DL, PartValue, Address,
9810                          MachinePointerInfo::getFixedStack(MF, FI)));
9811       }
9812       ArgValue = SpillSlot;
9813     } else {
9814       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9815     }
9816 
9817     // Use local copy if it is a byval arg.
9818     if (Flags.isByVal())
9819       ArgValue = ByValArgs[j++];
9820 
9821     if (VA.isRegLoc()) {
9822       // Queue up the argument copies and emit them at the end.
9823       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9824     } else {
9825       assert(VA.isMemLoc() && "Argument not register or memory");
9826       assert(!IsTailCall && "Tail call not allowed if stack is used "
9827                             "for passing parameters");
9828 
9829       // Work out the address of the stack slot.
9830       if (!StackPtr.getNode())
9831         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9832       SDValue Address =
9833           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9834                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9835 
9836       // Emit the store.
9837       MemOpChains.push_back(
9838           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9839     }
9840   }
9841 
9842   // Join the stores, which are independent of one another.
9843   if (!MemOpChains.empty())
9844     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9845 
9846   SDValue Glue;
9847 
9848   // Build a sequence of copy-to-reg nodes, chained and glued together.
9849   for (auto &Reg : RegsToPass) {
9850     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9851     Glue = Chain.getValue(1);
9852   }
9853 
9854   // Validate that none of the argument registers have been marked as
9855   // reserved, if so report an error. Do the same for the return address if this
9856   // is not a tailcall.
9857   validateCCReservedRegs(RegsToPass, MF);
9858   if (!IsTailCall &&
9859       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9860     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9861         MF.getFunction(),
9862         "Return address register required, but has been reserved."});
9863 
9864   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9865   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9866   // split it and then direct call can be matched by PseudoCALL.
9867   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9868     const GlobalValue *GV = S->getGlobal();
9869 
9870     unsigned OpFlags = RISCVII::MO_CALL;
9871     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9872       OpFlags = RISCVII::MO_PLT;
9873 
9874     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9875   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9876     unsigned OpFlags = RISCVII::MO_CALL;
9877 
9878     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9879                                                  nullptr))
9880       OpFlags = RISCVII::MO_PLT;
9881 
9882     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9883   }
9884 
9885   // The first call operand is the chain and the second is the target address.
9886   SmallVector<SDValue, 8> Ops;
9887   Ops.push_back(Chain);
9888   Ops.push_back(Callee);
9889 
9890   // Add argument registers to the end of the list so that they are
9891   // known live into the call.
9892   for (auto &Reg : RegsToPass)
9893     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9894 
9895   if (!IsTailCall) {
9896     // Add a register mask operand representing the call-preserved registers.
9897     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9898     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9899     assert(Mask && "Missing call preserved mask for calling convention");
9900     Ops.push_back(DAG.getRegisterMask(Mask));
9901   }
9902 
9903   // Glue the call to the argument copies, if any.
9904   if (Glue.getNode())
9905     Ops.push_back(Glue);
9906 
9907   // Emit the call.
9908   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9909 
9910   if (IsTailCall) {
9911     MF.getFrameInfo().setHasTailCall();
9912     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9913   }
9914 
9915   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9916   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9917   Glue = Chain.getValue(1);
9918 
9919   // Mark the end of the call, which is glued to the call itself.
9920   Chain = DAG.getCALLSEQ_END(Chain,
9921                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9922                              DAG.getConstant(0, DL, PtrVT, true),
9923                              Glue, DL);
9924   Glue = Chain.getValue(1);
9925 
9926   // Assign locations to each value returned by this call.
9927   SmallVector<CCValAssign, 16> RVLocs;
9928   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9929   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9930 
9931   // Copy all of the result registers out of their specified physreg.
9932   for (auto &VA : RVLocs) {
9933     // Copy the value out
9934     SDValue RetValue =
9935         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9936     // Glue the RetValue to the end of the call sequence
9937     Chain = RetValue.getValue(1);
9938     Glue = RetValue.getValue(2);
9939 
9940     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9941       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9942       SDValue RetValue2 =
9943           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9944       Chain = RetValue2.getValue(1);
9945       Glue = RetValue2.getValue(2);
9946       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9947                              RetValue2);
9948     }
9949 
9950     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9951 
9952     InVals.push_back(RetValue);
9953   }
9954 
9955   return Chain;
9956 }
9957 
9958 bool RISCVTargetLowering::CanLowerReturn(
9959     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9960     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9961   SmallVector<CCValAssign, 16> RVLocs;
9962   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9963 
9964   Optional<unsigned> FirstMaskArgument;
9965   if (Subtarget.hasVInstructions())
9966     FirstMaskArgument = preAssignMask(Outs);
9967 
9968   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9969     MVT VT = Outs[i].VT;
9970     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9971     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9972     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9973                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9974                  *this, FirstMaskArgument))
9975       return false;
9976   }
9977   return true;
9978 }
9979 
9980 SDValue
9981 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9982                                  bool IsVarArg,
9983                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9984                                  const SmallVectorImpl<SDValue> &OutVals,
9985                                  const SDLoc &DL, SelectionDAG &DAG) const {
9986   const MachineFunction &MF = DAG.getMachineFunction();
9987   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9988 
9989   // Stores the assignment of the return value to a location.
9990   SmallVector<CCValAssign, 16> RVLocs;
9991 
9992   // Info about the registers and stack slot.
9993   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
9994                  *DAG.getContext());
9995 
9996   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
9997                     nullptr, CC_RISCV);
9998 
9999   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10000     report_fatal_error("GHC functions return void only");
10001 
10002   SDValue Glue;
10003   SmallVector<SDValue, 4> RetOps(1, Chain);
10004 
10005   // Copy the result values into the output registers.
10006   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10007     SDValue Val = OutVals[i];
10008     CCValAssign &VA = RVLocs[i];
10009     assert(VA.isRegLoc() && "Can only return in registers!");
10010 
10011     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10012       // Handle returning f64 on RV32D with a soft float ABI.
10013       assert(VA.isRegLoc() && "Expected return via registers");
10014       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10015                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10016       SDValue Lo = SplitF64.getValue(0);
10017       SDValue Hi = SplitF64.getValue(1);
10018       Register RegLo = VA.getLocReg();
10019       assert(RegLo < RISCV::X31 && "Invalid register pair");
10020       Register RegHi = RegLo + 1;
10021 
10022       if (STI.isRegisterReservedByUser(RegLo) ||
10023           STI.isRegisterReservedByUser(RegHi))
10024         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10025             MF.getFunction(),
10026             "Return value register required, but has been reserved."});
10027 
10028       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10029       Glue = Chain.getValue(1);
10030       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10031       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10032       Glue = Chain.getValue(1);
10033       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10034     } else {
10035       // Handle a 'normal' return.
10036       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10037       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10038 
10039       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10040         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10041             MF.getFunction(),
10042             "Return value register required, but has been reserved."});
10043 
10044       // Guarantee that all emitted copies are stuck together.
10045       Glue = Chain.getValue(1);
10046       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10047     }
10048   }
10049 
10050   RetOps[0] = Chain; // Update chain.
10051 
10052   // Add the glue node if we have it.
10053   if (Glue.getNode()) {
10054     RetOps.push_back(Glue);
10055   }
10056 
10057   unsigned RetOpc = RISCVISD::RET_FLAG;
10058   // Interrupt service routines use different return instructions.
10059   const Function &Func = DAG.getMachineFunction().getFunction();
10060   if (Func.hasFnAttribute("interrupt")) {
10061     if (!Func.getReturnType()->isVoidTy())
10062       report_fatal_error(
10063           "Functions with the interrupt attribute must have void return type!");
10064 
10065     MachineFunction &MF = DAG.getMachineFunction();
10066     StringRef Kind =
10067       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10068 
10069     if (Kind == "user")
10070       RetOpc = RISCVISD::URET_FLAG;
10071     else if (Kind == "supervisor")
10072       RetOpc = RISCVISD::SRET_FLAG;
10073     else
10074       RetOpc = RISCVISD::MRET_FLAG;
10075   }
10076 
10077   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10078 }
10079 
10080 void RISCVTargetLowering::validateCCReservedRegs(
10081     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10082     MachineFunction &MF) const {
10083   const Function &F = MF.getFunction();
10084   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10085 
10086   if (llvm::any_of(Regs, [&STI](auto Reg) {
10087         return STI.isRegisterReservedByUser(Reg.first);
10088       }))
10089     F.getContext().diagnose(DiagnosticInfoUnsupported{
10090         F, "Argument register required, but has been reserved."});
10091 }
10092 
10093 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10094   return CI->isTailCall();
10095 }
10096 
10097 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10098 #define NODE_NAME_CASE(NODE)                                                   \
10099   case RISCVISD::NODE:                                                         \
10100     return "RISCVISD::" #NODE;
10101   // clang-format off
10102   switch ((RISCVISD::NodeType)Opcode) {
10103   case RISCVISD::FIRST_NUMBER:
10104     break;
10105   NODE_NAME_CASE(RET_FLAG)
10106   NODE_NAME_CASE(URET_FLAG)
10107   NODE_NAME_CASE(SRET_FLAG)
10108   NODE_NAME_CASE(MRET_FLAG)
10109   NODE_NAME_CASE(CALL)
10110   NODE_NAME_CASE(SELECT_CC)
10111   NODE_NAME_CASE(BR_CC)
10112   NODE_NAME_CASE(BuildPairF64)
10113   NODE_NAME_CASE(SplitF64)
10114   NODE_NAME_CASE(TAIL)
10115   NODE_NAME_CASE(MULHSU)
10116   NODE_NAME_CASE(SLLW)
10117   NODE_NAME_CASE(SRAW)
10118   NODE_NAME_CASE(SRLW)
10119   NODE_NAME_CASE(DIVW)
10120   NODE_NAME_CASE(DIVUW)
10121   NODE_NAME_CASE(REMUW)
10122   NODE_NAME_CASE(ROLW)
10123   NODE_NAME_CASE(RORW)
10124   NODE_NAME_CASE(CLZW)
10125   NODE_NAME_CASE(CTZW)
10126   NODE_NAME_CASE(FSLW)
10127   NODE_NAME_CASE(FSRW)
10128   NODE_NAME_CASE(FSL)
10129   NODE_NAME_CASE(FSR)
10130   NODE_NAME_CASE(FMV_H_X)
10131   NODE_NAME_CASE(FMV_X_ANYEXTH)
10132   NODE_NAME_CASE(FMV_W_X_RV64)
10133   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10134   NODE_NAME_CASE(FCVT_X)
10135   NODE_NAME_CASE(FCVT_XU)
10136   NODE_NAME_CASE(FCVT_W_RV64)
10137   NODE_NAME_CASE(FCVT_WU_RV64)
10138   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10139   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10140   NODE_NAME_CASE(READ_CYCLE_WIDE)
10141   NODE_NAME_CASE(GREV)
10142   NODE_NAME_CASE(GREVW)
10143   NODE_NAME_CASE(GORC)
10144   NODE_NAME_CASE(GORCW)
10145   NODE_NAME_CASE(SHFL)
10146   NODE_NAME_CASE(SHFLW)
10147   NODE_NAME_CASE(UNSHFL)
10148   NODE_NAME_CASE(UNSHFLW)
10149   NODE_NAME_CASE(BFP)
10150   NODE_NAME_CASE(BFPW)
10151   NODE_NAME_CASE(BCOMPRESS)
10152   NODE_NAME_CASE(BCOMPRESSW)
10153   NODE_NAME_CASE(BDECOMPRESS)
10154   NODE_NAME_CASE(BDECOMPRESSW)
10155   NODE_NAME_CASE(VMV_V_X_VL)
10156   NODE_NAME_CASE(VFMV_V_F_VL)
10157   NODE_NAME_CASE(VMV_X_S)
10158   NODE_NAME_CASE(VMV_S_X_VL)
10159   NODE_NAME_CASE(VFMV_S_F_VL)
10160   NODE_NAME_CASE(SPLAT_VECTOR_I64)
10161   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10162   NODE_NAME_CASE(READ_VLENB)
10163   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10164   NODE_NAME_CASE(VSLIDEUP_VL)
10165   NODE_NAME_CASE(VSLIDE1UP_VL)
10166   NODE_NAME_CASE(VSLIDEDOWN_VL)
10167   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10168   NODE_NAME_CASE(VID_VL)
10169   NODE_NAME_CASE(VFNCVT_ROD_VL)
10170   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10171   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10172   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10173   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10174   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10175   NODE_NAME_CASE(VECREDUCE_AND_VL)
10176   NODE_NAME_CASE(VECREDUCE_OR_VL)
10177   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10178   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10179   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10180   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10181   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10182   NODE_NAME_CASE(ADD_VL)
10183   NODE_NAME_CASE(AND_VL)
10184   NODE_NAME_CASE(MUL_VL)
10185   NODE_NAME_CASE(OR_VL)
10186   NODE_NAME_CASE(SDIV_VL)
10187   NODE_NAME_CASE(SHL_VL)
10188   NODE_NAME_CASE(SREM_VL)
10189   NODE_NAME_CASE(SRA_VL)
10190   NODE_NAME_CASE(SRL_VL)
10191   NODE_NAME_CASE(SUB_VL)
10192   NODE_NAME_CASE(UDIV_VL)
10193   NODE_NAME_CASE(UREM_VL)
10194   NODE_NAME_CASE(XOR_VL)
10195   NODE_NAME_CASE(SADDSAT_VL)
10196   NODE_NAME_CASE(UADDSAT_VL)
10197   NODE_NAME_CASE(SSUBSAT_VL)
10198   NODE_NAME_CASE(USUBSAT_VL)
10199   NODE_NAME_CASE(FADD_VL)
10200   NODE_NAME_CASE(FSUB_VL)
10201   NODE_NAME_CASE(FMUL_VL)
10202   NODE_NAME_CASE(FDIV_VL)
10203   NODE_NAME_CASE(FNEG_VL)
10204   NODE_NAME_CASE(FABS_VL)
10205   NODE_NAME_CASE(FSQRT_VL)
10206   NODE_NAME_CASE(FMA_VL)
10207   NODE_NAME_CASE(FCOPYSIGN_VL)
10208   NODE_NAME_CASE(SMIN_VL)
10209   NODE_NAME_CASE(SMAX_VL)
10210   NODE_NAME_CASE(UMIN_VL)
10211   NODE_NAME_CASE(UMAX_VL)
10212   NODE_NAME_CASE(FMINNUM_VL)
10213   NODE_NAME_CASE(FMAXNUM_VL)
10214   NODE_NAME_CASE(MULHS_VL)
10215   NODE_NAME_CASE(MULHU_VL)
10216   NODE_NAME_CASE(FP_TO_SINT_VL)
10217   NODE_NAME_CASE(FP_TO_UINT_VL)
10218   NODE_NAME_CASE(SINT_TO_FP_VL)
10219   NODE_NAME_CASE(UINT_TO_FP_VL)
10220   NODE_NAME_CASE(FP_EXTEND_VL)
10221   NODE_NAME_CASE(FP_ROUND_VL)
10222   NODE_NAME_CASE(VWMUL_VL)
10223   NODE_NAME_CASE(VWMULU_VL)
10224   NODE_NAME_CASE(VWMULSU_VL)
10225   NODE_NAME_CASE(VWADDU_VL)
10226   NODE_NAME_CASE(SETCC_VL)
10227   NODE_NAME_CASE(VSELECT_VL)
10228   NODE_NAME_CASE(VP_MERGE_VL)
10229   NODE_NAME_CASE(VMAND_VL)
10230   NODE_NAME_CASE(VMOR_VL)
10231   NODE_NAME_CASE(VMXOR_VL)
10232   NODE_NAME_CASE(VMCLR_VL)
10233   NODE_NAME_CASE(VMSET_VL)
10234   NODE_NAME_CASE(VRGATHER_VX_VL)
10235   NODE_NAME_CASE(VRGATHER_VV_VL)
10236   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10237   NODE_NAME_CASE(VSEXT_VL)
10238   NODE_NAME_CASE(VZEXT_VL)
10239   NODE_NAME_CASE(VCPOP_VL)
10240   NODE_NAME_CASE(VLE_VL)
10241   NODE_NAME_CASE(VSE_VL)
10242   NODE_NAME_CASE(READ_CSR)
10243   NODE_NAME_CASE(WRITE_CSR)
10244   NODE_NAME_CASE(SWAP_CSR)
10245   }
10246   // clang-format on
10247   return nullptr;
10248 #undef NODE_NAME_CASE
10249 }
10250 
10251 /// getConstraintType - Given a constraint letter, return the type of
10252 /// constraint it is for this target.
10253 RISCVTargetLowering::ConstraintType
10254 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10255   if (Constraint.size() == 1) {
10256     switch (Constraint[0]) {
10257     default:
10258       break;
10259     case 'f':
10260       return C_RegisterClass;
10261     case 'I':
10262     case 'J':
10263     case 'K':
10264       return C_Immediate;
10265     case 'A':
10266       return C_Memory;
10267     case 'S': // A symbolic address
10268       return C_Other;
10269     }
10270   } else {
10271     if (Constraint == "vr" || Constraint == "vm")
10272       return C_RegisterClass;
10273   }
10274   return TargetLowering::getConstraintType(Constraint);
10275 }
10276 
10277 std::pair<unsigned, const TargetRegisterClass *>
10278 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10279                                                   StringRef Constraint,
10280                                                   MVT VT) const {
10281   // First, see if this is a constraint that directly corresponds to a
10282   // RISCV register class.
10283   if (Constraint.size() == 1) {
10284     switch (Constraint[0]) {
10285     case 'r':
10286       // TODO: Support fixed vectors up to XLen for P extension?
10287       if (VT.isVector())
10288         break;
10289       return std::make_pair(0U, &RISCV::GPRRegClass);
10290     case 'f':
10291       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10292         return std::make_pair(0U, &RISCV::FPR16RegClass);
10293       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10294         return std::make_pair(0U, &RISCV::FPR32RegClass);
10295       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10296         return std::make_pair(0U, &RISCV::FPR64RegClass);
10297       break;
10298     default:
10299       break;
10300     }
10301   } else if (Constraint == "vr") {
10302     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10303                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10304       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10305         return std::make_pair(0U, RC);
10306     }
10307   } else if (Constraint == "vm") {
10308     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10309       return std::make_pair(0U, &RISCV::VMV0RegClass);
10310   }
10311 
10312   // Clang will correctly decode the usage of register name aliases into their
10313   // official names. However, other frontends like `rustc` do not. This allows
10314   // users of these frontends to use the ABI names for registers in LLVM-style
10315   // register constraints.
10316   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10317                                .Case("{zero}", RISCV::X0)
10318                                .Case("{ra}", RISCV::X1)
10319                                .Case("{sp}", RISCV::X2)
10320                                .Case("{gp}", RISCV::X3)
10321                                .Case("{tp}", RISCV::X4)
10322                                .Case("{t0}", RISCV::X5)
10323                                .Case("{t1}", RISCV::X6)
10324                                .Case("{t2}", RISCV::X7)
10325                                .Cases("{s0}", "{fp}", RISCV::X8)
10326                                .Case("{s1}", RISCV::X9)
10327                                .Case("{a0}", RISCV::X10)
10328                                .Case("{a1}", RISCV::X11)
10329                                .Case("{a2}", RISCV::X12)
10330                                .Case("{a3}", RISCV::X13)
10331                                .Case("{a4}", RISCV::X14)
10332                                .Case("{a5}", RISCV::X15)
10333                                .Case("{a6}", RISCV::X16)
10334                                .Case("{a7}", RISCV::X17)
10335                                .Case("{s2}", RISCV::X18)
10336                                .Case("{s3}", RISCV::X19)
10337                                .Case("{s4}", RISCV::X20)
10338                                .Case("{s5}", RISCV::X21)
10339                                .Case("{s6}", RISCV::X22)
10340                                .Case("{s7}", RISCV::X23)
10341                                .Case("{s8}", RISCV::X24)
10342                                .Case("{s9}", RISCV::X25)
10343                                .Case("{s10}", RISCV::X26)
10344                                .Case("{s11}", RISCV::X27)
10345                                .Case("{t3}", RISCV::X28)
10346                                .Case("{t4}", RISCV::X29)
10347                                .Case("{t5}", RISCV::X30)
10348                                .Case("{t6}", RISCV::X31)
10349                                .Default(RISCV::NoRegister);
10350   if (XRegFromAlias != RISCV::NoRegister)
10351     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10352 
10353   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10354   // TableGen record rather than the AsmName to choose registers for InlineAsm
10355   // constraints, plus we want to match those names to the widest floating point
10356   // register type available, manually select floating point registers here.
10357   //
10358   // The second case is the ABI name of the register, so that frontends can also
10359   // use the ABI names in register constraint lists.
10360   if (Subtarget.hasStdExtF()) {
10361     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10362                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10363                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10364                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10365                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10366                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10367                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10368                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10369                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10370                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10371                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10372                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10373                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10374                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10375                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10376                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10377                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10378                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10379                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10380                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10381                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10382                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10383                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10384                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10385                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10386                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10387                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10388                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10389                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10390                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10391                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10392                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10393                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10394                         .Default(RISCV::NoRegister);
10395     if (FReg != RISCV::NoRegister) {
10396       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10397       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10398         unsigned RegNo = FReg - RISCV::F0_F;
10399         unsigned DReg = RISCV::F0_D + RegNo;
10400         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10401       }
10402       if (VT == MVT::f32 || VT == MVT::Other)
10403         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10404       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10405         unsigned RegNo = FReg - RISCV::F0_F;
10406         unsigned HReg = RISCV::F0_H + RegNo;
10407         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10408       }
10409     }
10410   }
10411 
10412   if (Subtarget.hasVInstructions()) {
10413     Register VReg = StringSwitch<Register>(Constraint.lower())
10414                         .Case("{v0}", RISCV::V0)
10415                         .Case("{v1}", RISCV::V1)
10416                         .Case("{v2}", RISCV::V2)
10417                         .Case("{v3}", RISCV::V3)
10418                         .Case("{v4}", RISCV::V4)
10419                         .Case("{v5}", RISCV::V5)
10420                         .Case("{v6}", RISCV::V6)
10421                         .Case("{v7}", RISCV::V7)
10422                         .Case("{v8}", RISCV::V8)
10423                         .Case("{v9}", RISCV::V9)
10424                         .Case("{v10}", RISCV::V10)
10425                         .Case("{v11}", RISCV::V11)
10426                         .Case("{v12}", RISCV::V12)
10427                         .Case("{v13}", RISCV::V13)
10428                         .Case("{v14}", RISCV::V14)
10429                         .Case("{v15}", RISCV::V15)
10430                         .Case("{v16}", RISCV::V16)
10431                         .Case("{v17}", RISCV::V17)
10432                         .Case("{v18}", RISCV::V18)
10433                         .Case("{v19}", RISCV::V19)
10434                         .Case("{v20}", RISCV::V20)
10435                         .Case("{v21}", RISCV::V21)
10436                         .Case("{v22}", RISCV::V22)
10437                         .Case("{v23}", RISCV::V23)
10438                         .Case("{v24}", RISCV::V24)
10439                         .Case("{v25}", RISCV::V25)
10440                         .Case("{v26}", RISCV::V26)
10441                         .Case("{v27}", RISCV::V27)
10442                         .Case("{v28}", RISCV::V28)
10443                         .Case("{v29}", RISCV::V29)
10444                         .Case("{v30}", RISCV::V30)
10445                         .Case("{v31}", RISCV::V31)
10446                         .Default(RISCV::NoRegister);
10447     if (VReg != RISCV::NoRegister) {
10448       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10449         return std::make_pair(VReg, &RISCV::VMRegClass);
10450       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10451         return std::make_pair(VReg, &RISCV::VRRegClass);
10452       for (const auto *RC :
10453            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10454         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10455           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10456           return std::make_pair(VReg, RC);
10457         }
10458       }
10459     }
10460   }
10461 
10462   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10463 }
10464 
10465 unsigned
10466 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10467   // Currently only support length 1 constraints.
10468   if (ConstraintCode.size() == 1) {
10469     switch (ConstraintCode[0]) {
10470     case 'A':
10471       return InlineAsm::Constraint_A;
10472     default:
10473       break;
10474     }
10475   }
10476 
10477   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10478 }
10479 
10480 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10481     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10482     SelectionDAG &DAG) const {
10483   // Currently only support length 1 constraints.
10484   if (Constraint.length() == 1) {
10485     switch (Constraint[0]) {
10486     case 'I':
10487       // Validate & create a 12-bit signed immediate operand.
10488       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10489         uint64_t CVal = C->getSExtValue();
10490         if (isInt<12>(CVal))
10491           Ops.push_back(
10492               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10493       }
10494       return;
10495     case 'J':
10496       // Validate & create an integer zero operand.
10497       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10498         if (C->getZExtValue() == 0)
10499           Ops.push_back(
10500               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10501       return;
10502     case 'K':
10503       // Validate & create a 5-bit unsigned immediate operand.
10504       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10505         uint64_t CVal = C->getZExtValue();
10506         if (isUInt<5>(CVal))
10507           Ops.push_back(
10508               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10509       }
10510       return;
10511     case 'S':
10512       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10513         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10514                                                  GA->getValueType(0)));
10515       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10516         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10517                                                 BA->getValueType(0)));
10518       }
10519       return;
10520     default:
10521       break;
10522     }
10523   }
10524   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10525 }
10526 
10527 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10528                                                    Instruction *Inst,
10529                                                    AtomicOrdering Ord) const {
10530   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10531     return Builder.CreateFence(Ord);
10532   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10533     return Builder.CreateFence(AtomicOrdering::Release);
10534   return nullptr;
10535 }
10536 
10537 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10538                                                     Instruction *Inst,
10539                                                     AtomicOrdering Ord) const {
10540   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10541     return Builder.CreateFence(AtomicOrdering::Acquire);
10542   return nullptr;
10543 }
10544 
10545 TargetLowering::AtomicExpansionKind
10546 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10547   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10548   // point operations can't be used in an lr/sc sequence without breaking the
10549   // forward-progress guarantee.
10550   if (AI->isFloatingPointOperation())
10551     return AtomicExpansionKind::CmpXChg;
10552 
10553   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10554   if (Size == 8 || Size == 16)
10555     return AtomicExpansionKind::MaskedIntrinsic;
10556   return AtomicExpansionKind::None;
10557 }
10558 
10559 static Intrinsic::ID
10560 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10561   if (XLen == 32) {
10562     switch (BinOp) {
10563     default:
10564       llvm_unreachable("Unexpected AtomicRMW BinOp");
10565     case AtomicRMWInst::Xchg:
10566       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10567     case AtomicRMWInst::Add:
10568       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10569     case AtomicRMWInst::Sub:
10570       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10571     case AtomicRMWInst::Nand:
10572       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10573     case AtomicRMWInst::Max:
10574       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10575     case AtomicRMWInst::Min:
10576       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10577     case AtomicRMWInst::UMax:
10578       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10579     case AtomicRMWInst::UMin:
10580       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10581     }
10582   }
10583 
10584   if (XLen == 64) {
10585     switch (BinOp) {
10586     default:
10587       llvm_unreachable("Unexpected AtomicRMW BinOp");
10588     case AtomicRMWInst::Xchg:
10589       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10590     case AtomicRMWInst::Add:
10591       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10592     case AtomicRMWInst::Sub:
10593       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10594     case AtomicRMWInst::Nand:
10595       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10596     case AtomicRMWInst::Max:
10597       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10598     case AtomicRMWInst::Min:
10599       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10600     case AtomicRMWInst::UMax:
10601       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10602     case AtomicRMWInst::UMin:
10603       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10604     }
10605   }
10606 
10607   llvm_unreachable("Unexpected XLen\n");
10608 }
10609 
10610 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10611     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10612     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10613   unsigned XLen = Subtarget.getXLen();
10614   Value *Ordering =
10615       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10616   Type *Tys[] = {AlignedAddr->getType()};
10617   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10618       AI->getModule(),
10619       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10620 
10621   if (XLen == 64) {
10622     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10623     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10624     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10625   }
10626 
10627   Value *Result;
10628 
10629   // Must pass the shift amount needed to sign extend the loaded value prior
10630   // to performing a signed comparison for min/max. ShiftAmt is the number of
10631   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10632   // is the number of bits to left+right shift the value in order to
10633   // sign-extend.
10634   if (AI->getOperation() == AtomicRMWInst::Min ||
10635       AI->getOperation() == AtomicRMWInst::Max) {
10636     const DataLayout &DL = AI->getModule()->getDataLayout();
10637     unsigned ValWidth =
10638         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10639     Value *SextShamt =
10640         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10641     Result = Builder.CreateCall(LrwOpScwLoop,
10642                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10643   } else {
10644     Result =
10645         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10646   }
10647 
10648   if (XLen == 64)
10649     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10650   return Result;
10651 }
10652 
10653 TargetLowering::AtomicExpansionKind
10654 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10655     AtomicCmpXchgInst *CI) const {
10656   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10657   if (Size == 8 || Size == 16)
10658     return AtomicExpansionKind::MaskedIntrinsic;
10659   return AtomicExpansionKind::None;
10660 }
10661 
10662 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10663     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10664     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10665   unsigned XLen = Subtarget.getXLen();
10666   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10667   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10668   if (XLen == 64) {
10669     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10670     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10671     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10672     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10673   }
10674   Type *Tys[] = {AlignedAddr->getType()};
10675   Function *MaskedCmpXchg =
10676       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10677   Value *Result = Builder.CreateCall(
10678       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10679   if (XLen == 64)
10680     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10681   return Result;
10682 }
10683 
10684 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10685   return false;
10686 }
10687 
10688 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10689                                                EVT VT) const {
10690   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10691     return false;
10692 
10693   switch (FPVT.getSimpleVT().SimpleTy) {
10694   case MVT::f16:
10695     return Subtarget.hasStdExtZfh();
10696   case MVT::f32:
10697     return Subtarget.hasStdExtF();
10698   case MVT::f64:
10699     return Subtarget.hasStdExtD();
10700   default:
10701     return false;
10702   }
10703 }
10704 
10705 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10706   // If we are using the small code model, we can reduce size of jump table
10707   // entry to 4 bytes.
10708   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10709       getTargetMachine().getCodeModel() == CodeModel::Small) {
10710     return MachineJumpTableInfo::EK_Custom32;
10711   }
10712   return TargetLowering::getJumpTableEncoding();
10713 }
10714 
10715 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10716     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10717     unsigned uid, MCContext &Ctx) const {
10718   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10719          getTargetMachine().getCodeModel() == CodeModel::Small);
10720   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10721 }
10722 
10723 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10724                                                      EVT VT) const {
10725   VT = VT.getScalarType();
10726 
10727   if (!VT.isSimple())
10728     return false;
10729 
10730   switch (VT.getSimpleVT().SimpleTy) {
10731   case MVT::f16:
10732     return Subtarget.hasStdExtZfh();
10733   case MVT::f32:
10734     return Subtarget.hasStdExtF();
10735   case MVT::f64:
10736     return Subtarget.hasStdExtD();
10737   default:
10738     break;
10739   }
10740 
10741   return false;
10742 }
10743 
10744 Register RISCVTargetLowering::getExceptionPointerRegister(
10745     const Constant *PersonalityFn) const {
10746   return RISCV::X10;
10747 }
10748 
10749 Register RISCVTargetLowering::getExceptionSelectorRegister(
10750     const Constant *PersonalityFn) const {
10751   return RISCV::X11;
10752 }
10753 
10754 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10755   // Return false to suppress the unnecessary extensions if the LibCall
10756   // arguments or return value is f32 type for LP64 ABI.
10757   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10758   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10759     return false;
10760 
10761   return true;
10762 }
10763 
10764 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10765   if (Subtarget.is64Bit() && Type == MVT::i32)
10766     return true;
10767 
10768   return IsSigned;
10769 }
10770 
10771 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10772                                                  SDValue C) const {
10773   // Check integral scalar types.
10774   if (VT.isScalarInteger()) {
10775     // Omit the optimization if the sub target has the M extension and the data
10776     // size exceeds XLen.
10777     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10778       return false;
10779     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10780       // Break the MUL to a SLLI and an ADD/SUB.
10781       const APInt &Imm = ConstNode->getAPIntValue();
10782       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10783           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10784         return true;
10785       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10786       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10787           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10788            (Imm - 8).isPowerOf2()))
10789         return true;
10790       // Omit the following optimization if the sub target has the M extension
10791       // and the data size >= XLen.
10792       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10793         return false;
10794       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10795       // a pair of LUI/ADDI.
10796       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10797         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10798         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10799             (1 - ImmS).isPowerOf2())
10800         return true;
10801       }
10802     }
10803   }
10804 
10805   return false;
10806 }
10807 
10808 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10809     const SDValue &AddNode, const SDValue &ConstNode) const {
10810   // Let the DAGCombiner decide for vectors.
10811   EVT VT = AddNode.getValueType();
10812   if (VT.isVector())
10813     return true;
10814 
10815   // Let the DAGCombiner decide for larger types.
10816   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10817     return true;
10818 
10819   // It is worse if c1 is simm12 while c1*c2 is not.
10820   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10821   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10822   const APInt &C1 = C1Node->getAPIntValue();
10823   const APInt &C2 = C2Node->getAPIntValue();
10824   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10825     return false;
10826 
10827   // Default to true and let the DAGCombiner decide.
10828   return true;
10829 }
10830 
10831 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10832     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10833     bool *Fast) const {
10834   if (!VT.isVector())
10835     return false;
10836 
10837   EVT ElemVT = VT.getVectorElementType();
10838   if (Alignment >= ElemVT.getStoreSize()) {
10839     if (Fast)
10840       *Fast = true;
10841     return true;
10842   }
10843 
10844   return false;
10845 }
10846 
10847 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10848     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10849     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10850   bool IsABIRegCopy = CC.hasValue();
10851   EVT ValueVT = Val.getValueType();
10852   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10853     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10854     // and cast to f32.
10855     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10856     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10857     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10858                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10859     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10860     Parts[0] = Val;
10861     return true;
10862   }
10863 
10864   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10865     LLVMContext &Context = *DAG.getContext();
10866     EVT ValueEltVT = ValueVT.getVectorElementType();
10867     EVT PartEltVT = PartVT.getVectorElementType();
10868     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10869     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10870     if (PartVTBitSize % ValueVTBitSize == 0) {
10871       assert(PartVTBitSize >= ValueVTBitSize);
10872       // If the element types are different, bitcast to the same element type of
10873       // PartVT first.
10874       // Give an example here, we want copy a <vscale x 1 x i8> value to
10875       // <vscale x 4 x i16>.
10876       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10877       // subvector, then we can bitcast to <vscale x 4 x i16>.
10878       if (ValueEltVT != PartEltVT) {
10879         if (PartVTBitSize > ValueVTBitSize) {
10880           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10881           assert(Count != 0 && "The number of element should not be zero.");
10882           EVT SameEltTypeVT =
10883               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10884           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10885                             DAG.getUNDEF(SameEltTypeVT), Val,
10886                             DAG.getVectorIdxConstant(0, DL));
10887         }
10888         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10889       } else {
10890         Val =
10891             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10892                         Val, DAG.getVectorIdxConstant(0, DL));
10893       }
10894       Parts[0] = Val;
10895       return true;
10896     }
10897   }
10898   return false;
10899 }
10900 
10901 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10902     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10903     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10904   bool IsABIRegCopy = CC.hasValue();
10905   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10906     SDValue Val = Parts[0];
10907 
10908     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10909     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10910     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10911     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10912     return Val;
10913   }
10914 
10915   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10916     LLVMContext &Context = *DAG.getContext();
10917     SDValue Val = Parts[0];
10918     EVT ValueEltVT = ValueVT.getVectorElementType();
10919     EVT PartEltVT = PartVT.getVectorElementType();
10920     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10921     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10922     if (PartVTBitSize % ValueVTBitSize == 0) {
10923       assert(PartVTBitSize >= ValueVTBitSize);
10924       EVT SameEltTypeVT = ValueVT;
10925       // If the element types are different, convert it to the same element type
10926       // of PartVT.
10927       // Give an example here, we want copy a <vscale x 1 x i8> value from
10928       // <vscale x 4 x i16>.
10929       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10930       // then we can extract <vscale x 1 x i8>.
10931       if (ValueEltVT != PartEltVT) {
10932         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10933         assert(Count != 0 && "The number of element should not be zero.");
10934         SameEltTypeVT =
10935             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10936         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10937       }
10938       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10939                         DAG.getVectorIdxConstant(0, DL));
10940       return Val;
10941     }
10942   }
10943   return SDValue();
10944 }
10945 
10946 SDValue
10947 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10948                                    SelectionDAG &DAG,
10949                                    SmallVectorImpl<SDNode *> &Created) const {
10950   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10951   if (isIntDivCheap(N->getValueType(0), Attr))
10952     return SDValue(N, 0); // Lower SDIV as SDIV
10953 
10954   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
10955          "Unexpected divisor!");
10956 
10957   // Conditional move is needed, so do the transformation iff Zbt is enabled.
10958   if (!Subtarget.hasStdExtZbt())
10959     return SDValue();
10960 
10961   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
10962   // Besides, more critical path instructions will be generated when dividing
10963   // by 2. So we keep using the original DAGs for these cases.
10964   unsigned Lg2 = Divisor.countTrailingZeros();
10965   if (Lg2 == 1 || Lg2 >= 12)
10966     return SDValue();
10967 
10968   // fold (sdiv X, pow2)
10969   EVT VT = N->getValueType(0);
10970   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
10971     return SDValue();
10972 
10973   SDLoc DL(N);
10974   SDValue N0 = N->getOperand(0);
10975   SDValue Zero = DAG.getConstant(0, DL, VT);
10976   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10977 
10978   // Add (N0 < 0) ? Pow2 - 1 : 0;
10979   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
10980   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10981   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
10982 
10983   Created.push_back(Cmp.getNode());
10984   Created.push_back(Add.getNode());
10985   Created.push_back(Sel.getNode());
10986 
10987   // Divide by pow2.
10988   SDValue SRA =
10989       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
10990 
10991   // If we're dividing by a positive value, we're done.  Otherwise, we must
10992   // negate the result.
10993   if (Divisor.isNonNegative())
10994     return SRA;
10995 
10996   Created.push_back(SRA.getNode());
10997   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10998 }
10999 
11000 #define GET_REGISTER_MATCHER
11001 #include "RISCVGenAsmMatcher.inc"
11002 
11003 Register
11004 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11005                                        const MachineFunction &MF) const {
11006   Register Reg = MatchRegisterAltName(RegName);
11007   if (Reg == RISCV::NoRegister)
11008     Reg = MatchRegisterName(RegName);
11009   if (Reg == RISCV::NoRegister)
11010     report_fatal_error(
11011         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11012   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11013   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11014     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11015                              StringRef(RegName) + "\"."));
11016   return Reg;
11017 }
11018 
11019 namespace llvm {
11020 namespace RISCVVIntrinsicsTable {
11021 
11022 #define GET_RISCVVIntrinsicsTable_IMPL
11023 #include "RISCVGenSearchableTables.inc"
11024 
11025 } // namespace RISCVVIntrinsicsTable
11026 
11027 } // namespace llvm
11028