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   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
174                    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, ISD::STACKRESTORE}, MVT::Other, Expand);
185 
186   setOperationAction(ISD::VASTART, MVT::Other, Custom);
187   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
188 
189   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
190 
191   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
192 
193   if (!Subtarget.hasStdExtZbb())
194     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
195 
196   if (Subtarget.is64Bit()) {
197     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
198 
199     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
200                        MVT::i32, Custom);
201 
202     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
203                        MVT::i32, Custom);
204   } else {
205     setLibcallName(
206         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
207         nullptr);
208     setLibcallName(RTLIB::MULO_I64, nullptr);
209   }
210 
211   if (!Subtarget.hasStdExtM()) {
212     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
213                         ISD::SREM, ISD::UREM},
214                        XLenVT, Expand);
215   } else {
216     if (Subtarget.is64Bit()) {
217       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
218 
219       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
220                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
221     } else {
222       setOperationAction(ISD::MUL, MVT::i64, Custom);
223     }
224   }
225 
226   setOperationAction(
227       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
228       Expand);
229 
230   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
231                      Custom);
232 
233   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
234       Subtarget.hasStdExtZbkb()) {
235     if (Subtarget.is64Bit())
236       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
237   } else {
238     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
239   }
240 
241   if (Subtarget.hasStdExtZbp()) {
242     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
243     // more combining.
244     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
245 
246     // BSWAP i8 doesn't exist.
247     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
248 
249     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
250 
251     if (Subtarget.is64Bit())
252       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
253   } else {
254     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
255     // pattern match it directly in isel.
256     setOperationAction(ISD::BSWAP, XLenVT,
257                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
258                            ? Legal
259                            : Expand);
260     // Zbkb can use rev8+brev8 to implement bitreverse.
261     setOperationAction(ISD::BITREVERSE, XLenVT,
262                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
263   }
264 
265   if (Subtarget.hasStdExtZbb()) {
266     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
267                        Legal);
268 
269     if (Subtarget.is64Bit())
270       setOperationAction(
271           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
272           MVT::i32, Custom);
273   } else {
274     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
275 
276     if (Subtarget.is64Bit())
277       setOperationAction(ISD::ABS, MVT::i32, Custom);
278   }
279 
280   if (Subtarget.hasStdExtZbt()) {
281     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
282     setOperationAction(ISD::SELECT, XLenVT, Legal);
283 
284     if (Subtarget.is64Bit())
285       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
286   } else {
287     setOperationAction(ISD::SELECT, XLenVT, Custom);
288   }
289 
290   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
291       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
292       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
293       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
294       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
295       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
296       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
297 
298   static const ISD::CondCode FPCCToExpand[] = {
299       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
300       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
301       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
302 
303   static const ISD::NodeType FPOpToExpand[] = {
304       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
305       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
306 
307   if (Subtarget.hasStdExtZfh())
308     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
309 
310   if (Subtarget.hasStdExtZfh()) {
311     for (auto NT : FPLegalNodeTypes)
312       setOperationAction(NT, MVT::f16, Legal);
313     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
314     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
315     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
316     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
317     setOperationAction(ISD::SELECT, MVT::f16, Custom);
318     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
319 
320     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
321                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
322                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
323                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
324                         ISD::FLOG2, ISD::FLOG10},
325                        MVT::f16, Promote);
326 
327     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
328     // complete support for all operations in LegalizeDAG.
329 
330     // We need to custom promote this.
331     if (Subtarget.is64Bit())
332       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
333   }
334 
335   if (Subtarget.hasStdExtF()) {
336     for (auto NT : FPLegalNodeTypes)
337       setOperationAction(NT, MVT::f32, Legal);
338     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
339     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
340     setOperationAction(ISD::SELECT, MVT::f32, Custom);
341     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
342     for (auto Op : FPOpToExpand)
343       setOperationAction(Op, MVT::f32, Expand);
344     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
345     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
346   }
347 
348   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
349     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
350 
351   if (Subtarget.hasStdExtD()) {
352     for (auto NT : FPLegalNodeTypes)
353       setOperationAction(NT, MVT::f64, Legal);
354     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
355     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
356     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
357     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
358     setOperationAction(ISD::SELECT, MVT::f64, Custom);
359     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
360     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
361     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
362     for (auto Op : FPOpToExpand)
363       setOperationAction(Op, MVT::f64, Expand);
364     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
365     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
366   }
367 
368   if (Subtarget.is64Bit())
369     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
370                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
371                        MVT::i32, Custom);
372 
373   if (Subtarget.hasStdExtF()) {
374     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
375                        Custom);
376 
377     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
378                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
379                        XLenVT, Legal);
380 
381     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
382     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
383   }
384 
385   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
386                       ISD::JumpTable},
387                      XLenVT, Custom);
388 
389   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
390 
391   if (Subtarget.is64Bit())
392     setOperationAction(ISD::Constant, MVT::i64, Custom);
393 
394   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
395   // Unfortunately this can't be determined just from the ISA naming string.
396   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
397                      Subtarget.is64Bit() ? Legal : Custom);
398 
399   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
400   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
401   if (Subtarget.is64Bit())
402     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
403 
404   if (Subtarget.hasStdExtA()) {
405     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
406     setMinCmpXchgSizeInBits(32);
407   } else {
408     setMaxAtomicSizeInBitsSupported(0);
409   }
410 
411   setBooleanContents(ZeroOrOneBooleanContent);
412 
413   if (Subtarget.hasVInstructions()) {
414     setBooleanVectorContents(ZeroOrOneBooleanContent);
415 
416     setOperationAction(ISD::VSCALE, XLenVT, Custom);
417 
418     // RVV intrinsics may have illegal operands.
419     // We also need to custom legalize vmv.x.s.
420     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
421                        {MVT::i8, MVT::i16}, Custom);
422     if (Subtarget.is64Bit())
423       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
424     else
425       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
426                          MVT::i64, Custom);
427 
428     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
429                        MVT::Other, Custom);
430 
431     static const unsigned IntegerVPOps[] = {
432         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
433         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
434         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
435         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
436         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
437         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
438         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
439         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
440         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
441         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
442 
443     static const unsigned FloatingPointVPOps[] = {
444         ISD::VP_FADD,        ISD::VP_FSUB,
445         ISD::VP_FMUL,        ISD::VP_FDIV,
446         ISD::VP_FNEG,        ISD::VP_FMA,
447         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
448         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
449         ISD::VP_MERGE,       ISD::VP_SELECT,
450         ISD::VP_SITOFP,      ISD::VP_UITOFP,
451         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
452         ISD::VP_FP_EXTEND};
453 
454     if (!Subtarget.is64Bit()) {
455       // We must custom-lower certain vXi64 operations on RV32 due to the vector
456       // element type being illegal.
457       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
458                          MVT::i64, Custom);
459 
460       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
461                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
462                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
463                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
464                          MVT::i64, Custom);
465 
466       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
467                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
468                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
469                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
470                          MVT::i64, Custom);
471     }
472 
473     for (MVT VT : BoolVecVTs) {
474       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
475 
476       // Mask VTs are custom-expanded into a series of standard nodes
477       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
478                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
479                          VT, Custom);
480 
481       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
482                          Custom);
483 
484       setOperationAction(ISD::SELECT, VT, Custom);
485       setOperationAction(
486           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
487           Expand);
488 
489       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
490 
491       setOperationAction(
492           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
493           Custom);
494 
495       setOperationAction(
496           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
497           Custom);
498 
499       // RVV has native int->float & float->int conversions where the
500       // element type sizes are within one power-of-two of each other. Any
501       // wider distances between type sizes have to be lowered as sequences
502       // which progressively narrow the gap in stages.
503       setOperationAction(
504           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
505           VT, Custom);
506 
507       // Expand all extending loads to types larger than this, and truncating
508       // stores from types larger than this.
509       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
510         setTruncStoreAction(OtherVT, VT, Expand);
511         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
512                          VT, Expand);
513       }
514 
515       setOperationAction(
516           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
517           Custom);
518     }
519 
520     for (MVT VT : IntVecVTs) {
521       if (VT.getVectorElementType() == MVT::i64 &&
522           !Subtarget.hasVInstructionsI64())
523         continue;
524 
525       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
526       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
527 
528       // Vectors implement MULHS/MULHU.
529       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
530 
531       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
532       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
533         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
534 
535       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
536                          Legal);
537 
538       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
539 
540       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
541                          Expand);
542 
543       setOperationAction(ISD::BSWAP, VT, Expand);
544 
545       // Custom-lower extensions and truncations from/to mask types.
546       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
547                          VT, Custom);
548 
549       // RVV has native int->float & float->int conversions where the
550       // element type sizes are within one power-of-two of each other. Any
551       // wider distances between type sizes have to be lowered as sequences
552       // which progressively narrow the gap in stages.
553       setOperationAction(
554           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
555           VT, Custom);
556 
557       setOperationAction(
558           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
559 
560       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
561       // nodes which truncate by one power of two at a time.
562       setOperationAction(ISD::TRUNCATE, VT, Custom);
563 
564       // Custom-lower insert/extract operations to simplify patterns.
565       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
566                          Custom);
567 
568       // Custom-lower reduction operations to set up the corresponding custom
569       // nodes' operands.
570       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
571                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
572                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
573                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
574                          VT, Custom);
575 
576       setOperationAction(IntegerVPOps, VT, Custom);
577 
578       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
579 
580       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
581                          VT, Custom);
582 
583       setOperationAction(
584           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
585           Custom);
586 
587       setOperationAction(
588           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
589           VT, Custom);
590 
591       setOperationAction(ISD::SELECT, VT, Custom);
592       setOperationAction(ISD::SELECT_CC, VT, Expand);
593 
594       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
595 
596       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
597         setTruncStoreAction(VT, OtherVT, Expand);
598         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
599                          VT, Expand);
600       }
601 
602       // Splice
603       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
604 
605       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
606       // type that can represent the value exactly.
607       if (VT.getVectorElementType() != MVT::i64) {
608         MVT FloatEltVT =
609             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
610         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
611         if (isTypeLegal(FloatVT)) {
612           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
613                              Custom);
614         }
615       }
616     }
617 
618     // Expand various CCs to best match the RVV ISA, which natively supports UNE
619     // but no other unordered comparisons, and supports all ordered comparisons
620     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
621     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
622     // and we pattern-match those back to the "original", swapping operands once
623     // more. This way we catch both operations and both "vf" and "fv" forms with
624     // fewer patterns.
625     static const ISD::CondCode VFPCCToExpand[] = {
626         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
627         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
628         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
629     };
630 
631     // Sets common operation actions on RVV floating-point vector types.
632     const auto SetCommonVFPActions = [&](MVT VT) {
633       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
634       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
635       // sizes are within one power-of-two of each other. Therefore conversions
636       // between vXf16 and vXf64 must be lowered as sequences which convert via
637       // vXf32.
638       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
639       // Custom-lower insert/extract operations to simplify patterns.
640       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
641                          Custom);
642       // Expand various condition codes (explained above).
643       setCondCodeAction(VFPCCToExpand, VT, Expand);
644 
645       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
646 
647       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
648                          VT, Custom);
649 
650       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
651                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
652                          VT, Custom);
653 
654       // Expand FP operations that need libcalls.
655       setOperationAction(ISD::FREM, VT, Expand);
656       setOperationAction(ISD::FPOW, VT, Expand);
657       setOperationAction(ISD::FCOS, VT, Expand);
658       setOperationAction(ISD::FSIN, VT, Expand);
659       setOperationAction(ISD::FSINCOS, VT, Expand);
660       setOperationAction(ISD::FEXP, VT, Expand);
661       setOperationAction(ISD::FEXP2, VT, Expand);
662       setOperationAction(ISD::FLOG, VT, Expand);
663       setOperationAction(ISD::FLOG2, VT, Expand);
664       setOperationAction(ISD::FLOG10, VT, Expand);
665       setOperationAction(ISD::FRINT, VT, Expand);
666       setOperationAction(ISD::FNEARBYINT, VT, Expand);
667 
668       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
669       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
670       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
671       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
672 
673       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
674 
675       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
676 
677       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
678                          VT, Custom);
679 
680       setOperationAction(
681           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
682           Custom);
683 
684       setOperationAction(ISD::SELECT, VT, Custom);
685       setOperationAction(ISD::SELECT_CC, VT, Expand);
686 
687       setOperationAction(
688           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
689           VT, Custom);
690 
691       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
692 
693       setOperationAction(FloatingPointVPOps, VT, Custom);
694     };
695 
696     // Sets common extload/truncstore actions on RVV floating-point vector
697     // types.
698     const auto SetCommonVFPExtLoadTruncStoreActions =
699         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
700           for (auto SmallVT : SmallerVTs) {
701             setTruncStoreAction(VT, SmallVT, Expand);
702             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
703           }
704         };
705 
706     if (Subtarget.hasVInstructionsF16())
707       for (MVT VT : F16VecVTs)
708         SetCommonVFPActions(VT);
709 
710     for (MVT VT : F32VecVTs) {
711       if (Subtarget.hasVInstructionsF32())
712         SetCommonVFPActions(VT);
713       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
714     }
715 
716     for (MVT VT : F64VecVTs) {
717       if (Subtarget.hasVInstructionsF64())
718         SetCommonVFPActions(VT);
719       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
720       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
721     }
722 
723     if (Subtarget.useRVVForFixedLengthVectors()) {
724       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
725         if (!useRVVForFixedLengthVectorVT(VT))
726           continue;
727 
728         // By default everything must be expanded.
729         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
730           setOperationAction(Op, VT, Expand);
731         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
732           setTruncStoreAction(VT, OtherVT, Expand);
733           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
734                            OtherVT, VT, Expand);
735         }
736 
737         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
738         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
739                            Custom);
740 
741         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
742                            Custom);
743 
744         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
745                            VT, Custom);
746 
747         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
748 
749         setOperationAction(ISD::SETCC, VT, Custom);
750 
751         setOperationAction(ISD::SELECT, VT, Custom);
752 
753         setOperationAction(ISD::TRUNCATE, VT, Custom);
754 
755         setOperationAction(ISD::BITCAST, VT, Custom);
756 
757         setOperationAction(
758             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
759             Custom);
760 
761         setOperationAction(
762             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
763             Custom);
764 
765         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
766                             ISD::FP_TO_UINT},
767                            VT, Custom);
768 
769         // Operations below are different for between masks and other vectors.
770         if (VT.getVectorElementType() == MVT::i1) {
771           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
772                               ISD::OR, ISD::XOR},
773                              VT, Custom);
774 
775           setOperationAction(
776               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
777               VT, Custom);
778           continue;
779         }
780 
781         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
782         // it before type legalization for i64 vectors on RV32. It will then be
783         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
784         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
785         // improvements first.
786         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
787           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
788           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
789         }
790 
791         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
792         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
793 
794         setOperationAction(
795             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
796 
797         setOperationAction(
798             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
799             Custom);
800 
801         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
802                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
803                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
804                            VT, Custom);
805 
806         setOperationAction(
807             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
808 
809         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
810         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
811           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
812 
813         setOperationAction(
814             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
815             Custom);
816 
817         setOperationAction(ISD::VSELECT, VT, Custom);
818         setOperationAction(ISD::SELECT_CC, VT, Expand);
819 
820         setOperationAction(
821             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
822 
823         // Custom-lower reduction operations to set up the corresponding custom
824         // nodes' operands.
825         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
826                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
827                             ISD::VECREDUCE_UMIN},
828                            VT, Custom);
829 
830         setOperationAction(IntegerVPOps, VT, Custom);
831 
832         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
833         // type that can represent the value exactly.
834         if (VT.getVectorElementType() != MVT::i64) {
835           MVT FloatEltVT =
836               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
837           EVT FloatVT =
838               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
839           if (isTypeLegal(FloatVT))
840             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
841                                Custom);
842         }
843       }
844 
845       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
846         if (!useRVVForFixedLengthVectorVT(VT))
847           continue;
848 
849         // By default everything must be expanded.
850         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
851           setOperationAction(Op, VT, Expand);
852         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
853           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
854           setTruncStoreAction(VT, OtherVT, Expand);
855         }
856 
857         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
858         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
859                            Custom);
860 
861         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
862                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
863                             ISD::EXTRACT_VECTOR_ELT},
864                            VT, Custom);
865 
866         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
867                             ISD::MGATHER, ISD::MSCATTER},
868                            VT, Custom);
869 
870         setOperationAction(
871             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
872             Custom);
873 
874         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
875                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
876                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
877                            VT, Custom);
878 
879         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
880 
881         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
882                            VT, Custom);
883 
884         for (auto CC : VFPCCToExpand)
885           setCondCodeAction(CC, VT, Expand);
886 
887         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
888         setOperationAction(ISD::SELECT_CC, VT, Expand);
889 
890         setOperationAction(ISD::BITCAST, VT, Custom);
891 
892         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
893                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
894                            VT, Custom);
895 
896         setOperationAction(FloatingPointVPOps, VT, Custom);
897       }
898 
899       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
900       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
901                          Custom);
902       if (Subtarget.hasStdExtZfh())
903         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
904       if (Subtarget.hasStdExtF())
905         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
906       if (Subtarget.hasStdExtD())
907         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
908     }
909   }
910 
911   // Function alignments.
912   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
913   setMinFunctionAlignment(FunctionAlignment);
914   setPrefFunctionAlignment(FunctionAlignment);
915 
916   setMinimumJumpTableEntries(5);
917 
918   // Jumps are expensive, compared to logic
919   setJumpIsExpensive();
920 
921   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
922                        ISD::OR, ISD::XOR});
923 
924   if (Subtarget.hasStdExtF())
925     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
926 
927   if (Subtarget.hasStdExtZbp())
928     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
929 
930   if (Subtarget.hasStdExtZbb())
931     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
932 
933   if (Subtarget.hasStdExtZbkb())
934     setTargetDAGCombine(ISD::BITREVERSE);
935   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
936     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
937   if (Subtarget.hasStdExtF())
938     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
939                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
940   if (Subtarget.hasVInstructions())
941     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
942                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
943                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
944 
945   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
946   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
947 }
948 
949 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
950                                             LLVMContext &Context,
951                                             EVT VT) const {
952   if (!VT.isVector())
953     return getPointerTy(DL);
954   if (Subtarget.hasVInstructions() &&
955       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
956     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
957   return VT.changeVectorElementTypeToInteger();
958 }
959 
960 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
961   return Subtarget.getXLenVT();
962 }
963 
964 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
965                                              const CallInst &I,
966                                              MachineFunction &MF,
967                                              unsigned Intrinsic) const {
968   auto &DL = I.getModule()->getDataLayout();
969   switch (Intrinsic) {
970   default:
971     return false;
972   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
973   case Intrinsic::riscv_masked_atomicrmw_add_i32:
974   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
975   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
976   case Intrinsic::riscv_masked_atomicrmw_max_i32:
977   case Intrinsic::riscv_masked_atomicrmw_min_i32:
978   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
979   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
980   case Intrinsic::riscv_masked_cmpxchg_i32:
981     Info.opc = ISD::INTRINSIC_W_CHAIN;
982     Info.memVT = MVT::i32;
983     Info.ptrVal = I.getArgOperand(0);
984     Info.offset = 0;
985     Info.align = Align(4);
986     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
987                  MachineMemOperand::MOVolatile;
988     return true;
989   case Intrinsic::riscv_masked_strided_load:
990     Info.opc = ISD::INTRINSIC_W_CHAIN;
991     Info.ptrVal = I.getArgOperand(1);
992     Info.memVT = getValueType(DL, I.getType()->getScalarType());
993     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
994     Info.size = MemoryLocation::UnknownSize;
995     Info.flags |= MachineMemOperand::MOLoad;
996     return true;
997   case Intrinsic::riscv_masked_strided_store:
998     Info.opc = ISD::INTRINSIC_VOID;
999     Info.ptrVal = I.getArgOperand(1);
1000     Info.memVT =
1001         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1002     Info.align = Align(
1003         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1004         8);
1005     Info.size = MemoryLocation::UnknownSize;
1006     Info.flags |= MachineMemOperand::MOStore;
1007     return true;
1008   case Intrinsic::riscv_seg2_load:
1009   case Intrinsic::riscv_seg3_load:
1010   case Intrinsic::riscv_seg4_load:
1011   case Intrinsic::riscv_seg5_load:
1012   case Intrinsic::riscv_seg6_load:
1013   case Intrinsic::riscv_seg7_load:
1014   case Intrinsic::riscv_seg8_load:
1015     Info.opc = ISD::INTRINSIC_W_CHAIN;
1016     Info.ptrVal = I.getArgOperand(0);
1017     Info.memVT =
1018         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1019     Info.align =
1020         Align(DL.getTypeSizeInBits(
1021                   I.getType()->getStructElementType(0)->getScalarType()) /
1022               8);
1023     Info.size = MemoryLocation::UnknownSize;
1024     Info.flags |= MachineMemOperand::MOLoad;
1025     return true;
1026   }
1027 }
1028 
1029 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1030                                                 const AddrMode &AM, Type *Ty,
1031                                                 unsigned AS,
1032                                                 Instruction *I) const {
1033   // No global is ever allowed as a base.
1034   if (AM.BaseGV)
1035     return false;
1036 
1037   // RVV instructions only support register addressing.
1038   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1039     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1040 
1041   // Require a 12-bit signed offset.
1042   if (!isInt<12>(AM.BaseOffs))
1043     return false;
1044 
1045   switch (AM.Scale) {
1046   case 0: // "r+i" or just "i", depending on HasBaseReg.
1047     break;
1048   case 1:
1049     if (!AM.HasBaseReg) // allow "r+i".
1050       break;
1051     return false; // disallow "r+r" or "r+r+i".
1052   default:
1053     return false;
1054   }
1055 
1056   return true;
1057 }
1058 
1059 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1060   return isInt<12>(Imm);
1061 }
1062 
1063 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1064   return isInt<12>(Imm);
1065 }
1066 
1067 // On RV32, 64-bit integers are split into their high and low parts and held
1068 // in two different registers, so the trunc is free since the low register can
1069 // just be used.
1070 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1071   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1072     return false;
1073   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1074   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1075   return (SrcBits == 64 && DestBits == 32);
1076 }
1077 
1078 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1079   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1080       !SrcVT.isInteger() || !DstVT.isInteger())
1081     return false;
1082   unsigned SrcBits = SrcVT.getSizeInBits();
1083   unsigned DestBits = DstVT.getSizeInBits();
1084   return (SrcBits == 64 && DestBits == 32);
1085 }
1086 
1087 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1088   // Zexts are free if they can be combined with a load.
1089   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1090   // poorly with type legalization of compares preferring sext.
1091   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1092     EVT MemVT = LD->getMemoryVT();
1093     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1094         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1095          LD->getExtensionType() == ISD::ZEXTLOAD))
1096       return true;
1097   }
1098 
1099   return TargetLowering::isZExtFree(Val, VT2);
1100 }
1101 
1102 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1103   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1104 }
1105 
1106 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1107   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1108 }
1109 
1110 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1111   return Subtarget.hasStdExtZbb();
1112 }
1113 
1114 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1115   return Subtarget.hasStdExtZbb();
1116 }
1117 
1118 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1119   EVT VT = Y.getValueType();
1120 
1121   // FIXME: Support vectors once we have tests.
1122   if (VT.isVector())
1123     return false;
1124 
1125   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1126           Subtarget.hasStdExtZbkb()) &&
1127          !isa<ConstantSDNode>(Y);
1128 }
1129 
1130 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1131   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1132   auto *C = dyn_cast<ConstantSDNode>(Y);
1133   return C && C->getAPIntValue().ule(10);
1134 }
1135 
1136 bool RISCVTargetLowering::
1137     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1138         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1139         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1140         SelectionDAG &DAG) const {
1141   // One interesting pattern that we'd want to form is 'bit extract':
1142   //   ((1 >> Y) & 1) ==/!= 0
1143   // But we also need to be careful not to try to reverse that fold.
1144 
1145   // Is this '((1 >> Y) & 1)'?
1146   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1147     return false; // Keep the 'bit extract' pattern.
1148 
1149   // Will this be '((1 >> Y) & 1)' after the transform?
1150   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1151     return true; // Do form the 'bit extract' pattern.
1152 
1153   // If 'X' is a constant, and we transform, then we will immediately
1154   // try to undo the fold, thus causing endless combine loop.
1155   // So only do the transform if X is not a constant. This matches the default
1156   // implementation of this function.
1157   return !XC;
1158 }
1159 
1160 /// Check if sinking \p I's operands to I's basic block is profitable, because
1161 /// the operands can be folded into a target instruction, e.g.
1162 /// splats of scalars can fold into vector instructions.
1163 bool RISCVTargetLowering::shouldSinkOperands(
1164     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1165   using namespace llvm::PatternMatch;
1166 
1167   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1168     return false;
1169 
1170   auto IsSinker = [&](Instruction *I, int Operand) {
1171     switch (I->getOpcode()) {
1172     case Instruction::Add:
1173     case Instruction::Sub:
1174     case Instruction::Mul:
1175     case Instruction::And:
1176     case Instruction::Or:
1177     case Instruction::Xor:
1178     case Instruction::FAdd:
1179     case Instruction::FSub:
1180     case Instruction::FMul:
1181     case Instruction::FDiv:
1182     case Instruction::ICmp:
1183     case Instruction::FCmp:
1184       return true;
1185     case Instruction::Shl:
1186     case Instruction::LShr:
1187     case Instruction::AShr:
1188     case Instruction::UDiv:
1189     case Instruction::SDiv:
1190     case Instruction::URem:
1191     case Instruction::SRem:
1192       return Operand == 1;
1193     case Instruction::Call:
1194       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1195         switch (II->getIntrinsicID()) {
1196         case Intrinsic::fma:
1197         case Intrinsic::vp_fma:
1198           return Operand == 0 || Operand == 1;
1199         // FIXME: Our patterns can only match vx/vf instructions when the splat
1200         // it on the RHS, because TableGen doesn't recognize our VP operations
1201         // as commutative.
1202         case Intrinsic::vp_add:
1203         case Intrinsic::vp_mul:
1204         case Intrinsic::vp_and:
1205         case Intrinsic::vp_or:
1206         case Intrinsic::vp_xor:
1207         case Intrinsic::vp_fadd:
1208         case Intrinsic::vp_fmul:
1209         case Intrinsic::vp_shl:
1210         case Intrinsic::vp_lshr:
1211         case Intrinsic::vp_ashr:
1212         case Intrinsic::vp_udiv:
1213         case Intrinsic::vp_sdiv:
1214         case Intrinsic::vp_urem:
1215         case Intrinsic::vp_srem:
1216           return Operand == 1;
1217         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1218         // explicit patterns for both LHS and RHS (as 'vr' versions).
1219         case Intrinsic::vp_sub:
1220         case Intrinsic::vp_fsub:
1221         case Intrinsic::vp_fdiv:
1222           return Operand == 0 || Operand == 1;
1223         default:
1224           return false;
1225         }
1226       }
1227       return false;
1228     default:
1229       return false;
1230     }
1231   };
1232 
1233   for (auto OpIdx : enumerate(I->operands())) {
1234     if (!IsSinker(I, OpIdx.index()))
1235       continue;
1236 
1237     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1238     // Make sure we are not already sinking this operand
1239     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1240       continue;
1241 
1242     // We are looking for a splat that can be sunk.
1243     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1244                              m_Undef(), m_ZeroMask())))
1245       continue;
1246 
1247     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1248     // and vector registers
1249     for (Use &U : Op->uses()) {
1250       Instruction *Insn = cast<Instruction>(U.getUser());
1251       if (!IsSinker(Insn, U.getOperandNo()))
1252         return false;
1253     }
1254 
1255     Ops.push_back(&Op->getOperandUse(0));
1256     Ops.push_back(&OpIdx.value());
1257   }
1258   return true;
1259 }
1260 
1261 bool RISCVTargetLowering::isOffsetFoldingLegal(
1262     const GlobalAddressSDNode *GA) const {
1263   // In order to maximise the opportunity for common subexpression elimination,
1264   // keep a separate ADD node for the global address offset instead of folding
1265   // it in the global address node. Later peephole optimisations may choose to
1266   // fold it back in when profitable.
1267   return false;
1268 }
1269 
1270 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1271                                        bool ForCodeSize) const {
1272   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1273   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1274     return false;
1275   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1276     return false;
1277   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1278     return false;
1279   return Imm.isZero();
1280 }
1281 
1282 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1283   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1284          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1285          (VT == MVT::f64 && Subtarget.hasStdExtD());
1286 }
1287 
1288 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1289                                                       CallingConv::ID CC,
1290                                                       EVT VT) const {
1291   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1292   // We might still end up using a GPR but that will be decided based on ABI.
1293   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1294   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1295     return MVT::f32;
1296 
1297   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1298 }
1299 
1300 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1301                                                            CallingConv::ID CC,
1302                                                            EVT VT) const {
1303   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1304   // We might still end up using a GPR but that will be decided based on ABI.
1305   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1306   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1307     return 1;
1308 
1309   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1310 }
1311 
1312 // Changes the condition code and swaps operands if necessary, so the SetCC
1313 // operation matches one of the comparisons supported directly by branches
1314 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1315 // with 1/-1.
1316 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1317                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1318   // Convert X > -1 to X >= 0.
1319   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1320     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1321     CC = ISD::SETGE;
1322     return;
1323   }
1324   // Convert X < 1 to 0 >= X.
1325   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1326     RHS = LHS;
1327     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1328     CC = ISD::SETGE;
1329     return;
1330   }
1331 
1332   switch (CC) {
1333   default:
1334     break;
1335   case ISD::SETGT:
1336   case ISD::SETLE:
1337   case ISD::SETUGT:
1338   case ISD::SETULE:
1339     CC = ISD::getSetCCSwappedOperands(CC);
1340     std::swap(LHS, RHS);
1341     break;
1342   }
1343 }
1344 
1345 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1346   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1347   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1348   if (VT.getVectorElementType() == MVT::i1)
1349     KnownSize *= 8;
1350 
1351   switch (KnownSize) {
1352   default:
1353     llvm_unreachable("Invalid LMUL.");
1354   case 8:
1355     return RISCVII::VLMUL::LMUL_F8;
1356   case 16:
1357     return RISCVII::VLMUL::LMUL_F4;
1358   case 32:
1359     return RISCVII::VLMUL::LMUL_F2;
1360   case 64:
1361     return RISCVII::VLMUL::LMUL_1;
1362   case 128:
1363     return RISCVII::VLMUL::LMUL_2;
1364   case 256:
1365     return RISCVII::VLMUL::LMUL_4;
1366   case 512:
1367     return RISCVII::VLMUL::LMUL_8;
1368   }
1369 }
1370 
1371 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1372   switch (LMul) {
1373   default:
1374     llvm_unreachable("Invalid LMUL.");
1375   case RISCVII::VLMUL::LMUL_F8:
1376   case RISCVII::VLMUL::LMUL_F4:
1377   case RISCVII::VLMUL::LMUL_F2:
1378   case RISCVII::VLMUL::LMUL_1:
1379     return RISCV::VRRegClassID;
1380   case RISCVII::VLMUL::LMUL_2:
1381     return RISCV::VRM2RegClassID;
1382   case RISCVII::VLMUL::LMUL_4:
1383     return RISCV::VRM4RegClassID;
1384   case RISCVII::VLMUL::LMUL_8:
1385     return RISCV::VRM8RegClassID;
1386   }
1387 }
1388 
1389 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1390   RISCVII::VLMUL LMUL = getLMUL(VT);
1391   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1392       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1393       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1394       LMUL == RISCVII::VLMUL::LMUL_1) {
1395     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1396                   "Unexpected subreg numbering");
1397     return RISCV::sub_vrm1_0 + Index;
1398   }
1399   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1400     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1401                   "Unexpected subreg numbering");
1402     return RISCV::sub_vrm2_0 + Index;
1403   }
1404   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1405     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1406                   "Unexpected subreg numbering");
1407     return RISCV::sub_vrm4_0 + Index;
1408   }
1409   llvm_unreachable("Invalid vector type.");
1410 }
1411 
1412 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1413   if (VT.getVectorElementType() == MVT::i1)
1414     return RISCV::VRRegClassID;
1415   return getRegClassIDForLMUL(getLMUL(VT));
1416 }
1417 
1418 // Attempt to decompose a subvector insert/extract between VecVT and
1419 // SubVecVT via subregister indices. Returns the subregister index that
1420 // can perform the subvector insert/extract with the given element index, as
1421 // well as the index corresponding to any leftover subvectors that must be
1422 // further inserted/extracted within the register class for SubVecVT.
1423 std::pair<unsigned, unsigned>
1424 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1425     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1426     const RISCVRegisterInfo *TRI) {
1427   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1428                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1429                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1430                 "Register classes not ordered");
1431   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1432   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1433   // Try to compose a subregister index that takes us from the incoming
1434   // LMUL>1 register class down to the outgoing one. At each step we half
1435   // the LMUL:
1436   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1437   // Note that this is not guaranteed to find a subregister index, such as
1438   // when we are extracting from one VR type to another.
1439   unsigned SubRegIdx = RISCV::NoSubRegister;
1440   for (const unsigned RCID :
1441        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1442     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1443       VecVT = VecVT.getHalfNumVectorElementsVT();
1444       bool IsHi =
1445           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1446       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1447                                             getSubregIndexByMVT(VecVT, IsHi));
1448       if (IsHi)
1449         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1450     }
1451   return {SubRegIdx, InsertExtractIdx};
1452 }
1453 
1454 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1455 // stores for those types.
1456 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1457   return !Subtarget.useRVVForFixedLengthVectors() ||
1458          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1459 }
1460 
1461 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1462   if (ScalarTy->isPointerTy())
1463     return true;
1464 
1465   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1466       ScalarTy->isIntegerTy(32))
1467     return true;
1468 
1469   if (ScalarTy->isIntegerTy(64))
1470     return Subtarget.hasVInstructionsI64();
1471 
1472   if (ScalarTy->isHalfTy())
1473     return Subtarget.hasVInstructionsF16();
1474   if (ScalarTy->isFloatTy())
1475     return Subtarget.hasVInstructionsF32();
1476   if (ScalarTy->isDoubleTy())
1477     return Subtarget.hasVInstructionsF64();
1478 
1479   return false;
1480 }
1481 
1482 static SDValue getVLOperand(SDValue Op) {
1483   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1484           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1485          "Unexpected opcode");
1486   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1487   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1488   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1489       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1490   if (!II)
1491     return SDValue();
1492   return Op.getOperand(II->VLOperand + 1 + HasChain);
1493 }
1494 
1495 static bool useRVVForFixedLengthVectorVT(MVT VT,
1496                                          const RISCVSubtarget &Subtarget) {
1497   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1498   if (!Subtarget.useRVVForFixedLengthVectors())
1499     return false;
1500 
1501   // We only support a set of vector types with a consistent maximum fixed size
1502   // across all supported vector element types to avoid legalization issues.
1503   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1504   // fixed-length vector type we support is 1024 bytes.
1505   if (VT.getFixedSizeInBits() > 1024 * 8)
1506     return false;
1507 
1508   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1509 
1510   MVT EltVT = VT.getVectorElementType();
1511 
1512   // Don't use RVV for vectors we cannot scalarize if required.
1513   switch (EltVT.SimpleTy) {
1514   // i1 is supported but has different rules.
1515   default:
1516     return false;
1517   case MVT::i1:
1518     // Masks can only use a single register.
1519     if (VT.getVectorNumElements() > MinVLen)
1520       return false;
1521     MinVLen /= 8;
1522     break;
1523   case MVT::i8:
1524   case MVT::i16:
1525   case MVT::i32:
1526     break;
1527   case MVT::i64:
1528     if (!Subtarget.hasVInstructionsI64())
1529       return false;
1530     break;
1531   case MVT::f16:
1532     if (!Subtarget.hasVInstructionsF16())
1533       return false;
1534     break;
1535   case MVT::f32:
1536     if (!Subtarget.hasVInstructionsF32())
1537       return false;
1538     break;
1539   case MVT::f64:
1540     if (!Subtarget.hasVInstructionsF64())
1541       return false;
1542     break;
1543   }
1544 
1545   // Reject elements larger than ELEN.
1546   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1547     return false;
1548 
1549   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1550   // Don't use RVV for types that don't fit.
1551   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1552     return false;
1553 
1554   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1555   // the base fixed length RVV support in place.
1556   if (!VT.isPow2VectorType())
1557     return false;
1558 
1559   return true;
1560 }
1561 
1562 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1563   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1564 }
1565 
1566 // Return the largest legal scalable vector type that matches VT's element type.
1567 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1568                                             const RISCVSubtarget &Subtarget) {
1569   // This may be called before legal types are setup.
1570   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1571           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1572          "Expected legal fixed length vector!");
1573 
1574   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1575   unsigned MaxELen = Subtarget.getELEN();
1576 
1577   MVT EltVT = VT.getVectorElementType();
1578   switch (EltVT.SimpleTy) {
1579   default:
1580     llvm_unreachable("unexpected element type for RVV container");
1581   case MVT::i1:
1582   case MVT::i8:
1583   case MVT::i16:
1584   case MVT::i32:
1585   case MVT::i64:
1586   case MVT::f16:
1587   case MVT::f32:
1588   case MVT::f64: {
1589     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1590     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1591     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1592     unsigned NumElts =
1593         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1594     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1595     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1596     return MVT::getScalableVectorVT(EltVT, NumElts);
1597   }
1598   }
1599 }
1600 
1601 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1602                                             const RISCVSubtarget &Subtarget) {
1603   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1604                                           Subtarget);
1605 }
1606 
1607 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1608   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1609 }
1610 
1611 // Grow V to consume an entire RVV register.
1612 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1613                                        const RISCVSubtarget &Subtarget) {
1614   assert(VT.isScalableVector() &&
1615          "Expected to convert into a scalable vector!");
1616   assert(V.getValueType().isFixedLengthVector() &&
1617          "Expected a fixed length vector operand!");
1618   SDLoc DL(V);
1619   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1620   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1621 }
1622 
1623 // Shrink V so it's just big enough to maintain a VT's worth of data.
1624 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1625                                          const RISCVSubtarget &Subtarget) {
1626   assert(VT.isFixedLengthVector() &&
1627          "Expected to convert into a fixed length vector!");
1628   assert(V.getValueType().isScalableVector() &&
1629          "Expected a scalable vector operand!");
1630   SDLoc DL(V);
1631   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1632   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1633 }
1634 
1635 /// Return the type of the mask type suitable for masking the provided
1636 /// vector type.  This is simply an i1 element type vector of the same
1637 /// (possibly scalable) length.
1638 static MVT getMaskTypeFor(EVT VecVT) {
1639   assert(VecVT.isVector());
1640   ElementCount EC = VecVT.getVectorElementCount();
1641   return MVT::getVectorVT(MVT::i1, EC);
1642 }
1643 
1644 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1645 /// vector length VL.  .
1646 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1647                               SelectionDAG &DAG) {
1648   MVT MaskVT = getMaskTypeFor(VecVT);
1649   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1650 }
1651 
1652 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1653 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1654 // the vector type that it is contained in.
1655 static std::pair<SDValue, SDValue>
1656 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1657                 const RISCVSubtarget &Subtarget) {
1658   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1659   MVT XLenVT = Subtarget.getXLenVT();
1660   SDValue VL = VecVT.isFixedLengthVector()
1661                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1662                    : DAG.getRegister(RISCV::X0, XLenVT);
1663   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1664   return {Mask, VL};
1665 }
1666 
1667 // As above but assuming the given type is a scalable vector type.
1668 static std::pair<SDValue, SDValue>
1669 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1670                         const RISCVSubtarget &Subtarget) {
1671   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1672   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1673 }
1674 
1675 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1676 // of either is (currently) supported. This can get us into an infinite loop
1677 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1678 // as a ..., etc.
1679 // Until either (or both) of these can reliably lower any node, reporting that
1680 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1681 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1682 // which is not desirable.
1683 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1684     EVT VT, unsigned DefinedValues) const {
1685   return false;
1686 }
1687 
1688 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1689                                   const RISCVSubtarget &Subtarget) {
1690   // RISCV FP-to-int conversions saturate to the destination register size, but
1691   // don't produce 0 for nan. We can use a conversion instruction and fix the
1692   // nan case with a compare and a select.
1693   SDValue Src = Op.getOperand(0);
1694 
1695   EVT DstVT = Op.getValueType();
1696   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1697 
1698   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1699   unsigned Opc;
1700   if (SatVT == DstVT)
1701     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1702   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1703     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1704   else
1705     return SDValue();
1706   // FIXME: Support other SatVTs by clamping before or after the conversion.
1707 
1708   SDLoc DL(Op);
1709   SDValue FpToInt = DAG.getNode(
1710       Opc, DL, DstVT, Src,
1711       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1712 
1713   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1714   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1715 }
1716 
1717 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1718 // and back. Taking care to avoid converting values that are nan or already
1719 // correct.
1720 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1721 // have FRM dependencies modeled yet.
1722 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1723   MVT VT = Op.getSimpleValueType();
1724   assert(VT.isVector() && "Unexpected type");
1725 
1726   SDLoc DL(Op);
1727 
1728   // Freeze the source since we are increasing the number of uses.
1729   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1730 
1731   // Truncate to integer and convert back to FP.
1732   MVT IntVT = VT.changeVectorElementTypeToInteger();
1733   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1734   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1735 
1736   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1737 
1738   if (Op.getOpcode() == ISD::FCEIL) {
1739     // If the truncated value is the greater than or equal to the original
1740     // value, we've computed the ceil. Otherwise, we went the wrong way and
1741     // need to increase by 1.
1742     // FIXME: This should use a masked operation. Handle here or in isel?
1743     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1744                                  DAG.getConstantFP(1.0, DL, VT));
1745     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1746     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1747   } else if (Op.getOpcode() == ISD::FFLOOR) {
1748     // If the truncated value is the less than or equal to the original value,
1749     // we've computed the floor. Otherwise, we went the wrong way and need to
1750     // decrease by 1.
1751     // FIXME: This should use a masked operation. Handle here or in isel?
1752     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1753                                  DAG.getConstantFP(1.0, DL, VT));
1754     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1755     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1756   }
1757 
1758   // Restore the original sign so that -0.0 is preserved.
1759   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1760 
1761   // Determine the largest integer that can be represented exactly. This and
1762   // values larger than it don't have any fractional bits so don't need to
1763   // be converted.
1764   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1765   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1766   APFloat MaxVal = APFloat(FltSem);
1767   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1768                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1769   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1770 
1771   // If abs(Src) was larger than MaxVal or nan, keep it.
1772   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1773   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1774   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1775 }
1776 
1777 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1778 // This mode isn't supported in vector hardware on RISCV. But as long as we
1779 // aren't compiling with trapping math, we can emulate this with
1780 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1781 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1782 // dependencies modeled yet.
1783 // FIXME: Use masked operations to avoid final merge.
1784 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1785   MVT VT = Op.getSimpleValueType();
1786   assert(VT.isVector() && "Unexpected type");
1787 
1788   SDLoc DL(Op);
1789 
1790   // Freeze the source since we are increasing the number of uses.
1791   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1792 
1793   // We do the conversion on the absolute value and fix the sign at the end.
1794   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1795 
1796   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1797   bool Ignored;
1798   APFloat Point5Pred = APFloat(0.5f);
1799   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1800   Point5Pred.next(/*nextDown*/ true);
1801 
1802   // Add the adjustment.
1803   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1804                                DAG.getConstantFP(Point5Pred, DL, VT));
1805 
1806   // Truncate to integer and convert back to fp.
1807   MVT IntVT = VT.changeVectorElementTypeToInteger();
1808   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1809   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1810 
1811   // Restore the original sign.
1812   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1813 
1814   // Determine the largest integer that can be represented exactly. This and
1815   // values larger than it don't have any fractional bits so don't need to
1816   // be converted.
1817   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1818   APFloat MaxVal = APFloat(FltSem);
1819   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1820                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1821   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1822 
1823   // If abs(Src) was larger than MaxVal or nan, keep it.
1824   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1825   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1826   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1827 }
1828 
1829 struct VIDSequence {
1830   int64_t StepNumerator;
1831   unsigned StepDenominator;
1832   int64_t Addend;
1833 };
1834 
1835 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1836 // to the (non-zero) step S and start value X. This can be then lowered as the
1837 // RVV sequence (VID * S) + X, for example.
1838 // The step S is represented as an integer numerator divided by a positive
1839 // denominator. Note that the implementation currently only identifies
1840 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1841 // cannot detect 2/3, for example.
1842 // Note that this method will also match potentially unappealing index
1843 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1844 // determine whether this is worth generating code for.
1845 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1846   unsigned NumElts = Op.getNumOperands();
1847   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1848   if (!Op.getValueType().isInteger())
1849     return None;
1850 
1851   Optional<unsigned> SeqStepDenom;
1852   Optional<int64_t> SeqStepNum, SeqAddend;
1853   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1854   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1855   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1856     // Assume undef elements match the sequence; we just have to be careful
1857     // when interpolating across them.
1858     if (Op.getOperand(Idx).isUndef())
1859       continue;
1860     // The BUILD_VECTOR must be all constants.
1861     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1862       return None;
1863 
1864     uint64_t Val = Op.getConstantOperandVal(Idx) &
1865                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1866 
1867     if (PrevElt) {
1868       // Calculate the step since the last non-undef element, and ensure
1869       // it's consistent across the entire sequence.
1870       unsigned IdxDiff = Idx - PrevElt->second;
1871       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1872 
1873       // A zero-value value difference means that we're somewhere in the middle
1874       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1875       // step change before evaluating the sequence.
1876       if (ValDiff == 0)
1877         continue;
1878 
1879       int64_t Remainder = ValDiff % IdxDiff;
1880       // Normalize the step if it's greater than 1.
1881       if (Remainder != ValDiff) {
1882         // The difference must cleanly divide the element span.
1883         if (Remainder != 0)
1884           return None;
1885         ValDiff /= IdxDiff;
1886         IdxDiff = 1;
1887       }
1888 
1889       if (!SeqStepNum)
1890         SeqStepNum = ValDiff;
1891       else if (ValDiff != SeqStepNum)
1892         return None;
1893 
1894       if (!SeqStepDenom)
1895         SeqStepDenom = IdxDiff;
1896       else if (IdxDiff != *SeqStepDenom)
1897         return None;
1898     }
1899 
1900     // Record this non-undef element for later.
1901     if (!PrevElt || PrevElt->first != Val)
1902       PrevElt = std::make_pair(Val, Idx);
1903   }
1904 
1905   // We need to have logged a step for this to count as a legal index sequence.
1906   if (!SeqStepNum || !SeqStepDenom)
1907     return None;
1908 
1909   // Loop back through the sequence and validate elements we might have skipped
1910   // while waiting for a valid step. While doing this, log any sequence addend.
1911   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1912     if (Op.getOperand(Idx).isUndef())
1913       continue;
1914     uint64_t Val = Op.getConstantOperandVal(Idx) &
1915                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1916     uint64_t ExpectedVal =
1917         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1918     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1919     if (!SeqAddend)
1920       SeqAddend = Addend;
1921     else if (Addend != SeqAddend)
1922       return None;
1923   }
1924 
1925   assert(SeqAddend && "Must have an addend if we have a step");
1926 
1927   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1928 }
1929 
1930 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1931 // and lower it as a VRGATHER_VX_VL from the source vector.
1932 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1933                                   SelectionDAG &DAG,
1934                                   const RISCVSubtarget &Subtarget) {
1935   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1936     return SDValue();
1937   SDValue Vec = SplatVal.getOperand(0);
1938   // Only perform this optimization on vectors of the same size for simplicity.
1939   if (Vec.getValueType() != VT)
1940     return SDValue();
1941   SDValue Idx = SplatVal.getOperand(1);
1942   // The index must be a legal type.
1943   if (Idx.getValueType() != Subtarget.getXLenVT())
1944     return SDValue();
1945 
1946   MVT ContainerVT = VT;
1947   if (VT.isFixedLengthVector()) {
1948     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1949     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1950   }
1951 
1952   SDValue Mask, VL;
1953   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1954 
1955   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
1956                                Idx, Mask, VL);
1957 
1958   if (!VT.isFixedLengthVector())
1959     return Gather;
1960 
1961   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1962 }
1963 
1964 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1965                                  const RISCVSubtarget &Subtarget) {
1966   MVT VT = Op.getSimpleValueType();
1967   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1968 
1969   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1970 
1971   SDLoc DL(Op);
1972   SDValue Mask, VL;
1973   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1974 
1975   MVT XLenVT = Subtarget.getXLenVT();
1976   unsigned NumElts = Op.getNumOperands();
1977 
1978   if (VT.getVectorElementType() == MVT::i1) {
1979     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1980       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1981       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1982     }
1983 
1984     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1985       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1986       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1987     }
1988 
1989     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1990     // scalar integer chunks whose bit-width depends on the number of mask
1991     // bits and XLEN.
1992     // First, determine the most appropriate scalar integer type to use. This
1993     // is at most XLenVT, but may be shrunk to a smaller vector element type
1994     // according to the size of the final vector - use i8 chunks rather than
1995     // XLenVT if we're producing a v8i1. This results in more consistent
1996     // codegen across RV32 and RV64.
1997     unsigned NumViaIntegerBits =
1998         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1999     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2000     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2001       // If we have to use more than one INSERT_VECTOR_ELT then this
2002       // optimization is likely to increase code size; avoid peforming it in
2003       // such a case. We can use a load from a constant pool in this case.
2004       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2005         return SDValue();
2006       // Now we can create our integer vector type. Note that it may be larger
2007       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2008       MVT IntegerViaVecVT =
2009           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2010                            divideCeil(NumElts, NumViaIntegerBits));
2011 
2012       uint64_t Bits = 0;
2013       unsigned BitPos = 0, IntegerEltIdx = 0;
2014       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2015 
2016       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2017         // Once we accumulate enough bits to fill our scalar type, insert into
2018         // our vector and clear our accumulated data.
2019         if (I != 0 && I % NumViaIntegerBits == 0) {
2020           if (NumViaIntegerBits <= 32)
2021             Bits = SignExtend64<32>(Bits);
2022           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2023           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2024                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2025           Bits = 0;
2026           BitPos = 0;
2027           IntegerEltIdx++;
2028         }
2029         SDValue V = Op.getOperand(I);
2030         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2031         Bits |= ((uint64_t)BitValue << BitPos);
2032       }
2033 
2034       // Insert the (remaining) scalar value into position in our integer
2035       // vector type.
2036       if (NumViaIntegerBits <= 32)
2037         Bits = SignExtend64<32>(Bits);
2038       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2039       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2040                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2041 
2042       if (NumElts < NumViaIntegerBits) {
2043         // If we're producing a smaller vector than our minimum legal integer
2044         // type, bitcast to the equivalent (known-legal) mask type, and extract
2045         // our final mask.
2046         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2047         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2048         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2049                           DAG.getConstant(0, DL, XLenVT));
2050       } else {
2051         // Else we must have produced an integer type with the same size as the
2052         // mask type; bitcast for the final result.
2053         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2054         Vec = DAG.getBitcast(VT, Vec);
2055       }
2056 
2057       return Vec;
2058     }
2059 
2060     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2061     // vector type, we have a legal equivalently-sized i8 type, so we can use
2062     // that.
2063     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2064     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2065 
2066     SDValue WideVec;
2067     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2068       // For a splat, perform a scalar truncate before creating the wider
2069       // vector.
2070       assert(Splat.getValueType() == XLenVT &&
2071              "Unexpected type for i1 splat value");
2072       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2073                           DAG.getConstant(1, DL, XLenVT));
2074       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2075     } else {
2076       SmallVector<SDValue, 8> Ops(Op->op_values());
2077       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2078       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2079       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2080     }
2081 
2082     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2083   }
2084 
2085   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2086     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2087       return Gather;
2088     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2089                                         : RISCVISD::VMV_V_X_VL;
2090     Splat =
2091         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2092     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2093   }
2094 
2095   // Try and match index sequences, which we can lower to the vid instruction
2096   // with optional modifications. An all-undef vector is matched by
2097   // getSplatValue, above.
2098   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2099     int64_t StepNumerator = SimpleVID->StepNumerator;
2100     unsigned StepDenominator = SimpleVID->StepDenominator;
2101     int64_t Addend = SimpleVID->Addend;
2102 
2103     assert(StepNumerator != 0 && "Invalid step");
2104     bool Negate = false;
2105     int64_t SplatStepVal = StepNumerator;
2106     unsigned StepOpcode = ISD::MUL;
2107     if (StepNumerator != 1) {
2108       if (isPowerOf2_64(std::abs(StepNumerator))) {
2109         Negate = StepNumerator < 0;
2110         StepOpcode = ISD::SHL;
2111         SplatStepVal = Log2_64(std::abs(StepNumerator));
2112       }
2113     }
2114 
2115     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2116     // threshold since it's the immediate value many RVV instructions accept.
2117     // There is no vmul.vi instruction so ensure multiply constant can fit in
2118     // a single addi instruction.
2119     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2120          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2121         isPowerOf2_32(StepDenominator) &&
2122         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2123       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2124       // Convert right out of the scalable type so we can use standard ISD
2125       // nodes for the rest of the computation. If we used scalable types with
2126       // these, we'd lose the fixed-length vector info and generate worse
2127       // vsetvli code.
2128       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2129       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2130           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2131         SDValue SplatStep = DAG.getSplatBuildVector(
2132             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2133         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2134       }
2135       if (StepDenominator != 1) {
2136         SDValue SplatStep = DAG.getSplatBuildVector(
2137             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2138         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2139       }
2140       if (Addend != 0 || Negate) {
2141         SDValue SplatAddend = DAG.getSplatBuildVector(
2142             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2143         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2144       }
2145       return VID;
2146     }
2147   }
2148 
2149   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2150   // when re-interpreted as a vector with a larger element type. For example,
2151   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2152   // could be instead splat as
2153   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2154   // TODO: This optimization could also work on non-constant splats, but it
2155   // would require bit-manipulation instructions to construct the splat value.
2156   SmallVector<SDValue> Sequence;
2157   unsigned EltBitSize = VT.getScalarSizeInBits();
2158   const auto *BV = cast<BuildVectorSDNode>(Op);
2159   if (VT.isInteger() && EltBitSize < 64 &&
2160       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2161       BV->getRepeatedSequence(Sequence) &&
2162       (Sequence.size() * EltBitSize) <= 64) {
2163     unsigned SeqLen = Sequence.size();
2164     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2165     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2166     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2167             ViaIntVT == MVT::i64) &&
2168            "Unexpected sequence type");
2169 
2170     unsigned EltIdx = 0;
2171     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2172     uint64_t SplatValue = 0;
2173     // Construct the amalgamated value which can be splatted as this larger
2174     // vector type.
2175     for (const auto &SeqV : Sequence) {
2176       if (!SeqV.isUndef())
2177         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2178                        << (EltIdx * EltBitSize));
2179       EltIdx++;
2180     }
2181 
2182     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2183     // achieve better constant materializion.
2184     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2185       SplatValue = SignExtend64<32>(SplatValue);
2186 
2187     // Since we can't introduce illegal i64 types at this stage, we can only
2188     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2189     // way we can use RVV instructions to splat.
2190     assert((ViaIntVT.bitsLE(XLenVT) ||
2191             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2192            "Unexpected bitcast sequence");
2193     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2194       SDValue ViaVL =
2195           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2196       MVT ViaContainerVT =
2197           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2198       SDValue Splat =
2199           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2200                       DAG.getUNDEF(ViaContainerVT),
2201                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2202       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2203       return DAG.getBitcast(VT, Splat);
2204     }
2205   }
2206 
2207   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2208   // which constitute a large proportion of the elements. In such cases we can
2209   // splat a vector with the dominant element and make up the shortfall with
2210   // INSERT_VECTOR_ELTs.
2211   // Note that this includes vectors of 2 elements by association. The
2212   // upper-most element is the "dominant" one, allowing us to use a splat to
2213   // "insert" the upper element, and an insert of the lower element at position
2214   // 0, which improves codegen.
2215   SDValue DominantValue;
2216   unsigned MostCommonCount = 0;
2217   DenseMap<SDValue, unsigned> ValueCounts;
2218   unsigned NumUndefElts =
2219       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2220 
2221   // Track the number of scalar loads we know we'd be inserting, estimated as
2222   // any non-zero floating-point constant. Other kinds of element are either
2223   // already in registers or are materialized on demand. The threshold at which
2224   // a vector load is more desirable than several scalar materializion and
2225   // vector-insertion instructions is not known.
2226   unsigned NumScalarLoads = 0;
2227 
2228   for (SDValue V : Op->op_values()) {
2229     if (V.isUndef())
2230       continue;
2231 
2232     ValueCounts.insert(std::make_pair(V, 0));
2233     unsigned &Count = ValueCounts[V];
2234 
2235     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2236       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2237 
2238     // Is this value dominant? In case of a tie, prefer the highest element as
2239     // it's cheaper to insert near the beginning of a vector than it is at the
2240     // end.
2241     if (++Count >= MostCommonCount) {
2242       DominantValue = V;
2243       MostCommonCount = Count;
2244     }
2245   }
2246 
2247   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2248   unsigned NumDefElts = NumElts - NumUndefElts;
2249   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2250 
2251   // Don't perform this optimization when optimizing for size, since
2252   // materializing elements and inserting them tends to cause code bloat.
2253   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2254       ((MostCommonCount > DominantValueCountThreshold) ||
2255        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2256     // Start by splatting the most common element.
2257     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2258 
2259     DenseSet<SDValue> Processed{DominantValue};
2260     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2261     for (const auto &OpIdx : enumerate(Op->ops())) {
2262       const SDValue &V = OpIdx.value();
2263       if (V.isUndef() || !Processed.insert(V).second)
2264         continue;
2265       if (ValueCounts[V] == 1) {
2266         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2267                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2268       } else {
2269         // Blend in all instances of this value using a VSELECT, using a
2270         // mask where each bit signals whether that element is the one
2271         // we're after.
2272         SmallVector<SDValue> Ops;
2273         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2274           return DAG.getConstant(V == V1, DL, XLenVT);
2275         });
2276         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2277                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2278                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2279       }
2280     }
2281 
2282     return Vec;
2283   }
2284 
2285   return SDValue();
2286 }
2287 
2288 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2289                                    SDValue Lo, SDValue Hi, SDValue VL,
2290                                    SelectionDAG &DAG) {
2291   if (!Passthru)
2292     Passthru = DAG.getUNDEF(VT);
2293   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2294     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2295     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2296     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2297     // node in order to try and match RVV vector/scalar instructions.
2298     if ((LoC >> 31) == HiC)
2299       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2300 
2301     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2302     // vmv.v.x whose EEW = 32 to lower it.
2303     auto *Const = dyn_cast<ConstantSDNode>(VL);
2304     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2305       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2306       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2307       // access the subtarget here now.
2308       auto InterVec = DAG.getNode(
2309           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2310                                   DAG.getRegister(RISCV::X0, MVT::i32));
2311       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2312     }
2313   }
2314 
2315   // Fall back to a stack store and stride x0 vector load.
2316   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2317                      Hi, VL);
2318 }
2319 
2320 // Called by type legalization to handle splat of i64 on RV32.
2321 // FIXME: We can optimize this when the type has sign or zero bits in one
2322 // of the halves.
2323 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2324                                    SDValue Scalar, SDValue VL,
2325                                    SelectionDAG &DAG) {
2326   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2327   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2328                            DAG.getConstant(0, DL, MVT::i32));
2329   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2330                            DAG.getConstant(1, DL, MVT::i32));
2331   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2332 }
2333 
2334 // This function lowers a splat of a scalar operand Splat with the vector
2335 // length VL. It ensures the final sequence is type legal, which is useful when
2336 // lowering a splat after type legalization.
2337 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2338                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2339                                 const RISCVSubtarget &Subtarget) {
2340   bool HasPassthru = Passthru && !Passthru.isUndef();
2341   if (!HasPassthru && !Passthru)
2342     Passthru = DAG.getUNDEF(VT);
2343   if (VT.isFloatingPoint()) {
2344     // If VL is 1, we could use vfmv.s.f.
2345     if (isOneConstant(VL))
2346       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2347     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2348   }
2349 
2350   MVT XLenVT = Subtarget.getXLenVT();
2351 
2352   // Simplest case is that the operand needs to be promoted to XLenVT.
2353   if (Scalar.getValueType().bitsLE(XLenVT)) {
2354     // If the operand is a constant, sign extend to increase our chances
2355     // of being able to use a .vi instruction. ANY_EXTEND would become a
2356     // a zero extend and the simm5 check in isel would fail.
2357     // FIXME: Should we ignore the upper bits in isel instead?
2358     unsigned ExtOpc =
2359         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2360     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2361     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2362     // If VL is 1 and the scalar value won't benefit from immediate, we could
2363     // use vmv.s.x.
2364     if (isOneConstant(VL) &&
2365         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2366       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2367     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2368   }
2369 
2370   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2371          "Unexpected scalar for splat lowering!");
2372 
2373   if (isOneConstant(VL) && isNullConstant(Scalar))
2374     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2375                        DAG.getConstant(0, DL, XLenVT), VL);
2376 
2377   // Otherwise use the more complicated splatting algorithm.
2378   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2379 }
2380 
2381 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2382                                 const RISCVSubtarget &Subtarget) {
2383   // We need to be able to widen elements to the next larger integer type.
2384   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2385     return false;
2386 
2387   int Size = Mask.size();
2388   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2389 
2390   int Srcs[] = {-1, -1};
2391   for (int i = 0; i != Size; ++i) {
2392     // Ignore undef elements.
2393     if (Mask[i] < 0)
2394       continue;
2395 
2396     // Is this an even or odd element.
2397     int Pol = i % 2;
2398 
2399     // Ensure we consistently use the same source for this element polarity.
2400     int Src = Mask[i] / Size;
2401     if (Srcs[Pol] < 0)
2402       Srcs[Pol] = Src;
2403     if (Srcs[Pol] != Src)
2404       return false;
2405 
2406     // Make sure the element within the source is appropriate for this element
2407     // in the destination.
2408     int Elt = Mask[i] % Size;
2409     if (Elt != i / 2)
2410       return false;
2411   }
2412 
2413   // We need to find a source for each polarity and they can't be the same.
2414   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2415     return false;
2416 
2417   // Swap the sources if the second source was in the even polarity.
2418   SwapSources = Srcs[0] > Srcs[1];
2419 
2420   return true;
2421 }
2422 
2423 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2424 /// and then extract the original number of elements from the rotated result.
2425 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2426 /// returned rotation amount is for a rotate right, where elements move from
2427 /// higher elements to lower elements. \p LoSrc indicates the first source
2428 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2429 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2430 /// 0 or 1 if a rotation is found.
2431 ///
2432 /// NOTE: We talk about rotate to the right which matches how bit shift and
2433 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2434 /// and the table below write vectors with the lowest elements on the left.
2435 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2436   int Size = Mask.size();
2437 
2438   // We need to detect various ways of spelling a rotation:
2439   //   [11, 12, 13, 14, 15,  0,  1,  2]
2440   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2441   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2442   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2443   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2444   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2445   int Rotation = 0;
2446   LoSrc = -1;
2447   HiSrc = -1;
2448   for (int i = 0; i != Size; ++i) {
2449     int M = Mask[i];
2450     if (M < 0)
2451       continue;
2452 
2453     // Determine where a rotate vector would have started.
2454     int StartIdx = i - (M % Size);
2455     // The identity rotation isn't interesting, stop.
2456     if (StartIdx == 0)
2457       return -1;
2458 
2459     // If we found the tail of a vector the rotation must be the missing
2460     // front. If we found the head of a vector, it must be how much of the
2461     // head.
2462     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2463 
2464     if (Rotation == 0)
2465       Rotation = CandidateRotation;
2466     else if (Rotation != CandidateRotation)
2467       // The rotations don't match, so we can't match this mask.
2468       return -1;
2469 
2470     // Compute which value this mask is pointing at.
2471     int MaskSrc = M < Size ? 0 : 1;
2472 
2473     // Compute which of the two target values this index should be assigned to.
2474     // This reflects whether the high elements are remaining or the low elemnts
2475     // are remaining.
2476     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2477 
2478     // Either set up this value if we've not encountered it before, or check
2479     // that it remains consistent.
2480     if (TargetSrc < 0)
2481       TargetSrc = MaskSrc;
2482     else if (TargetSrc != MaskSrc)
2483       // This may be a rotation, but it pulls from the inputs in some
2484       // unsupported interleaving.
2485       return -1;
2486   }
2487 
2488   // Check that we successfully analyzed the mask, and normalize the results.
2489   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2490   assert((LoSrc >= 0 || HiSrc >= 0) &&
2491          "Failed to find a rotated input vector!");
2492 
2493   return Rotation;
2494 }
2495 
2496 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2497                                    const RISCVSubtarget &Subtarget) {
2498   SDValue V1 = Op.getOperand(0);
2499   SDValue V2 = Op.getOperand(1);
2500   SDLoc DL(Op);
2501   MVT XLenVT = Subtarget.getXLenVT();
2502   MVT VT = Op.getSimpleValueType();
2503   unsigned NumElts = VT.getVectorNumElements();
2504   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2505 
2506   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2507 
2508   SDValue TrueMask, VL;
2509   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2510 
2511   if (SVN->isSplat()) {
2512     const int Lane = SVN->getSplatIndex();
2513     if (Lane >= 0) {
2514       MVT SVT = VT.getVectorElementType();
2515 
2516       // Turn splatted vector load into a strided load with an X0 stride.
2517       SDValue V = V1;
2518       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2519       // with undef.
2520       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2521       int Offset = Lane;
2522       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2523         int OpElements =
2524             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2525         V = V.getOperand(Offset / OpElements);
2526         Offset %= OpElements;
2527       }
2528 
2529       // We need to ensure the load isn't atomic or volatile.
2530       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2531         auto *Ld = cast<LoadSDNode>(V);
2532         Offset *= SVT.getStoreSize();
2533         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2534                                                    TypeSize::Fixed(Offset), DL);
2535 
2536         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2537         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2538           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2539           SDValue IntID =
2540               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2541           SDValue Ops[] = {Ld->getChain(),
2542                            IntID,
2543                            DAG.getUNDEF(ContainerVT),
2544                            NewAddr,
2545                            DAG.getRegister(RISCV::X0, XLenVT),
2546                            VL};
2547           SDValue NewLoad = DAG.getMemIntrinsicNode(
2548               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2549               DAG.getMachineFunction().getMachineMemOperand(
2550                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2551           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2552           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2553         }
2554 
2555         // Otherwise use a scalar load and splat. This will give the best
2556         // opportunity to fold a splat into the operation. ISel can turn it into
2557         // the x0 strided load if we aren't able to fold away the select.
2558         if (SVT.isFloatingPoint())
2559           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2560                           Ld->getPointerInfo().getWithOffset(Offset),
2561                           Ld->getOriginalAlign(),
2562                           Ld->getMemOperand()->getFlags());
2563         else
2564           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2565                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2566                              Ld->getOriginalAlign(),
2567                              Ld->getMemOperand()->getFlags());
2568         DAG.makeEquivalentMemoryOrdering(Ld, V);
2569 
2570         unsigned Opc =
2571             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2572         SDValue Splat =
2573             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2574         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2575       }
2576 
2577       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2578       assert(Lane < (int)NumElts && "Unexpected lane!");
2579       SDValue Gather =
2580           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2581                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2582       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2583     }
2584   }
2585 
2586   ArrayRef<int> Mask = SVN->getMask();
2587 
2588   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2589   // be undef which can be handled with a single SLIDEDOWN/UP.
2590   int LoSrc, HiSrc;
2591   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2592   if (Rotation > 0) {
2593     SDValue LoV, HiV;
2594     if (LoSrc >= 0) {
2595       LoV = LoSrc == 0 ? V1 : V2;
2596       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2597     }
2598     if (HiSrc >= 0) {
2599       HiV = HiSrc == 0 ? V1 : V2;
2600       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2601     }
2602 
2603     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2604     // to slide LoV up by (NumElts - Rotation).
2605     unsigned InvRotate = NumElts - Rotation;
2606 
2607     SDValue Res = DAG.getUNDEF(ContainerVT);
2608     if (HiV) {
2609       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2610       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2611       // causes multiple vsetvlis in some test cases such as lowering
2612       // reduce.mul
2613       SDValue DownVL = VL;
2614       if (LoV)
2615         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2616       Res =
2617           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2618                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2619     }
2620     if (LoV)
2621       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2622                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2623 
2624     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2625   }
2626 
2627   // Detect an interleave shuffle and lower to
2628   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2629   bool SwapSources;
2630   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2631     // Swap sources if needed.
2632     if (SwapSources)
2633       std::swap(V1, V2);
2634 
2635     // Extract the lower half of the vectors.
2636     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2637     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2638                      DAG.getConstant(0, DL, XLenVT));
2639     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2640                      DAG.getConstant(0, DL, XLenVT));
2641 
2642     // Double the element width and halve the number of elements in an int type.
2643     unsigned EltBits = VT.getScalarSizeInBits();
2644     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2645     MVT WideIntVT =
2646         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2647     // Convert this to a scalable vector. We need to base this on the
2648     // destination size to ensure there's always a type with a smaller LMUL.
2649     MVT WideIntContainerVT =
2650         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2651 
2652     // Convert sources to scalable vectors with the same element count as the
2653     // larger type.
2654     MVT HalfContainerVT = MVT::getVectorVT(
2655         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2656     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2657     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2658 
2659     // Cast sources to integer.
2660     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2661     MVT IntHalfVT =
2662         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2663     V1 = DAG.getBitcast(IntHalfVT, V1);
2664     V2 = DAG.getBitcast(IntHalfVT, V2);
2665 
2666     // Freeze V2 since we use it twice and we need to be sure that the add and
2667     // multiply see the same value.
2668     V2 = DAG.getFreeze(V2);
2669 
2670     // Recreate TrueMask using the widened type's element count.
2671     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2672 
2673     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2674     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2675                               V2, TrueMask, VL);
2676     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2677     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2678                                      DAG.getUNDEF(IntHalfVT),
2679                                      DAG.getAllOnesConstant(DL, XLenVT));
2680     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2681                                    V2, Multiplier, TrueMask, VL);
2682     // Add the new copies to our previous addition giving us 2^eltbits copies of
2683     // V2. This is equivalent to shifting V2 left by eltbits. This should
2684     // combine with the vwmulu.vv above to form vwmaccu.vv.
2685     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2686                       TrueMask, VL);
2687     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2688     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2689     // vector VT.
2690     ContainerVT =
2691         MVT::getVectorVT(VT.getVectorElementType(),
2692                          WideIntContainerVT.getVectorElementCount() * 2);
2693     Add = DAG.getBitcast(ContainerVT, Add);
2694     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2695   }
2696 
2697   // Detect shuffles which can be re-expressed as vector selects; these are
2698   // shuffles in which each element in the destination is taken from an element
2699   // at the corresponding index in either source vectors.
2700   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2701     int MaskIndex = MaskIdx.value();
2702     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2703   });
2704 
2705   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2706 
2707   SmallVector<SDValue> MaskVals;
2708   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2709   // merged with a second vrgather.
2710   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2711 
2712   // By default we preserve the original operand order, and use a mask to
2713   // select LHS as true and RHS as false. However, since RVV vector selects may
2714   // feature splats but only on the LHS, we may choose to invert our mask and
2715   // instead select between RHS and LHS.
2716   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2717   bool InvertMask = IsSelect == SwapOps;
2718 
2719   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2720   // half.
2721   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2722 
2723   // Now construct the mask that will be used by the vselect or blended
2724   // vrgather operation. For vrgathers, construct the appropriate indices into
2725   // each vector.
2726   for (int MaskIndex : Mask) {
2727     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2728     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2729     if (!IsSelect) {
2730       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2731       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2732                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2733                                      : DAG.getUNDEF(XLenVT));
2734       GatherIndicesRHS.push_back(
2735           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2736                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2737       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2738         ++LHSIndexCounts[MaskIndex];
2739       if (!IsLHSOrUndefIndex)
2740         ++RHSIndexCounts[MaskIndex - NumElts];
2741     }
2742   }
2743 
2744   if (SwapOps) {
2745     std::swap(V1, V2);
2746     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2747   }
2748 
2749   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2750   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2751   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2752 
2753   if (IsSelect)
2754     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2755 
2756   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2757     // On such a large vector we're unable to use i8 as the index type.
2758     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2759     // may involve vector splitting if we're already at LMUL=8, or our
2760     // user-supplied maximum fixed-length LMUL.
2761     return SDValue();
2762   }
2763 
2764   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2765   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2766   MVT IndexVT = VT.changeTypeToInteger();
2767   // Since we can't introduce illegal index types at this stage, use i16 and
2768   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2769   // than XLenVT.
2770   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2771     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2772     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2773   }
2774 
2775   MVT IndexContainerVT =
2776       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2777 
2778   SDValue Gather;
2779   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2780   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2781   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2782     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2783                               Subtarget);
2784   } else {
2785     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2786     // If only one index is used, we can use a "splat" vrgather.
2787     // TODO: We can splat the most-common index and fix-up any stragglers, if
2788     // that's beneficial.
2789     if (LHSIndexCounts.size() == 1) {
2790       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2791       Gather =
2792           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2793                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2794     } else {
2795       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2796       LHSIndices =
2797           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2798 
2799       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2800                            TrueMask, VL);
2801     }
2802   }
2803 
2804   // If a second vector operand is used by this shuffle, blend it in with an
2805   // additional vrgather.
2806   if (!V2.isUndef()) {
2807     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2808     // If only one index is used, we can use a "splat" vrgather.
2809     // TODO: We can splat the most-common index and fix-up any stragglers, if
2810     // that's beneficial.
2811     if (RHSIndexCounts.size() == 1) {
2812       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2813       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2814                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2815     } else {
2816       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2817       RHSIndices =
2818           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2819       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2820                        VL);
2821     }
2822 
2823     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2824     SelectMask =
2825         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2826 
2827     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2828                          Gather, VL);
2829   }
2830 
2831   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2832 }
2833 
2834 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2835   // Support splats for any type. These should type legalize well.
2836   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2837     return true;
2838 
2839   // Only support legal VTs for other shuffles for now.
2840   if (!isTypeLegal(VT))
2841     return false;
2842 
2843   MVT SVT = VT.getSimpleVT();
2844 
2845   bool SwapSources;
2846   int LoSrc, HiSrc;
2847   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2848          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2849 }
2850 
2851 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2852 // the exponent.
2853 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2854   MVT VT = Op.getSimpleValueType();
2855   unsigned EltSize = VT.getScalarSizeInBits();
2856   SDValue Src = Op.getOperand(0);
2857   SDLoc DL(Op);
2858 
2859   // We need a FP type that can represent the value.
2860   // TODO: Use f16 for i8 when possible?
2861   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2862   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2863 
2864   // Legal types should have been checked in the RISCVTargetLowering
2865   // constructor.
2866   // TODO: Splitting may make sense in some cases.
2867   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2868          "Expected legal float type!");
2869 
2870   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2871   // The trailing zero count is equal to log2 of this single bit value.
2872   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2873     SDValue Neg =
2874         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2875     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2876   }
2877 
2878   // We have a legal FP type, convert to it.
2879   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2880   // Bitcast to integer and shift the exponent to the LSB.
2881   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2882   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2883   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2884   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2885                               DAG.getConstant(ShiftAmt, DL, IntVT));
2886   // Truncate back to original type to allow vnsrl.
2887   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2888   // The exponent contains log2 of the value in biased form.
2889   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2890 
2891   // For trailing zeros, we just need to subtract the bias.
2892   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2893     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2894                        DAG.getConstant(ExponentBias, DL, VT));
2895 
2896   // For leading zeros, we need to remove the bias and convert from log2 to
2897   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2898   unsigned Adjust = ExponentBias + (EltSize - 1);
2899   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2900 }
2901 
2902 // While RVV has alignment restrictions, we should always be able to load as a
2903 // legal equivalently-sized byte-typed vector instead. This method is
2904 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2905 // the load is already correctly-aligned, it returns SDValue().
2906 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2907                                                     SelectionDAG &DAG) const {
2908   auto *Load = cast<LoadSDNode>(Op);
2909   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2910 
2911   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2912                                      Load->getMemoryVT(),
2913                                      *Load->getMemOperand()))
2914     return SDValue();
2915 
2916   SDLoc DL(Op);
2917   MVT VT = Op.getSimpleValueType();
2918   unsigned EltSizeBits = VT.getScalarSizeInBits();
2919   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2920          "Unexpected unaligned RVV load type");
2921   MVT NewVT =
2922       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2923   assert(NewVT.isValid() &&
2924          "Expecting equally-sized RVV vector types to be legal");
2925   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2926                           Load->getPointerInfo(), Load->getOriginalAlign(),
2927                           Load->getMemOperand()->getFlags());
2928   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2929 }
2930 
2931 // While RVV has alignment restrictions, we should always be able to store as a
2932 // legal equivalently-sized byte-typed vector instead. This method is
2933 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2934 // returns SDValue() if the store is already correctly aligned.
2935 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2936                                                      SelectionDAG &DAG) const {
2937   auto *Store = cast<StoreSDNode>(Op);
2938   assert(Store && Store->getValue().getValueType().isVector() &&
2939          "Expected vector store");
2940 
2941   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2942                                      Store->getMemoryVT(),
2943                                      *Store->getMemOperand()))
2944     return SDValue();
2945 
2946   SDLoc DL(Op);
2947   SDValue StoredVal = Store->getValue();
2948   MVT VT = StoredVal.getSimpleValueType();
2949   unsigned EltSizeBits = VT.getScalarSizeInBits();
2950   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2951          "Unexpected unaligned RVV store type");
2952   MVT NewVT =
2953       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2954   assert(NewVT.isValid() &&
2955          "Expecting equally-sized RVV vector types to be legal");
2956   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2957   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2958                       Store->getPointerInfo(), Store->getOriginalAlign(),
2959                       Store->getMemOperand()->getFlags());
2960 }
2961 
2962 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
2963                              const RISCVSubtarget &Subtarget) {
2964   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
2965 
2966   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
2967 
2968   // All simm32 constants should be handled by isel.
2969   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
2970   // this check redundant, but small immediates are common so this check
2971   // should have better compile time.
2972   if (isInt<32>(Imm))
2973     return Op;
2974 
2975   // We only need to cost the immediate, if constant pool lowering is enabled.
2976   if (!Subtarget.useConstantPoolForLargeInts())
2977     return Op;
2978 
2979   RISCVMatInt::InstSeq Seq =
2980       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
2981   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
2982     return Op;
2983 
2984   // Expand to a constant pool using the default expansion code.
2985   return SDValue();
2986 }
2987 
2988 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2989                                             SelectionDAG &DAG) const {
2990   switch (Op.getOpcode()) {
2991   default:
2992     report_fatal_error("unimplemented operand");
2993   case ISD::GlobalAddress:
2994     return lowerGlobalAddress(Op, DAG);
2995   case ISD::BlockAddress:
2996     return lowerBlockAddress(Op, DAG);
2997   case ISD::ConstantPool:
2998     return lowerConstantPool(Op, DAG);
2999   case ISD::JumpTable:
3000     return lowerJumpTable(Op, DAG);
3001   case ISD::GlobalTLSAddress:
3002     return lowerGlobalTLSAddress(Op, DAG);
3003   case ISD::Constant:
3004     return lowerConstant(Op, DAG, Subtarget);
3005   case ISD::SELECT:
3006     return lowerSELECT(Op, DAG);
3007   case ISD::BRCOND:
3008     return lowerBRCOND(Op, DAG);
3009   case ISD::VASTART:
3010     return lowerVASTART(Op, DAG);
3011   case ISD::FRAMEADDR:
3012     return lowerFRAMEADDR(Op, DAG);
3013   case ISD::RETURNADDR:
3014     return lowerRETURNADDR(Op, DAG);
3015   case ISD::SHL_PARTS:
3016     return lowerShiftLeftParts(Op, DAG);
3017   case ISD::SRA_PARTS:
3018     return lowerShiftRightParts(Op, DAG, true);
3019   case ISD::SRL_PARTS:
3020     return lowerShiftRightParts(Op, DAG, false);
3021   case ISD::BITCAST: {
3022     SDLoc DL(Op);
3023     EVT VT = Op.getValueType();
3024     SDValue Op0 = Op.getOperand(0);
3025     EVT Op0VT = Op0.getValueType();
3026     MVT XLenVT = Subtarget.getXLenVT();
3027     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3028       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3029       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3030       return FPConv;
3031     }
3032     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3033         Subtarget.hasStdExtF()) {
3034       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3035       SDValue FPConv =
3036           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3037       return FPConv;
3038     }
3039 
3040     // Consider other scalar<->scalar casts as legal if the types are legal.
3041     // Otherwise expand them.
3042     if (!VT.isVector() && !Op0VT.isVector()) {
3043       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3044         return Op;
3045       return SDValue();
3046     }
3047 
3048     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3049            "Unexpected types");
3050 
3051     if (VT.isFixedLengthVector()) {
3052       // We can handle fixed length vector bitcasts with a simple replacement
3053       // in isel.
3054       if (Op0VT.isFixedLengthVector())
3055         return Op;
3056       // When bitcasting from scalar to fixed-length vector, insert the scalar
3057       // into a one-element vector of the result type, and perform a vector
3058       // bitcast.
3059       if (!Op0VT.isVector()) {
3060         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3061         if (!isTypeLegal(BVT))
3062           return SDValue();
3063         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3064                                               DAG.getUNDEF(BVT), Op0,
3065                                               DAG.getConstant(0, DL, XLenVT)));
3066       }
3067       return SDValue();
3068     }
3069     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3070     // thus: bitcast the vector to a one-element vector type whose element type
3071     // is the same as the result type, and extract the first element.
3072     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3073       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3074       if (!isTypeLegal(BVT))
3075         return SDValue();
3076       SDValue BVec = DAG.getBitcast(BVT, Op0);
3077       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3078                          DAG.getConstant(0, DL, XLenVT));
3079     }
3080     return SDValue();
3081   }
3082   case ISD::INTRINSIC_WO_CHAIN:
3083     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3084   case ISD::INTRINSIC_W_CHAIN:
3085     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3086   case ISD::INTRINSIC_VOID:
3087     return LowerINTRINSIC_VOID(Op, DAG);
3088   case ISD::BSWAP:
3089   case ISD::BITREVERSE: {
3090     MVT VT = Op.getSimpleValueType();
3091     SDLoc DL(Op);
3092     if (Subtarget.hasStdExtZbp()) {
3093       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3094       // Start with the maximum immediate value which is the bitwidth - 1.
3095       unsigned Imm = VT.getSizeInBits() - 1;
3096       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3097       if (Op.getOpcode() == ISD::BSWAP)
3098         Imm &= ~0x7U;
3099       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3100                          DAG.getConstant(Imm, DL, VT));
3101     }
3102     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3103     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3104     // Expand bitreverse to a bswap(rev8) followed by brev8.
3105     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3106     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3107     // as brev8 by an isel pattern.
3108     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3109                        DAG.getConstant(7, DL, VT));
3110   }
3111   case ISD::FSHL:
3112   case ISD::FSHR: {
3113     MVT VT = Op.getSimpleValueType();
3114     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3115     SDLoc DL(Op);
3116     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3117     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3118     // accidentally setting the extra bit.
3119     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3120     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3121                                 DAG.getConstant(ShAmtWidth, DL, VT));
3122     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3123     // instruction use different orders. fshl will return its first operand for
3124     // shift of zero, fshr will return its second operand. fsl and fsr both
3125     // return rs1 so the ISD nodes need to have different operand orders.
3126     // Shift amount is in rs2.
3127     SDValue Op0 = Op.getOperand(0);
3128     SDValue Op1 = Op.getOperand(1);
3129     unsigned Opc = RISCVISD::FSL;
3130     if (Op.getOpcode() == ISD::FSHR) {
3131       std::swap(Op0, Op1);
3132       Opc = RISCVISD::FSR;
3133     }
3134     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3135   }
3136   case ISD::TRUNCATE:
3137     // Only custom-lower vector truncates
3138     if (!Op.getSimpleValueType().isVector())
3139       return Op;
3140     return lowerVectorTruncLike(Op, DAG);
3141   case ISD::ANY_EXTEND:
3142   case ISD::ZERO_EXTEND:
3143     if (Op.getOperand(0).getValueType().isVector() &&
3144         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3145       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3146     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3147   case ISD::SIGN_EXTEND:
3148     if (Op.getOperand(0).getValueType().isVector() &&
3149         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3150       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3151     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3152   case ISD::SPLAT_VECTOR_PARTS:
3153     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3154   case ISD::INSERT_VECTOR_ELT:
3155     return lowerINSERT_VECTOR_ELT(Op, DAG);
3156   case ISD::EXTRACT_VECTOR_ELT:
3157     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3158   case ISD::VSCALE: {
3159     MVT VT = Op.getSimpleValueType();
3160     SDLoc DL(Op);
3161     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3162     // We define our scalable vector types for lmul=1 to use a 64 bit known
3163     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3164     // vscale as VLENB / 8.
3165     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3166     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3167       report_fatal_error("Support for VLEN==32 is incomplete.");
3168     // We assume VLENB is a multiple of 8. We manually choose the best shift
3169     // here because SimplifyDemandedBits isn't always able to simplify it.
3170     uint64_t Val = Op.getConstantOperandVal(0);
3171     if (isPowerOf2_64(Val)) {
3172       uint64_t Log2 = Log2_64(Val);
3173       if (Log2 < 3)
3174         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3175                            DAG.getConstant(3 - Log2, DL, VT));
3176       if (Log2 > 3)
3177         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3178                            DAG.getConstant(Log2 - 3, DL, VT));
3179       return VLENB;
3180     }
3181     // If the multiplier is a multiple of 8, scale it down to avoid needing
3182     // to shift the VLENB value.
3183     if ((Val % 8) == 0)
3184       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3185                          DAG.getConstant(Val / 8, DL, VT));
3186 
3187     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3188                                  DAG.getConstant(3, DL, VT));
3189     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3190   }
3191   case ISD::FPOWI: {
3192     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3193     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3194     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3195         Op.getOperand(1).getValueType() == MVT::i32) {
3196       SDLoc DL(Op);
3197       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3198       SDValue Powi =
3199           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3200       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3201                          DAG.getIntPtrConstant(0, DL));
3202     }
3203     return SDValue();
3204   }
3205   case ISD::FP_EXTEND:
3206   case ISD::FP_ROUND:
3207     if (!Op.getValueType().isVector())
3208       return Op;
3209     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3210   case ISD::FP_TO_SINT:
3211   case ISD::FP_TO_UINT:
3212   case ISD::SINT_TO_FP:
3213   case ISD::UINT_TO_FP: {
3214     // RVV can only do fp<->int conversions to types half/double the size as
3215     // the source. We custom-lower any conversions that do two hops into
3216     // sequences.
3217     MVT VT = Op.getSimpleValueType();
3218     if (!VT.isVector())
3219       return Op;
3220     SDLoc DL(Op);
3221     SDValue Src = Op.getOperand(0);
3222     MVT EltVT = VT.getVectorElementType();
3223     MVT SrcVT = Src.getSimpleValueType();
3224     MVT SrcEltVT = SrcVT.getVectorElementType();
3225     unsigned EltSize = EltVT.getSizeInBits();
3226     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3227     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3228            "Unexpected vector element types");
3229 
3230     bool IsInt2FP = SrcEltVT.isInteger();
3231     // Widening conversions
3232     if (EltSize > (2 * SrcEltSize)) {
3233       if (IsInt2FP) {
3234         // Do a regular integer sign/zero extension then convert to float.
3235         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3236                                       VT.getVectorElementCount());
3237         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3238                                  ? ISD::ZERO_EXTEND
3239                                  : ISD::SIGN_EXTEND;
3240         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3241         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3242       }
3243       // FP2Int
3244       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3245       // Do one doubling fp_extend then complete the operation by converting
3246       // to int.
3247       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3248       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3249       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3250     }
3251 
3252     // Narrowing conversions
3253     if (SrcEltSize > (2 * EltSize)) {
3254       if (IsInt2FP) {
3255         // One narrowing int_to_fp, then an fp_round.
3256         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3257         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3258         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3259         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3260       }
3261       // FP2Int
3262       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3263       // representable by the integer, the result is poison.
3264       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3265                                     VT.getVectorElementCount());
3266       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3267       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3268     }
3269 
3270     // Scalable vectors can exit here. Patterns will handle equally-sized
3271     // conversions halving/doubling ones.
3272     if (!VT.isFixedLengthVector())
3273       return Op;
3274 
3275     // For fixed-length vectors we lower to a custom "VL" node.
3276     unsigned RVVOpc = 0;
3277     switch (Op.getOpcode()) {
3278     default:
3279       llvm_unreachable("Impossible opcode");
3280     case ISD::FP_TO_SINT:
3281       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3282       break;
3283     case ISD::FP_TO_UINT:
3284       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3285       break;
3286     case ISD::SINT_TO_FP:
3287       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3288       break;
3289     case ISD::UINT_TO_FP:
3290       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3291       break;
3292     }
3293 
3294     MVT ContainerVT, SrcContainerVT;
3295     // Derive the reference container type from the larger vector type.
3296     if (SrcEltSize > EltSize) {
3297       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3298       ContainerVT =
3299           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3300     } else {
3301       ContainerVT = getContainerForFixedLengthVector(VT);
3302       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3303     }
3304 
3305     SDValue Mask, VL;
3306     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3307 
3308     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3309     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3310     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3311   }
3312   case ISD::FP_TO_SINT_SAT:
3313   case ISD::FP_TO_UINT_SAT:
3314     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3315   case ISD::FTRUNC:
3316   case ISD::FCEIL:
3317   case ISD::FFLOOR:
3318     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3319   case ISD::FROUND:
3320     return lowerFROUND(Op, DAG);
3321   case ISD::VECREDUCE_ADD:
3322   case ISD::VECREDUCE_UMAX:
3323   case ISD::VECREDUCE_SMAX:
3324   case ISD::VECREDUCE_UMIN:
3325   case ISD::VECREDUCE_SMIN:
3326     return lowerVECREDUCE(Op, DAG);
3327   case ISD::VECREDUCE_AND:
3328   case ISD::VECREDUCE_OR:
3329   case ISD::VECREDUCE_XOR:
3330     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3331       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3332     return lowerVECREDUCE(Op, DAG);
3333   case ISD::VECREDUCE_FADD:
3334   case ISD::VECREDUCE_SEQ_FADD:
3335   case ISD::VECREDUCE_FMIN:
3336   case ISD::VECREDUCE_FMAX:
3337     return lowerFPVECREDUCE(Op, DAG);
3338   case ISD::VP_REDUCE_ADD:
3339   case ISD::VP_REDUCE_UMAX:
3340   case ISD::VP_REDUCE_SMAX:
3341   case ISD::VP_REDUCE_UMIN:
3342   case ISD::VP_REDUCE_SMIN:
3343   case ISD::VP_REDUCE_FADD:
3344   case ISD::VP_REDUCE_SEQ_FADD:
3345   case ISD::VP_REDUCE_FMIN:
3346   case ISD::VP_REDUCE_FMAX:
3347     return lowerVPREDUCE(Op, DAG);
3348   case ISD::VP_REDUCE_AND:
3349   case ISD::VP_REDUCE_OR:
3350   case ISD::VP_REDUCE_XOR:
3351     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3352       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3353     return lowerVPREDUCE(Op, DAG);
3354   case ISD::INSERT_SUBVECTOR:
3355     return lowerINSERT_SUBVECTOR(Op, DAG);
3356   case ISD::EXTRACT_SUBVECTOR:
3357     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3358   case ISD::STEP_VECTOR:
3359     return lowerSTEP_VECTOR(Op, DAG);
3360   case ISD::VECTOR_REVERSE:
3361     return lowerVECTOR_REVERSE(Op, DAG);
3362   case ISD::VECTOR_SPLICE:
3363     return lowerVECTOR_SPLICE(Op, DAG);
3364   case ISD::BUILD_VECTOR:
3365     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3366   case ISD::SPLAT_VECTOR:
3367     if (Op.getValueType().getVectorElementType() == MVT::i1)
3368       return lowerVectorMaskSplat(Op, DAG);
3369     return SDValue();
3370   case ISD::VECTOR_SHUFFLE:
3371     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3372   case ISD::CONCAT_VECTORS: {
3373     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3374     // better than going through the stack, as the default expansion does.
3375     SDLoc DL(Op);
3376     MVT VT = Op.getSimpleValueType();
3377     unsigned NumOpElts =
3378         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3379     SDValue Vec = DAG.getUNDEF(VT);
3380     for (const auto &OpIdx : enumerate(Op->ops())) {
3381       SDValue SubVec = OpIdx.value();
3382       // Don't insert undef subvectors.
3383       if (SubVec.isUndef())
3384         continue;
3385       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3386                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3387     }
3388     return Vec;
3389   }
3390   case ISD::LOAD:
3391     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3392       return V;
3393     if (Op.getValueType().isFixedLengthVector())
3394       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3395     return Op;
3396   case ISD::STORE:
3397     if (auto V = expandUnalignedRVVStore(Op, DAG))
3398       return V;
3399     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3400       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3401     return Op;
3402   case ISD::MLOAD:
3403   case ISD::VP_LOAD:
3404     return lowerMaskedLoad(Op, DAG);
3405   case ISD::MSTORE:
3406   case ISD::VP_STORE:
3407     return lowerMaskedStore(Op, DAG);
3408   case ISD::SETCC:
3409     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3410   case ISD::ADD:
3411     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3412   case ISD::SUB:
3413     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3414   case ISD::MUL:
3415     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3416   case ISD::MULHS:
3417     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3418   case ISD::MULHU:
3419     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3420   case ISD::AND:
3421     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3422                                               RISCVISD::AND_VL);
3423   case ISD::OR:
3424     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3425                                               RISCVISD::OR_VL);
3426   case ISD::XOR:
3427     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3428                                               RISCVISD::XOR_VL);
3429   case ISD::SDIV:
3430     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3431   case ISD::SREM:
3432     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3433   case ISD::UDIV:
3434     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3435   case ISD::UREM:
3436     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3437   case ISD::SHL:
3438   case ISD::SRA:
3439   case ISD::SRL:
3440     if (Op.getSimpleValueType().isFixedLengthVector())
3441       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3442     // This can be called for an i32 shift amount that needs to be promoted.
3443     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3444            "Unexpected custom legalisation");
3445     return SDValue();
3446   case ISD::SADDSAT:
3447     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3448   case ISD::UADDSAT:
3449     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3450   case ISD::SSUBSAT:
3451     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3452   case ISD::USUBSAT:
3453     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3454   case ISD::FADD:
3455     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3456   case ISD::FSUB:
3457     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3458   case ISD::FMUL:
3459     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3460   case ISD::FDIV:
3461     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3462   case ISD::FNEG:
3463     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3464   case ISD::FABS:
3465     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3466   case ISD::FSQRT:
3467     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3468   case ISD::FMA:
3469     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3470   case ISD::SMIN:
3471     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3472   case ISD::SMAX:
3473     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3474   case ISD::UMIN:
3475     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3476   case ISD::UMAX:
3477     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3478   case ISD::FMINNUM:
3479     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3480   case ISD::FMAXNUM:
3481     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3482   case ISD::ABS:
3483     return lowerABS(Op, DAG);
3484   case ISD::CTLZ_ZERO_UNDEF:
3485   case ISD::CTTZ_ZERO_UNDEF:
3486     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3487   case ISD::VSELECT:
3488     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3489   case ISD::FCOPYSIGN:
3490     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3491   case ISD::MGATHER:
3492   case ISD::VP_GATHER:
3493     return lowerMaskedGather(Op, DAG);
3494   case ISD::MSCATTER:
3495   case ISD::VP_SCATTER:
3496     return lowerMaskedScatter(Op, DAG);
3497   case ISD::FLT_ROUNDS_:
3498     return lowerGET_ROUNDING(Op, DAG);
3499   case ISD::SET_ROUNDING:
3500     return lowerSET_ROUNDING(Op, DAG);
3501   case ISD::EH_DWARF_CFA:
3502     return lowerEH_DWARF_CFA(Op, DAG);
3503   case ISD::VP_SELECT:
3504     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3505   case ISD::VP_MERGE:
3506     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3507   case ISD::VP_ADD:
3508     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3509   case ISD::VP_SUB:
3510     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3511   case ISD::VP_MUL:
3512     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3513   case ISD::VP_SDIV:
3514     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3515   case ISD::VP_UDIV:
3516     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3517   case ISD::VP_SREM:
3518     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3519   case ISD::VP_UREM:
3520     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3521   case ISD::VP_AND:
3522     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3523   case ISD::VP_OR:
3524     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3525   case ISD::VP_XOR:
3526     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3527   case ISD::VP_ASHR:
3528     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3529   case ISD::VP_LSHR:
3530     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3531   case ISD::VP_SHL:
3532     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3533   case ISD::VP_FADD:
3534     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3535   case ISD::VP_FSUB:
3536     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3537   case ISD::VP_FMUL:
3538     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3539   case ISD::VP_FDIV:
3540     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3541   case ISD::VP_FNEG:
3542     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3543   case ISD::VP_FMA:
3544     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3545   case ISD::VP_SIGN_EXTEND:
3546   case ISD::VP_ZERO_EXTEND:
3547     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3548       return lowerVPExtMaskOp(Op, DAG);
3549     return lowerVPOp(Op, DAG,
3550                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3551                          ? RISCVISD::VSEXT_VL
3552                          : RISCVISD::VZEXT_VL);
3553   case ISD::VP_TRUNCATE:
3554     return lowerVectorTruncLike(Op, DAG);
3555   case ISD::VP_FP_EXTEND:
3556   case ISD::VP_FP_ROUND:
3557     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3558   case ISD::VP_FPTOSI:
3559     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3560   case ISD::VP_FPTOUI:
3561     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3562   case ISD::VP_SITOFP:
3563     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3564   case ISD::VP_UITOFP:
3565     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3566   case ISD::VP_SETCC:
3567     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3568       return lowerVPSetCCMaskOp(Op, DAG);
3569     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3570   }
3571 }
3572 
3573 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3574                              SelectionDAG &DAG, unsigned Flags) {
3575   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3576 }
3577 
3578 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3579                              SelectionDAG &DAG, unsigned Flags) {
3580   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3581                                    Flags);
3582 }
3583 
3584 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3585                              SelectionDAG &DAG, unsigned Flags) {
3586   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3587                                    N->getOffset(), Flags);
3588 }
3589 
3590 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3591                              SelectionDAG &DAG, unsigned Flags) {
3592   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3593 }
3594 
3595 template <class NodeTy>
3596 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3597                                      bool IsLocal) const {
3598   SDLoc DL(N);
3599   EVT Ty = getPointerTy(DAG.getDataLayout());
3600 
3601   if (isPositionIndependent()) {
3602     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3603     if (IsLocal)
3604       // Use PC-relative addressing to access the symbol. This generates the
3605       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3606       // %pcrel_lo(auipc)).
3607       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3608 
3609     // Use PC-relative addressing to access the GOT for this symbol, then load
3610     // the address from the GOT. This generates the pattern (PseudoLA sym),
3611     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3612     SDValue Load =
3613         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3614     MachineFunction &MF = DAG.getMachineFunction();
3615     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3616         MachinePointerInfo::getGOT(MF),
3617         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3618             MachineMemOperand::MOInvariant,
3619         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3620     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3621     return Load;
3622   }
3623 
3624   switch (getTargetMachine().getCodeModel()) {
3625   default:
3626     report_fatal_error("Unsupported code model for lowering");
3627   case CodeModel::Small: {
3628     // Generate a sequence for accessing addresses within the first 2 GiB of
3629     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3630     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3631     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3632     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3633     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3634   }
3635   case CodeModel::Medium: {
3636     // Generate a sequence for accessing addresses within any 2GiB range within
3637     // the address space. This generates the pattern (PseudoLLA sym), which
3638     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3639     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3640     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3641   }
3642   }
3643 }
3644 
3645 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3646                                                 SelectionDAG &DAG) const {
3647   SDLoc DL(Op);
3648   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3649   assert(N->getOffset() == 0 && "unexpected offset in global node");
3650 
3651   const GlobalValue *GV = N->getGlobal();
3652   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3653   return getAddr(N, DAG, IsLocal);
3654 }
3655 
3656 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3657                                                SelectionDAG &DAG) const {
3658   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3659 
3660   return getAddr(N, DAG);
3661 }
3662 
3663 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3664                                                SelectionDAG &DAG) const {
3665   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3666 
3667   return getAddr(N, DAG);
3668 }
3669 
3670 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3671                                             SelectionDAG &DAG) const {
3672   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3673 
3674   return getAddr(N, DAG);
3675 }
3676 
3677 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3678                                               SelectionDAG &DAG,
3679                                               bool UseGOT) const {
3680   SDLoc DL(N);
3681   EVT Ty = getPointerTy(DAG.getDataLayout());
3682   const GlobalValue *GV = N->getGlobal();
3683   MVT XLenVT = Subtarget.getXLenVT();
3684 
3685   if (UseGOT) {
3686     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3687     // load the address from the GOT and add the thread pointer. This generates
3688     // the pattern (PseudoLA_TLS_IE sym), which expands to
3689     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3690     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3691     SDValue Load =
3692         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3693     MachineFunction &MF = DAG.getMachineFunction();
3694     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3695         MachinePointerInfo::getGOT(MF),
3696         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3697             MachineMemOperand::MOInvariant,
3698         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3699     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3700 
3701     // Add the thread pointer.
3702     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3703     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3704   }
3705 
3706   // Generate a sequence for accessing the address relative to the thread
3707   // pointer, with the appropriate adjustment for the thread pointer offset.
3708   // This generates the pattern
3709   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3710   SDValue AddrHi =
3711       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3712   SDValue AddrAdd =
3713       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3714   SDValue AddrLo =
3715       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3716 
3717   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3718   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3719   SDValue MNAdd = SDValue(
3720       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3721       0);
3722   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3723 }
3724 
3725 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3726                                                SelectionDAG &DAG) const {
3727   SDLoc DL(N);
3728   EVT Ty = getPointerTy(DAG.getDataLayout());
3729   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3730   const GlobalValue *GV = N->getGlobal();
3731 
3732   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3733   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3734   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3735   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3736   SDValue Load =
3737       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3738 
3739   // Prepare argument list to generate call.
3740   ArgListTy Args;
3741   ArgListEntry Entry;
3742   Entry.Node = Load;
3743   Entry.Ty = CallTy;
3744   Args.push_back(Entry);
3745 
3746   // Setup call to __tls_get_addr.
3747   TargetLowering::CallLoweringInfo CLI(DAG);
3748   CLI.setDebugLoc(DL)
3749       .setChain(DAG.getEntryNode())
3750       .setLibCallee(CallingConv::C, CallTy,
3751                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3752                     std::move(Args));
3753 
3754   return LowerCallTo(CLI).first;
3755 }
3756 
3757 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3758                                                    SelectionDAG &DAG) const {
3759   SDLoc DL(Op);
3760   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3761   assert(N->getOffset() == 0 && "unexpected offset in global node");
3762 
3763   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3764 
3765   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3766       CallingConv::GHC)
3767     report_fatal_error("In GHC calling convention TLS is not supported");
3768 
3769   SDValue Addr;
3770   switch (Model) {
3771   case TLSModel::LocalExec:
3772     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3773     break;
3774   case TLSModel::InitialExec:
3775     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3776     break;
3777   case TLSModel::LocalDynamic:
3778   case TLSModel::GeneralDynamic:
3779     Addr = getDynamicTLSAddr(N, DAG);
3780     break;
3781   }
3782 
3783   return Addr;
3784 }
3785 
3786 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3787   SDValue CondV = Op.getOperand(0);
3788   SDValue TrueV = Op.getOperand(1);
3789   SDValue FalseV = Op.getOperand(2);
3790   SDLoc DL(Op);
3791   MVT VT = Op.getSimpleValueType();
3792   MVT XLenVT = Subtarget.getXLenVT();
3793 
3794   // Lower vector SELECTs to VSELECTs by splatting the condition.
3795   if (VT.isVector()) {
3796     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3797     SDValue CondSplat = VT.isScalableVector()
3798                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3799                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3800     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3801   }
3802 
3803   // If the result type is XLenVT and CondV is the output of a SETCC node
3804   // which also operated on XLenVT inputs, then merge the SETCC node into the
3805   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3806   // compare+branch instructions. i.e.:
3807   // (select (setcc lhs, rhs, cc), truev, falsev)
3808   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3809   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3810       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3811     SDValue LHS = CondV.getOperand(0);
3812     SDValue RHS = CondV.getOperand(1);
3813     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3814     ISD::CondCode CCVal = CC->get();
3815 
3816     // Special case for a select of 2 constants that have a diffence of 1.
3817     // Normally this is done by DAGCombine, but if the select is introduced by
3818     // type legalization or op legalization, we miss it. Restricting to SETLT
3819     // case for now because that is what signed saturating add/sub need.
3820     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3821     // but we would probably want to swap the true/false values if the condition
3822     // is SETGE/SETLE to avoid an XORI.
3823     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3824         CCVal == ISD::SETLT) {
3825       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3826       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3827       if (TrueVal - 1 == FalseVal)
3828         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3829       if (TrueVal + 1 == FalseVal)
3830         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3831     }
3832 
3833     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3834 
3835     SDValue TargetCC = DAG.getCondCode(CCVal);
3836     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3837     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3838   }
3839 
3840   // Otherwise:
3841   // (select condv, truev, falsev)
3842   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3843   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3844   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3845 
3846   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3847 
3848   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3849 }
3850 
3851 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3852   SDValue CondV = Op.getOperand(1);
3853   SDLoc DL(Op);
3854   MVT XLenVT = Subtarget.getXLenVT();
3855 
3856   if (CondV.getOpcode() == ISD::SETCC &&
3857       CondV.getOperand(0).getValueType() == XLenVT) {
3858     SDValue LHS = CondV.getOperand(0);
3859     SDValue RHS = CondV.getOperand(1);
3860     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3861 
3862     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3863 
3864     SDValue TargetCC = DAG.getCondCode(CCVal);
3865     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3866                        LHS, RHS, TargetCC, Op.getOperand(2));
3867   }
3868 
3869   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3870                      CondV, DAG.getConstant(0, DL, XLenVT),
3871                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3872 }
3873 
3874 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3875   MachineFunction &MF = DAG.getMachineFunction();
3876   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3877 
3878   SDLoc DL(Op);
3879   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3880                                  getPointerTy(MF.getDataLayout()));
3881 
3882   // vastart just stores the address of the VarArgsFrameIndex slot into the
3883   // memory location argument.
3884   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3885   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3886                       MachinePointerInfo(SV));
3887 }
3888 
3889 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3890                                             SelectionDAG &DAG) const {
3891   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3892   MachineFunction &MF = DAG.getMachineFunction();
3893   MachineFrameInfo &MFI = MF.getFrameInfo();
3894   MFI.setFrameAddressIsTaken(true);
3895   Register FrameReg = RI.getFrameRegister(MF);
3896   int XLenInBytes = Subtarget.getXLen() / 8;
3897 
3898   EVT VT = Op.getValueType();
3899   SDLoc DL(Op);
3900   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3901   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3902   while (Depth--) {
3903     int Offset = -(XLenInBytes * 2);
3904     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3905                               DAG.getIntPtrConstant(Offset, DL));
3906     FrameAddr =
3907         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3908   }
3909   return FrameAddr;
3910 }
3911 
3912 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3913                                              SelectionDAG &DAG) const {
3914   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3915   MachineFunction &MF = DAG.getMachineFunction();
3916   MachineFrameInfo &MFI = MF.getFrameInfo();
3917   MFI.setReturnAddressIsTaken(true);
3918   MVT XLenVT = Subtarget.getXLenVT();
3919   int XLenInBytes = Subtarget.getXLen() / 8;
3920 
3921   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3922     return SDValue();
3923 
3924   EVT VT = Op.getValueType();
3925   SDLoc DL(Op);
3926   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3927   if (Depth) {
3928     int Off = -XLenInBytes;
3929     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3930     SDValue Offset = DAG.getConstant(Off, DL, VT);
3931     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3932                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3933                        MachinePointerInfo());
3934   }
3935 
3936   // Return the value of the return address register, marking it an implicit
3937   // live-in.
3938   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3939   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3940 }
3941 
3942 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3943                                                  SelectionDAG &DAG) const {
3944   SDLoc DL(Op);
3945   SDValue Lo = Op.getOperand(0);
3946   SDValue Hi = Op.getOperand(1);
3947   SDValue Shamt = Op.getOperand(2);
3948   EVT VT = Lo.getValueType();
3949 
3950   // if Shamt-XLEN < 0: // Shamt < XLEN
3951   //   Lo = Lo << Shamt
3952   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3953   // else:
3954   //   Lo = 0
3955   //   Hi = Lo << (Shamt-XLEN)
3956 
3957   SDValue Zero = DAG.getConstant(0, DL, VT);
3958   SDValue One = DAG.getConstant(1, DL, VT);
3959   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3960   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3961   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3962   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3963 
3964   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3965   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3966   SDValue ShiftRightLo =
3967       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3968   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3969   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3970   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3971 
3972   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3973 
3974   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3975   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3976 
3977   SDValue Parts[2] = {Lo, Hi};
3978   return DAG.getMergeValues(Parts, DL);
3979 }
3980 
3981 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3982                                                   bool IsSRA) const {
3983   SDLoc DL(Op);
3984   SDValue Lo = Op.getOperand(0);
3985   SDValue Hi = Op.getOperand(1);
3986   SDValue Shamt = Op.getOperand(2);
3987   EVT VT = Lo.getValueType();
3988 
3989   // SRA expansion:
3990   //   if Shamt-XLEN < 0: // Shamt < XLEN
3991   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3992   //     Hi = Hi >>s Shamt
3993   //   else:
3994   //     Lo = Hi >>s (Shamt-XLEN);
3995   //     Hi = Hi >>s (XLEN-1)
3996   //
3997   // SRL expansion:
3998   //   if Shamt-XLEN < 0: // Shamt < XLEN
3999   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4000   //     Hi = Hi >>u Shamt
4001   //   else:
4002   //     Lo = Hi >>u (Shamt-XLEN);
4003   //     Hi = 0;
4004 
4005   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4006 
4007   SDValue Zero = DAG.getConstant(0, DL, VT);
4008   SDValue One = DAG.getConstant(1, DL, VT);
4009   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4010   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4011   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4012   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4013 
4014   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4015   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4016   SDValue ShiftLeftHi =
4017       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4018   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4019   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4020   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4021   SDValue HiFalse =
4022       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4023 
4024   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4025 
4026   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4027   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4028 
4029   SDValue Parts[2] = {Lo, Hi};
4030   return DAG.getMergeValues(Parts, DL);
4031 }
4032 
4033 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4034 // legal equivalently-sized i8 type, so we can use that as a go-between.
4035 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4036                                                   SelectionDAG &DAG) const {
4037   SDLoc DL(Op);
4038   MVT VT = Op.getSimpleValueType();
4039   SDValue SplatVal = Op.getOperand(0);
4040   // All-zeros or all-ones splats are handled specially.
4041   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4042     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4043     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4044   }
4045   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4046     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4047     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4048   }
4049   MVT XLenVT = Subtarget.getXLenVT();
4050   assert(SplatVal.getValueType() == XLenVT &&
4051          "Unexpected type for i1 splat value");
4052   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4053   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4054                          DAG.getConstant(1, DL, XLenVT));
4055   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4056   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4057   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4058 }
4059 
4060 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4061 // illegal (currently only vXi64 RV32).
4062 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4063 // them to VMV_V_X_VL.
4064 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4065                                                      SelectionDAG &DAG) const {
4066   SDLoc DL(Op);
4067   MVT VecVT = Op.getSimpleValueType();
4068   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4069          "Unexpected SPLAT_VECTOR_PARTS lowering");
4070 
4071   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4072   SDValue Lo = Op.getOperand(0);
4073   SDValue Hi = Op.getOperand(1);
4074 
4075   if (VecVT.isFixedLengthVector()) {
4076     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4077     SDLoc DL(Op);
4078     SDValue Mask, VL;
4079     std::tie(Mask, VL) =
4080         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4081 
4082     SDValue Res =
4083         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4084     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4085   }
4086 
4087   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4088     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4089     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4090     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4091     // node in order to try and match RVV vector/scalar instructions.
4092     if ((LoC >> 31) == HiC)
4093       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4094                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4095   }
4096 
4097   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4098   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4099       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4100       Hi.getConstantOperandVal(1) == 31)
4101     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4102                        DAG.getRegister(RISCV::X0, MVT::i32));
4103 
4104   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4105   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4106                      DAG.getUNDEF(VecVT), Lo, Hi,
4107                      DAG.getRegister(RISCV::X0, MVT::i32));
4108 }
4109 
4110 // Custom-lower extensions from mask vectors by using a vselect either with 1
4111 // for zero/any-extension or -1 for sign-extension:
4112 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4113 // Note that any-extension is lowered identically to zero-extension.
4114 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4115                                                 int64_t ExtTrueVal) const {
4116   SDLoc DL(Op);
4117   MVT VecVT = Op.getSimpleValueType();
4118   SDValue Src = Op.getOperand(0);
4119   // Only custom-lower extensions from mask types
4120   assert(Src.getValueType().isVector() &&
4121          Src.getValueType().getVectorElementType() == MVT::i1);
4122 
4123   if (VecVT.isScalableVector()) {
4124     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4125     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4126     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4127   }
4128 
4129   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4130   MVT I1ContainerVT =
4131       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4132 
4133   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4134 
4135   SDValue Mask, VL;
4136   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4137 
4138   MVT XLenVT = Subtarget.getXLenVT();
4139   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4140   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4141 
4142   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4143                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4144   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4145                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4146   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4147                                SplatTrueVal, SplatZero, VL);
4148 
4149   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4150 }
4151 
4152 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4153     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4154   MVT ExtVT = Op.getSimpleValueType();
4155   // Only custom-lower extensions from fixed-length vector types.
4156   if (!ExtVT.isFixedLengthVector())
4157     return Op;
4158   MVT VT = Op.getOperand(0).getSimpleValueType();
4159   // Grab the canonical container type for the extended type. Infer the smaller
4160   // type from that to ensure the same number of vector elements, as we know
4161   // the LMUL will be sufficient to hold the smaller type.
4162   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4163   // Get the extended container type manually to ensure the same number of
4164   // vector elements between source and dest.
4165   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4166                                      ContainerExtVT.getVectorElementCount());
4167 
4168   SDValue Op1 =
4169       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4170 
4171   SDLoc DL(Op);
4172   SDValue Mask, VL;
4173   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4174 
4175   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4176 
4177   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4178 }
4179 
4180 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4181 // setcc operation:
4182 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4183 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4184                                                       SelectionDAG &DAG) const {
4185   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4186   SDLoc DL(Op);
4187   EVT MaskVT = Op.getValueType();
4188   // Only expect to custom-lower truncations to mask types
4189   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4190          "Unexpected type for vector mask lowering");
4191   SDValue Src = Op.getOperand(0);
4192   MVT VecVT = Src.getSimpleValueType();
4193   SDValue Mask, VL;
4194   if (IsVPTrunc) {
4195     Mask = Op.getOperand(1);
4196     VL = Op.getOperand(2);
4197   }
4198   // If this is a fixed vector, we need to convert it to a scalable vector.
4199   MVT ContainerVT = VecVT;
4200 
4201   if (VecVT.isFixedLengthVector()) {
4202     ContainerVT = getContainerForFixedLengthVector(VecVT);
4203     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4204     if (IsVPTrunc) {
4205       MVT MaskContainerVT =
4206           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4207       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4208     }
4209   }
4210 
4211   if (!IsVPTrunc) {
4212     std::tie(Mask, VL) =
4213         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4214   }
4215 
4216   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4217   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4218 
4219   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4220                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4221   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4222                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4223 
4224   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4225   SDValue Trunc =
4226       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4227   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4228                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4229   if (MaskVT.isFixedLengthVector())
4230     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4231   return Trunc;
4232 }
4233 
4234 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4235                                                   SelectionDAG &DAG) const {
4236   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4237   SDLoc DL(Op);
4238 
4239   MVT VT = Op.getSimpleValueType();
4240   // Only custom-lower vector truncates
4241   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4242 
4243   // Truncates to mask types are handled differently
4244   if (VT.getVectorElementType() == MVT::i1)
4245     return lowerVectorMaskTruncLike(Op, DAG);
4246 
4247   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4248   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4249   // truncate by one power of two at a time.
4250   MVT DstEltVT = VT.getVectorElementType();
4251 
4252   SDValue Src = Op.getOperand(0);
4253   MVT SrcVT = Src.getSimpleValueType();
4254   MVT SrcEltVT = SrcVT.getVectorElementType();
4255 
4256   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4257          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4258          "Unexpected vector truncate lowering");
4259 
4260   MVT ContainerVT = SrcVT;
4261   SDValue Mask, VL;
4262   if (IsVPTrunc) {
4263     Mask = Op.getOperand(1);
4264     VL = Op.getOperand(2);
4265   }
4266   if (SrcVT.isFixedLengthVector()) {
4267     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4268     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4269     if (IsVPTrunc) {
4270       MVT MaskVT = getMaskTypeFor(ContainerVT);
4271       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4272     }
4273   }
4274 
4275   SDValue Result = Src;
4276   if (!IsVPTrunc) {
4277     std::tie(Mask, VL) =
4278         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4279   }
4280 
4281   LLVMContext &Context = *DAG.getContext();
4282   const ElementCount Count = ContainerVT.getVectorElementCount();
4283   do {
4284     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4285     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4286     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4287                          Mask, VL);
4288   } while (SrcEltVT != DstEltVT);
4289 
4290   if (SrcVT.isFixedLengthVector())
4291     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4292 
4293   return Result;
4294 }
4295 
4296 SDValue
4297 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4298                                                     SelectionDAG &DAG) const {
4299   bool IsVP =
4300       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4301   bool IsExtend =
4302       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4303   // RVV can only do truncate fp to types half the size as the source. We
4304   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4305   // conversion instruction.
4306   SDLoc DL(Op);
4307   MVT VT = Op.getSimpleValueType();
4308 
4309   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4310 
4311   SDValue Src = Op.getOperand(0);
4312   MVT SrcVT = Src.getSimpleValueType();
4313 
4314   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4315                                      SrcVT.getVectorElementType() != MVT::f16);
4316   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4317                                      SrcVT.getVectorElementType() != MVT::f64);
4318 
4319   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4320 
4321   // Prepare any fixed-length vector operands.
4322   MVT ContainerVT = VT;
4323   SDValue Mask, VL;
4324   if (IsVP) {
4325     Mask = Op.getOperand(1);
4326     VL = Op.getOperand(2);
4327   }
4328   if (VT.isFixedLengthVector()) {
4329     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4330     ContainerVT =
4331         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4332     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4333     if (IsVP) {
4334       MVT MaskVT = getMaskTypeFor(ContainerVT);
4335       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4336     }
4337   }
4338 
4339   if (!IsVP)
4340     std::tie(Mask, VL) =
4341         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4342 
4343   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4344 
4345   if (IsDirectConv) {
4346     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4347     if (VT.isFixedLengthVector())
4348       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4349     return Src;
4350   }
4351 
4352   unsigned InterConvOpc =
4353       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4354 
4355   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4356   SDValue IntermediateConv =
4357       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4358   SDValue Result =
4359       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4360   if (VT.isFixedLengthVector())
4361     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4362   return Result;
4363 }
4364 
4365 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4366 // first position of a vector, and that vector is slid up to the insert index.
4367 // By limiting the active vector length to index+1 and merging with the
4368 // original vector (with an undisturbed tail policy for elements >= VL), we
4369 // achieve the desired result of leaving all elements untouched except the one
4370 // at VL-1, which is replaced with the desired value.
4371 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4372                                                     SelectionDAG &DAG) const {
4373   SDLoc DL(Op);
4374   MVT VecVT = Op.getSimpleValueType();
4375   SDValue Vec = Op.getOperand(0);
4376   SDValue Val = Op.getOperand(1);
4377   SDValue Idx = Op.getOperand(2);
4378 
4379   if (VecVT.getVectorElementType() == MVT::i1) {
4380     // FIXME: For now we just promote to an i8 vector and insert into that,
4381     // but this is probably not optimal.
4382     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4383     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4384     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4385     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4386   }
4387 
4388   MVT ContainerVT = VecVT;
4389   // If the operand is a fixed-length vector, convert to a scalable one.
4390   if (VecVT.isFixedLengthVector()) {
4391     ContainerVT = getContainerForFixedLengthVector(VecVT);
4392     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4393   }
4394 
4395   MVT XLenVT = Subtarget.getXLenVT();
4396 
4397   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4398   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4399   // Even i64-element vectors on RV32 can be lowered without scalar
4400   // legalization if the most-significant 32 bits of the value are not affected
4401   // by the sign-extension of the lower 32 bits.
4402   // TODO: We could also catch sign extensions of a 32-bit value.
4403   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4404     const auto *CVal = cast<ConstantSDNode>(Val);
4405     if (isInt<32>(CVal->getSExtValue())) {
4406       IsLegalInsert = true;
4407       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4408     }
4409   }
4410 
4411   SDValue Mask, VL;
4412   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4413 
4414   SDValue ValInVec;
4415 
4416   if (IsLegalInsert) {
4417     unsigned Opc =
4418         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4419     if (isNullConstant(Idx)) {
4420       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4421       if (!VecVT.isFixedLengthVector())
4422         return Vec;
4423       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4424     }
4425     ValInVec =
4426         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4427   } else {
4428     // On RV32, i64-element vectors must be specially handled to place the
4429     // value at element 0, by using two vslide1up instructions in sequence on
4430     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4431     // this.
4432     SDValue One = DAG.getConstant(1, DL, XLenVT);
4433     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4434     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4435     MVT I32ContainerVT =
4436         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4437     SDValue I32Mask =
4438         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4439     // Limit the active VL to two.
4440     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4441     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4442     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4443     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4444                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4445     // First slide in the hi value, then the lo in underneath it.
4446     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4447                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4448                            I32Mask, InsertI64VL);
4449     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4450                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4451                            I32Mask, InsertI64VL);
4452     // Bitcast back to the right container type.
4453     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4454   }
4455 
4456   // Now that the value is in a vector, slide it into position.
4457   SDValue InsertVL =
4458       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4459   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4460                                 ValInVec, Idx, Mask, InsertVL);
4461   if (!VecVT.isFixedLengthVector())
4462     return Slideup;
4463   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4464 }
4465 
4466 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4467 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4468 // types this is done using VMV_X_S to allow us to glean information about the
4469 // sign bits of the result.
4470 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4471                                                      SelectionDAG &DAG) const {
4472   SDLoc DL(Op);
4473   SDValue Idx = Op.getOperand(1);
4474   SDValue Vec = Op.getOperand(0);
4475   EVT EltVT = Op.getValueType();
4476   MVT VecVT = Vec.getSimpleValueType();
4477   MVT XLenVT = Subtarget.getXLenVT();
4478 
4479   if (VecVT.getVectorElementType() == MVT::i1) {
4480     if (VecVT.isFixedLengthVector()) {
4481       unsigned NumElts = VecVT.getVectorNumElements();
4482       if (NumElts >= 8) {
4483         MVT WideEltVT;
4484         unsigned WidenVecLen;
4485         SDValue ExtractElementIdx;
4486         SDValue ExtractBitIdx;
4487         unsigned MaxEEW = Subtarget.getELEN();
4488         MVT LargestEltVT = MVT::getIntegerVT(
4489             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4490         if (NumElts <= LargestEltVT.getSizeInBits()) {
4491           assert(isPowerOf2_32(NumElts) &&
4492                  "the number of elements should be power of 2");
4493           WideEltVT = MVT::getIntegerVT(NumElts);
4494           WidenVecLen = 1;
4495           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4496           ExtractBitIdx = Idx;
4497         } else {
4498           WideEltVT = LargestEltVT;
4499           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4500           // extract element index = index / element width
4501           ExtractElementIdx = DAG.getNode(
4502               ISD::SRL, DL, XLenVT, Idx,
4503               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4504           // mask bit index = index % element width
4505           ExtractBitIdx = DAG.getNode(
4506               ISD::AND, DL, XLenVT, Idx,
4507               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4508         }
4509         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4510         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4511         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4512                                          Vec, ExtractElementIdx);
4513         // Extract the bit from GPR.
4514         SDValue ShiftRight =
4515             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4516         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4517                            DAG.getConstant(1, DL, XLenVT));
4518       }
4519     }
4520     // Otherwise, promote to an i8 vector and extract from that.
4521     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4522     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4523     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4524   }
4525 
4526   // If this is a fixed vector, we need to convert it to a scalable vector.
4527   MVT ContainerVT = VecVT;
4528   if (VecVT.isFixedLengthVector()) {
4529     ContainerVT = getContainerForFixedLengthVector(VecVT);
4530     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4531   }
4532 
4533   // If the index is 0, the vector is already in the right position.
4534   if (!isNullConstant(Idx)) {
4535     // Use a VL of 1 to avoid processing more elements than we need.
4536     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4537     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4538     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4539                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4540   }
4541 
4542   if (!EltVT.isInteger()) {
4543     // Floating-point extracts are handled in TableGen.
4544     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4545                        DAG.getConstant(0, DL, XLenVT));
4546   }
4547 
4548   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4549   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4550 }
4551 
4552 // Some RVV intrinsics may claim that they want an integer operand to be
4553 // promoted or expanded.
4554 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4555                                            const RISCVSubtarget &Subtarget) {
4556   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4557           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4558          "Unexpected opcode");
4559 
4560   if (!Subtarget.hasVInstructions())
4561     return SDValue();
4562 
4563   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4564   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4565   SDLoc DL(Op);
4566 
4567   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4568       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4569   if (!II || !II->hasScalarOperand())
4570     return SDValue();
4571 
4572   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4573   assert(SplatOp < Op.getNumOperands());
4574 
4575   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4576   SDValue &ScalarOp = Operands[SplatOp];
4577   MVT OpVT = ScalarOp.getSimpleValueType();
4578   MVT XLenVT = Subtarget.getXLenVT();
4579 
4580   // If this isn't a scalar, or its type is XLenVT we're done.
4581   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4582     return SDValue();
4583 
4584   // Simplest case is that the operand needs to be promoted to XLenVT.
4585   if (OpVT.bitsLT(XLenVT)) {
4586     // If the operand is a constant, sign extend to increase our chances
4587     // of being able to use a .vi instruction. ANY_EXTEND would become a
4588     // a zero extend and the simm5 check in isel would fail.
4589     // FIXME: Should we ignore the upper bits in isel instead?
4590     unsigned ExtOpc =
4591         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4592     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4593     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4594   }
4595 
4596   // Use the previous operand to get the vXi64 VT. The result might be a mask
4597   // VT for compares. Using the previous operand assumes that the previous
4598   // operand will never have a smaller element size than a scalar operand and
4599   // that a widening operation never uses SEW=64.
4600   // NOTE: If this fails the below assert, we can probably just find the
4601   // element count from any operand or result and use it to construct the VT.
4602   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4603   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4604 
4605   // The more complex case is when the scalar is larger than XLenVT.
4606   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4607          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4608 
4609   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4610   // instruction to sign-extend since SEW>XLEN.
4611   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4612     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4613     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4614   }
4615 
4616   switch (IntNo) {
4617   case Intrinsic::riscv_vslide1up:
4618   case Intrinsic::riscv_vslide1down:
4619   case Intrinsic::riscv_vslide1up_mask:
4620   case Intrinsic::riscv_vslide1down_mask: {
4621     // We need to special case these when the scalar is larger than XLen.
4622     unsigned NumOps = Op.getNumOperands();
4623     bool IsMasked = NumOps == 7;
4624 
4625     // Convert the vector source to the equivalent nxvXi32 vector.
4626     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4627     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4628 
4629     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4630                                    DAG.getConstant(0, DL, XLenVT));
4631     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4632                                    DAG.getConstant(1, DL, XLenVT));
4633 
4634     // Double the VL since we halved SEW.
4635     SDValue AVL = getVLOperand(Op);
4636     SDValue I32VL;
4637 
4638     // Optimize for constant AVL
4639     if (isa<ConstantSDNode>(AVL)) {
4640       unsigned EltSize = VT.getScalarSizeInBits();
4641       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4642 
4643       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4644       unsigned MaxVLMAX =
4645           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4646 
4647       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4648       unsigned MinVLMAX =
4649           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4650 
4651       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4652       if (AVLInt <= MinVLMAX) {
4653         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4654       } else if (AVLInt >= 2 * MaxVLMAX) {
4655         // Just set vl to VLMAX in this situation
4656         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4657         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4658         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4659         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4660         SDValue SETVLMAX = DAG.getTargetConstant(
4661             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4662         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4663                             LMUL);
4664       } else {
4665         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4666         // is related to the hardware implementation.
4667         // So let the following code handle
4668       }
4669     }
4670     if (!I32VL) {
4671       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4672       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4673       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4674       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4675       SDValue SETVL =
4676           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4677       // Using vsetvli instruction to get actually used length which related to
4678       // the hardware implementation
4679       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4680                                SEW, LMUL);
4681       I32VL =
4682           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4683     }
4684 
4685     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4686 
4687     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4688     // instructions.
4689     SDValue Passthru;
4690     if (IsMasked)
4691       Passthru = DAG.getUNDEF(I32VT);
4692     else
4693       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4694 
4695     if (IntNo == Intrinsic::riscv_vslide1up ||
4696         IntNo == Intrinsic::riscv_vslide1up_mask) {
4697       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4698                         ScalarHi, I32Mask, I32VL);
4699       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4700                         ScalarLo, I32Mask, I32VL);
4701     } else {
4702       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4703                         ScalarLo, I32Mask, I32VL);
4704       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4705                         ScalarHi, I32Mask, I32VL);
4706     }
4707 
4708     // Convert back to nxvXi64.
4709     Vec = DAG.getBitcast(VT, Vec);
4710 
4711     if (!IsMasked)
4712       return Vec;
4713     // Apply mask after the operation.
4714     SDValue Mask = Operands[NumOps - 3];
4715     SDValue MaskedOff = Operands[1];
4716     // Assume Policy operand is the last operand.
4717     uint64_t Policy =
4718         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4719     // We don't need to select maskedoff if it's undef.
4720     if (MaskedOff.isUndef())
4721       return Vec;
4722     // TAMU
4723     if (Policy == RISCVII::TAIL_AGNOSTIC)
4724       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4725                          AVL);
4726     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4727     // It's fine because vmerge does not care mask policy.
4728     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4729                        AVL);
4730   }
4731   }
4732 
4733   // We need to convert the scalar to a splat vector.
4734   SDValue VL = getVLOperand(Op);
4735   assert(VL.getValueType() == XLenVT);
4736   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4737   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4738 }
4739 
4740 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4741                                                      SelectionDAG &DAG) const {
4742   unsigned IntNo = Op.getConstantOperandVal(0);
4743   SDLoc DL(Op);
4744   MVT XLenVT = Subtarget.getXLenVT();
4745 
4746   switch (IntNo) {
4747   default:
4748     break; // Don't custom lower most intrinsics.
4749   case Intrinsic::thread_pointer: {
4750     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4751     return DAG.getRegister(RISCV::X4, PtrVT);
4752   }
4753   case Intrinsic::riscv_orc_b:
4754   case Intrinsic::riscv_brev8: {
4755     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4756     unsigned Opc =
4757         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4758     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4759                        DAG.getConstant(7, DL, XLenVT));
4760   }
4761   case Intrinsic::riscv_grev:
4762   case Intrinsic::riscv_gorc: {
4763     unsigned Opc =
4764         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4765     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4766   }
4767   case Intrinsic::riscv_zip:
4768   case Intrinsic::riscv_unzip: {
4769     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4770     // For i32 the immediate is 15. For i64 the immediate is 31.
4771     unsigned Opc =
4772         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4773     unsigned BitWidth = Op.getValueSizeInBits();
4774     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4775     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4776                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4777   }
4778   case Intrinsic::riscv_shfl:
4779   case Intrinsic::riscv_unshfl: {
4780     unsigned Opc =
4781         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4782     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4783   }
4784   case Intrinsic::riscv_bcompress:
4785   case Intrinsic::riscv_bdecompress: {
4786     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4787                                                        : RISCVISD::BDECOMPRESS;
4788     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4789   }
4790   case Intrinsic::riscv_bfp:
4791     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4792                        Op.getOperand(2));
4793   case Intrinsic::riscv_fsl:
4794     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4795                        Op.getOperand(2), Op.getOperand(3));
4796   case Intrinsic::riscv_fsr:
4797     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4798                        Op.getOperand(2), Op.getOperand(3));
4799   case Intrinsic::riscv_vmv_x_s:
4800     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4801     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4802                        Op.getOperand(1));
4803   case Intrinsic::riscv_vmv_v_x:
4804     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4805                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4806                             Subtarget);
4807   case Intrinsic::riscv_vfmv_v_f:
4808     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4809                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4810   case Intrinsic::riscv_vmv_s_x: {
4811     SDValue Scalar = Op.getOperand(2);
4812 
4813     if (Scalar.getValueType().bitsLE(XLenVT)) {
4814       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4815       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4816                          Op.getOperand(1), Scalar, Op.getOperand(3));
4817     }
4818 
4819     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4820 
4821     // This is an i64 value that lives in two scalar registers. We have to
4822     // insert this in a convoluted way. First we build vXi64 splat containing
4823     // the two values that we assemble using some bit math. Next we'll use
4824     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4825     // to merge element 0 from our splat into the source vector.
4826     // FIXME: This is probably not the best way to do this, but it is
4827     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4828     // point.
4829     //   sw lo, (a0)
4830     //   sw hi, 4(a0)
4831     //   vlse vX, (a0)
4832     //
4833     //   vid.v      vVid
4834     //   vmseq.vx   mMask, vVid, 0
4835     //   vmerge.vvm vDest, vSrc, vVal, mMask
4836     MVT VT = Op.getSimpleValueType();
4837     SDValue Vec = Op.getOperand(1);
4838     SDValue VL = getVLOperand(Op);
4839 
4840     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4841     if (Op.getOperand(1).isUndef())
4842       return SplattedVal;
4843     SDValue SplattedIdx =
4844         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4845                     DAG.getConstant(0, DL, MVT::i32), VL);
4846 
4847     MVT MaskVT = getMaskTypeFor(VT);
4848     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4849     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4850     SDValue SelectCond =
4851         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4852                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4853     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4854                        Vec, VL);
4855   }
4856   }
4857 
4858   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4859 }
4860 
4861 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4862                                                     SelectionDAG &DAG) const {
4863   unsigned IntNo = Op.getConstantOperandVal(1);
4864   switch (IntNo) {
4865   default:
4866     break;
4867   case Intrinsic::riscv_masked_strided_load: {
4868     SDLoc DL(Op);
4869     MVT XLenVT = Subtarget.getXLenVT();
4870 
4871     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4872     // the selection of the masked intrinsics doesn't do this for us.
4873     SDValue Mask = Op.getOperand(5);
4874     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4875 
4876     MVT VT = Op->getSimpleValueType(0);
4877     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4878 
4879     SDValue PassThru = Op.getOperand(2);
4880     if (!IsUnmasked) {
4881       MVT MaskVT = getMaskTypeFor(ContainerVT);
4882       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4883       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4884     }
4885 
4886     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4887 
4888     SDValue IntID = DAG.getTargetConstant(
4889         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4890         XLenVT);
4891 
4892     auto *Load = cast<MemIntrinsicSDNode>(Op);
4893     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4894     if (IsUnmasked)
4895       Ops.push_back(DAG.getUNDEF(ContainerVT));
4896     else
4897       Ops.push_back(PassThru);
4898     Ops.push_back(Op.getOperand(3)); // Ptr
4899     Ops.push_back(Op.getOperand(4)); // Stride
4900     if (!IsUnmasked)
4901       Ops.push_back(Mask);
4902     Ops.push_back(VL);
4903     if (!IsUnmasked) {
4904       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4905       Ops.push_back(Policy);
4906     }
4907 
4908     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4909     SDValue Result =
4910         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4911                                 Load->getMemoryVT(), Load->getMemOperand());
4912     SDValue Chain = Result.getValue(1);
4913     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4914     return DAG.getMergeValues({Result, Chain}, DL);
4915   }
4916   case Intrinsic::riscv_seg2_load:
4917   case Intrinsic::riscv_seg3_load:
4918   case Intrinsic::riscv_seg4_load:
4919   case Intrinsic::riscv_seg5_load:
4920   case Intrinsic::riscv_seg6_load:
4921   case Intrinsic::riscv_seg7_load:
4922   case Intrinsic::riscv_seg8_load: {
4923     SDLoc DL(Op);
4924     static const Intrinsic::ID VlsegInts[7] = {
4925         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4926         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4927         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4928         Intrinsic::riscv_vlseg8};
4929     unsigned NF = Op->getNumValues() - 1;
4930     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4931     MVT XLenVT = Subtarget.getXLenVT();
4932     MVT VT = Op->getSimpleValueType(0);
4933     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4934 
4935     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4936     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4937     auto *Load = cast<MemIntrinsicSDNode>(Op);
4938     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4939     ContainerVTs.push_back(MVT::Other);
4940     SDVTList VTs = DAG.getVTList(ContainerVTs);
4941     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
4942     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
4943     Ops.push_back(Op.getOperand(2));
4944     Ops.push_back(VL);
4945     SDValue Result =
4946         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4947                                 Load->getMemoryVT(), Load->getMemOperand());
4948     SmallVector<SDValue, 9> Results;
4949     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4950       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4951                                                   DAG, Subtarget));
4952     Results.push_back(Result.getValue(NF));
4953     return DAG.getMergeValues(Results, DL);
4954   }
4955   }
4956 
4957   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4958 }
4959 
4960 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4961                                                  SelectionDAG &DAG) const {
4962   unsigned IntNo = Op.getConstantOperandVal(1);
4963   switch (IntNo) {
4964   default:
4965     break;
4966   case Intrinsic::riscv_masked_strided_store: {
4967     SDLoc DL(Op);
4968     MVT XLenVT = Subtarget.getXLenVT();
4969 
4970     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4971     // the selection of the masked intrinsics doesn't do this for us.
4972     SDValue Mask = Op.getOperand(5);
4973     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4974 
4975     SDValue Val = Op.getOperand(2);
4976     MVT VT = Val.getSimpleValueType();
4977     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4978 
4979     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4980     if (!IsUnmasked) {
4981       MVT MaskVT = getMaskTypeFor(ContainerVT);
4982       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4983     }
4984 
4985     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4986 
4987     SDValue IntID = DAG.getTargetConstant(
4988         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4989         XLenVT);
4990 
4991     auto *Store = cast<MemIntrinsicSDNode>(Op);
4992     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4993     Ops.push_back(Val);
4994     Ops.push_back(Op.getOperand(3)); // Ptr
4995     Ops.push_back(Op.getOperand(4)); // Stride
4996     if (!IsUnmasked)
4997       Ops.push_back(Mask);
4998     Ops.push_back(VL);
4999 
5000     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5001                                    Ops, Store->getMemoryVT(),
5002                                    Store->getMemOperand());
5003   }
5004   }
5005 
5006   return SDValue();
5007 }
5008 
5009 static MVT getLMUL1VT(MVT VT) {
5010   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5011          "Unexpected vector MVT");
5012   return MVT::getScalableVectorVT(
5013       VT.getVectorElementType(),
5014       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5015 }
5016 
5017 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5018   switch (ISDOpcode) {
5019   default:
5020     llvm_unreachable("Unhandled reduction");
5021   case ISD::VECREDUCE_ADD:
5022     return RISCVISD::VECREDUCE_ADD_VL;
5023   case ISD::VECREDUCE_UMAX:
5024     return RISCVISD::VECREDUCE_UMAX_VL;
5025   case ISD::VECREDUCE_SMAX:
5026     return RISCVISD::VECREDUCE_SMAX_VL;
5027   case ISD::VECREDUCE_UMIN:
5028     return RISCVISD::VECREDUCE_UMIN_VL;
5029   case ISD::VECREDUCE_SMIN:
5030     return RISCVISD::VECREDUCE_SMIN_VL;
5031   case ISD::VECREDUCE_AND:
5032     return RISCVISD::VECREDUCE_AND_VL;
5033   case ISD::VECREDUCE_OR:
5034     return RISCVISD::VECREDUCE_OR_VL;
5035   case ISD::VECREDUCE_XOR:
5036     return RISCVISD::VECREDUCE_XOR_VL;
5037   }
5038 }
5039 
5040 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5041                                                          SelectionDAG &DAG,
5042                                                          bool IsVP) const {
5043   SDLoc DL(Op);
5044   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5045   MVT VecVT = Vec.getSimpleValueType();
5046   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5047           Op.getOpcode() == ISD::VECREDUCE_OR ||
5048           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5049           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5050           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5051           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5052          "Unexpected reduction lowering");
5053 
5054   MVT XLenVT = Subtarget.getXLenVT();
5055   assert(Op.getValueType() == XLenVT &&
5056          "Expected reduction output to be legalized to XLenVT");
5057 
5058   MVT ContainerVT = VecVT;
5059   if (VecVT.isFixedLengthVector()) {
5060     ContainerVT = getContainerForFixedLengthVector(VecVT);
5061     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5062   }
5063 
5064   SDValue Mask, VL;
5065   if (IsVP) {
5066     Mask = Op.getOperand(2);
5067     VL = Op.getOperand(3);
5068   } else {
5069     std::tie(Mask, VL) =
5070         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5071   }
5072 
5073   unsigned BaseOpc;
5074   ISD::CondCode CC;
5075   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5076 
5077   switch (Op.getOpcode()) {
5078   default:
5079     llvm_unreachable("Unhandled reduction");
5080   case ISD::VECREDUCE_AND:
5081   case ISD::VP_REDUCE_AND: {
5082     // vcpop ~x == 0
5083     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5084     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5085     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5086     CC = ISD::SETEQ;
5087     BaseOpc = ISD::AND;
5088     break;
5089   }
5090   case ISD::VECREDUCE_OR:
5091   case ISD::VP_REDUCE_OR:
5092     // vcpop x != 0
5093     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5094     CC = ISD::SETNE;
5095     BaseOpc = ISD::OR;
5096     break;
5097   case ISD::VECREDUCE_XOR:
5098   case ISD::VP_REDUCE_XOR: {
5099     // ((vcpop x) & 1) != 0
5100     SDValue One = DAG.getConstant(1, DL, XLenVT);
5101     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5102     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5103     CC = ISD::SETNE;
5104     BaseOpc = ISD::XOR;
5105     break;
5106   }
5107   }
5108 
5109   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5110 
5111   if (!IsVP)
5112     return SetCC;
5113 
5114   // Now include the start value in the operation.
5115   // Note that we must return the start value when no elements are operated
5116   // upon. The vcpop instructions we've emitted in each case above will return
5117   // 0 for an inactive vector, and so we've already received the neutral value:
5118   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5119   // can simply include the start value.
5120   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5121 }
5122 
5123 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5124                                             SelectionDAG &DAG) const {
5125   SDLoc DL(Op);
5126   SDValue Vec = Op.getOperand(0);
5127   EVT VecEVT = Vec.getValueType();
5128 
5129   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5130 
5131   // Due to ordering in legalize types we may have a vector type that needs to
5132   // be split. Do that manually so we can get down to a legal type.
5133   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5134          TargetLowering::TypeSplitVector) {
5135     SDValue Lo, Hi;
5136     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5137     VecEVT = Lo.getValueType();
5138     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5139   }
5140 
5141   // TODO: The type may need to be widened rather than split. Or widened before
5142   // it can be split.
5143   if (!isTypeLegal(VecEVT))
5144     return SDValue();
5145 
5146   MVT VecVT = VecEVT.getSimpleVT();
5147   MVT VecEltVT = VecVT.getVectorElementType();
5148   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5149 
5150   MVT ContainerVT = VecVT;
5151   if (VecVT.isFixedLengthVector()) {
5152     ContainerVT = getContainerForFixedLengthVector(VecVT);
5153     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5154   }
5155 
5156   MVT M1VT = getLMUL1VT(ContainerVT);
5157   MVT XLenVT = Subtarget.getXLenVT();
5158 
5159   SDValue Mask, VL;
5160   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5161 
5162   SDValue NeutralElem =
5163       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5164   SDValue IdentitySplat =
5165       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5166                        M1VT, DL, DAG, Subtarget);
5167   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5168                                   IdentitySplat, Mask, VL);
5169   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5170                              DAG.getConstant(0, DL, XLenVT));
5171   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5172 }
5173 
5174 // Given a reduction op, this function returns the matching reduction opcode,
5175 // the vector SDValue and the scalar SDValue required to lower this to a
5176 // RISCVISD node.
5177 static std::tuple<unsigned, SDValue, SDValue>
5178 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5179   SDLoc DL(Op);
5180   auto Flags = Op->getFlags();
5181   unsigned Opcode = Op.getOpcode();
5182   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5183   switch (Opcode) {
5184   default:
5185     llvm_unreachable("Unhandled reduction");
5186   case ISD::VECREDUCE_FADD: {
5187     // Use positive zero if we can. It is cheaper to materialize.
5188     SDValue Zero =
5189         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5190     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5191   }
5192   case ISD::VECREDUCE_SEQ_FADD:
5193     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5194                            Op.getOperand(0));
5195   case ISD::VECREDUCE_FMIN:
5196     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5197                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5198   case ISD::VECREDUCE_FMAX:
5199     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5200                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5201   }
5202 }
5203 
5204 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5205                                               SelectionDAG &DAG) const {
5206   SDLoc DL(Op);
5207   MVT VecEltVT = Op.getSimpleValueType();
5208 
5209   unsigned RVVOpcode;
5210   SDValue VectorVal, ScalarVal;
5211   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5212       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5213   MVT VecVT = VectorVal.getSimpleValueType();
5214 
5215   MVT ContainerVT = VecVT;
5216   if (VecVT.isFixedLengthVector()) {
5217     ContainerVT = getContainerForFixedLengthVector(VecVT);
5218     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5219   }
5220 
5221   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5222   MVT XLenVT = Subtarget.getXLenVT();
5223 
5224   SDValue Mask, VL;
5225   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5226 
5227   SDValue ScalarSplat =
5228       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5229                        M1VT, DL, DAG, Subtarget);
5230   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5231                                   VectorVal, ScalarSplat, Mask, VL);
5232   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5233                      DAG.getConstant(0, DL, XLenVT));
5234 }
5235 
5236 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5237   switch (ISDOpcode) {
5238   default:
5239     llvm_unreachable("Unhandled reduction");
5240   case ISD::VP_REDUCE_ADD:
5241     return RISCVISD::VECREDUCE_ADD_VL;
5242   case ISD::VP_REDUCE_UMAX:
5243     return RISCVISD::VECREDUCE_UMAX_VL;
5244   case ISD::VP_REDUCE_SMAX:
5245     return RISCVISD::VECREDUCE_SMAX_VL;
5246   case ISD::VP_REDUCE_UMIN:
5247     return RISCVISD::VECREDUCE_UMIN_VL;
5248   case ISD::VP_REDUCE_SMIN:
5249     return RISCVISD::VECREDUCE_SMIN_VL;
5250   case ISD::VP_REDUCE_AND:
5251     return RISCVISD::VECREDUCE_AND_VL;
5252   case ISD::VP_REDUCE_OR:
5253     return RISCVISD::VECREDUCE_OR_VL;
5254   case ISD::VP_REDUCE_XOR:
5255     return RISCVISD::VECREDUCE_XOR_VL;
5256   case ISD::VP_REDUCE_FADD:
5257     return RISCVISD::VECREDUCE_FADD_VL;
5258   case ISD::VP_REDUCE_SEQ_FADD:
5259     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5260   case ISD::VP_REDUCE_FMAX:
5261     return RISCVISD::VECREDUCE_FMAX_VL;
5262   case ISD::VP_REDUCE_FMIN:
5263     return RISCVISD::VECREDUCE_FMIN_VL;
5264   }
5265 }
5266 
5267 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5268                                            SelectionDAG &DAG) const {
5269   SDLoc DL(Op);
5270   SDValue Vec = Op.getOperand(1);
5271   EVT VecEVT = Vec.getValueType();
5272 
5273   // TODO: The type may need to be widened rather than split. Or widened before
5274   // it can be split.
5275   if (!isTypeLegal(VecEVT))
5276     return SDValue();
5277 
5278   MVT VecVT = VecEVT.getSimpleVT();
5279   MVT VecEltVT = VecVT.getVectorElementType();
5280   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5281 
5282   MVT ContainerVT = VecVT;
5283   if (VecVT.isFixedLengthVector()) {
5284     ContainerVT = getContainerForFixedLengthVector(VecVT);
5285     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5286   }
5287 
5288   SDValue VL = Op.getOperand(3);
5289   SDValue Mask = Op.getOperand(2);
5290 
5291   MVT M1VT = getLMUL1VT(ContainerVT);
5292   MVT XLenVT = Subtarget.getXLenVT();
5293   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5294 
5295   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5296                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5297                                         DL, DAG, Subtarget);
5298   SDValue Reduction =
5299       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5300   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5301                              DAG.getConstant(0, DL, XLenVT));
5302   if (!VecVT.isInteger())
5303     return Elt0;
5304   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5305 }
5306 
5307 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5308                                                    SelectionDAG &DAG) const {
5309   SDValue Vec = Op.getOperand(0);
5310   SDValue SubVec = Op.getOperand(1);
5311   MVT VecVT = Vec.getSimpleValueType();
5312   MVT SubVecVT = SubVec.getSimpleValueType();
5313 
5314   SDLoc DL(Op);
5315   MVT XLenVT = Subtarget.getXLenVT();
5316   unsigned OrigIdx = Op.getConstantOperandVal(2);
5317   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5318 
5319   // We don't have the ability to slide mask vectors up indexed by their i1
5320   // elements; the smallest we can do is i8. Often we are able to bitcast to
5321   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5322   // into a scalable one, we might not necessarily have enough scalable
5323   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5324   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5325       (OrigIdx != 0 || !Vec.isUndef())) {
5326     if (VecVT.getVectorMinNumElements() >= 8 &&
5327         SubVecVT.getVectorMinNumElements() >= 8) {
5328       assert(OrigIdx % 8 == 0 && "Invalid index");
5329       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5330              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5331              "Unexpected mask vector lowering");
5332       OrigIdx /= 8;
5333       SubVecVT =
5334           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5335                            SubVecVT.isScalableVector());
5336       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5337                                VecVT.isScalableVector());
5338       Vec = DAG.getBitcast(VecVT, Vec);
5339       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5340     } else {
5341       // We can't slide this mask vector up indexed by its i1 elements.
5342       // This poses a problem when we wish to insert a scalable vector which
5343       // can't be re-expressed as a larger type. Just choose the slow path and
5344       // extend to a larger type, then truncate back down.
5345       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5346       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5347       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5348       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5349       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5350                         Op.getOperand(2));
5351       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5352       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5353     }
5354   }
5355 
5356   // If the subvector vector is a fixed-length type, we cannot use subregister
5357   // manipulation to simplify the codegen; we don't know which register of a
5358   // LMUL group contains the specific subvector as we only know the minimum
5359   // register size. Therefore we must slide the vector group up the full
5360   // amount.
5361   if (SubVecVT.isFixedLengthVector()) {
5362     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5363       return Op;
5364     MVT ContainerVT = VecVT;
5365     if (VecVT.isFixedLengthVector()) {
5366       ContainerVT = getContainerForFixedLengthVector(VecVT);
5367       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5368     }
5369     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5370                          DAG.getUNDEF(ContainerVT), SubVec,
5371                          DAG.getConstant(0, DL, XLenVT));
5372     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5373       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5374       return DAG.getBitcast(Op.getValueType(), SubVec);
5375     }
5376     SDValue Mask =
5377         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5378     // Set the vector length to only the number of elements we care about. Note
5379     // that for slideup this includes the offset.
5380     SDValue VL =
5381         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5382     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5383     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5384                                   SubVec, SlideupAmt, Mask, VL);
5385     if (VecVT.isFixedLengthVector())
5386       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5387     return DAG.getBitcast(Op.getValueType(), Slideup);
5388   }
5389 
5390   unsigned SubRegIdx, RemIdx;
5391   std::tie(SubRegIdx, RemIdx) =
5392       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5393           VecVT, SubVecVT, OrigIdx, TRI);
5394 
5395   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5396   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5397                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5398                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5399 
5400   // 1. If the Idx has been completely eliminated and this subvector's size is
5401   // a vector register or a multiple thereof, or the surrounding elements are
5402   // undef, then this is a subvector insert which naturally aligns to a vector
5403   // register. These can easily be handled using subregister manipulation.
5404   // 2. If the subvector is smaller than a vector register, then the insertion
5405   // must preserve the undisturbed elements of the register. We do this by
5406   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5407   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5408   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5409   // LMUL=1 type back into the larger vector (resolving to another subregister
5410   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5411   // to avoid allocating a large register group to hold our subvector.
5412   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5413     return Op;
5414 
5415   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5416   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5417   // (in our case undisturbed). This means we can set up a subvector insertion
5418   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5419   // size of the subvector.
5420   MVT InterSubVT = VecVT;
5421   SDValue AlignedExtract = Vec;
5422   unsigned AlignedIdx = OrigIdx - RemIdx;
5423   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5424     InterSubVT = getLMUL1VT(VecVT);
5425     // Extract a subvector equal to the nearest full vector register type. This
5426     // should resolve to a EXTRACT_SUBREG instruction.
5427     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5428                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5429   }
5430 
5431   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5432   // For scalable vectors this must be further multiplied by vscale.
5433   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5434 
5435   SDValue Mask, VL;
5436   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5437 
5438   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5439   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5440   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5441   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5442 
5443   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5444                        DAG.getUNDEF(InterSubVT), SubVec,
5445                        DAG.getConstant(0, DL, XLenVT));
5446 
5447   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5448                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5449 
5450   // If required, insert this subvector back into the correct vector register.
5451   // This should resolve to an INSERT_SUBREG instruction.
5452   if (VecVT.bitsGT(InterSubVT))
5453     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5454                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5455 
5456   // We might have bitcast from a mask type: cast back to the original type if
5457   // required.
5458   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5459 }
5460 
5461 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5462                                                     SelectionDAG &DAG) const {
5463   SDValue Vec = Op.getOperand(0);
5464   MVT SubVecVT = Op.getSimpleValueType();
5465   MVT VecVT = Vec.getSimpleValueType();
5466 
5467   SDLoc DL(Op);
5468   MVT XLenVT = Subtarget.getXLenVT();
5469   unsigned OrigIdx = Op.getConstantOperandVal(1);
5470   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5471 
5472   // We don't have the ability to slide mask vectors down indexed by their i1
5473   // elements; the smallest we can do is i8. Often we are able to bitcast to
5474   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5475   // from a scalable one, we might not necessarily have enough scalable
5476   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5477   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5478     if (VecVT.getVectorMinNumElements() >= 8 &&
5479         SubVecVT.getVectorMinNumElements() >= 8) {
5480       assert(OrigIdx % 8 == 0 && "Invalid index");
5481       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5482              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5483              "Unexpected mask vector lowering");
5484       OrigIdx /= 8;
5485       SubVecVT =
5486           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5487                            SubVecVT.isScalableVector());
5488       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5489                                VecVT.isScalableVector());
5490       Vec = DAG.getBitcast(VecVT, Vec);
5491     } else {
5492       // We can't slide this mask vector down, indexed by its i1 elements.
5493       // This poses a problem when we wish to extract a scalable vector which
5494       // can't be re-expressed as a larger type. Just choose the slow path and
5495       // extend to a larger type, then truncate back down.
5496       // TODO: We could probably improve this when extracting certain fixed
5497       // from fixed, where we can extract as i8 and shift the correct element
5498       // right to reach the desired subvector?
5499       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5500       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5501       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5502       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5503                         Op.getOperand(1));
5504       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5505       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5506     }
5507   }
5508 
5509   // If the subvector vector is a fixed-length type, we cannot use subregister
5510   // manipulation to simplify the codegen; we don't know which register of a
5511   // LMUL group contains the specific subvector as we only know the minimum
5512   // register size. Therefore we must slide the vector group down the full
5513   // amount.
5514   if (SubVecVT.isFixedLengthVector()) {
5515     // With an index of 0 this is a cast-like subvector, which can be performed
5516     // with subregister operations.
5517     if (OrigIdx == 0)
5518       return Op;
5519     MVT ContainerVT = VecVT;
5520     if (VecVT.isFixedLengthVector()) {
5521       ContainerVT = getContainerForFixedLengthVector(VecVT);
5522       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5523     }
5524     SDValue Mask =
5525         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5526     // Set the vector length to only the number of elements we care about. This
5527     // avoids sliding down elements we're going to discard straight away.
5528     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5529     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5530     SDValue Slidedown =
5531         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5532                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5533     // Now we can use a cast-like subvector extract to get the result.
5534     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5535                             DAG.getConstant(0, DL, XLenVT));
5536     return DAG.getBitcast(Op.getValueType(), Slidedown);
5537   }
5538 
5539   unsigned SubRegIdx, RemIdx;
5540   std::tie(SubRegIdx, RemIdx) =
5541       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5542           VecVT, SubVecVT, OrigIdx, TRI);
5543 
5544   // If the Idx has been completely eliminated then this is a subvector extract
5545   // which naturally aligns to a vector register. These can easily be handled
5546   // using subregister manipulation.
5547   if (RemIdx == 0)
5548     return Op;
5549 
5550   // Else we must shift our vector register directly to extract the subvector.
5551   // Do this using VSLIDEDOWN.
5552 
5553   // If the vector type is an LMUL-group type, extract a subvector equal to the
5554   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5555   // instruction.
5556   MVT InterSubVT = VecVT;
5557   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5558     InterSubVT = getLMUL1VT(VecVT);
5559     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5560                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5561   }
5562 
5563   // Slide this vector register down by the desired number of elements in order
5564   // to place the desired subvector starting at element 0.
5565   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5566   // For scalable vectors this must be further multiplied by vscale.
5567   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5568 
5569   SDValue Mask, VL;
5570   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5571   SDValue Slidedown =
5572       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5573                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5574 
5575   // Now the vector is in the right position, extract our final subvector. This
5576   // should resolve to a COPY.
5577   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5578                           DAG.getConstant(0, DL, XLenVT));
5579 
5580   // We might have bitcast from a mask type: cast back to the original type if
5581   // required.
5582   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5583 }
5584 
5585 // Lower step_vector to the vid instruction. Any non-identity step value must
5586 // be accounted for my manual expansion.
5587 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5588                                               SelectionDAG &DAG) const {
5589   SDLoc DL(Op);
5590   MVT VT = Op.getSimpleValueType();
5591   MVT XLenVT = Subtarget.getXLenVT();
5592   SDValue Mask, VL;
5593   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5594   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5595   uint64_t StepValImm = Op.getConstantOperandVal(0);
5596   if (StepValImm != 1) {
5597     if (isPowerOf2_64(StepValImm)) {
5598       SDValue StepVal =
5599           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5600                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5601       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5602     } else {
5603       SDValue StepVal = lowerScalarSplat(
5604           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5605           VL, VT, DL, DAG, Subtarget);
5606       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5607     }
5608   }
5609   return StepVec;
5610 }
5611 
5612 // Implement vector_reverse using vrgather.vv with indices determined by
5613 // subtracting the id of each element from (VLMAX-1). This will convert
5614 // the indices like so:
5615 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5616 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5617 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5618                                                  SelectionDAG &DAG) const {
5619   SDLoc DL(Op);
5620   MVT VecVT = Op.getSimpleValueType();
5621   unsigned EltSize = VecVT.getScalarSizeInBits();
5622   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5623 
5624   unsigned MaxVLMAX = 0;
5625   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5626   if (VectorBitsMax != 0)
5627     MaxVLMAX =
5628         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5629 
5630   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5631   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5632 
5633   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5634   // to use vrgatherei16.vv.
5635   // TODO: It's also possible to use vrgatherei16.vv for other types to
5636   // decrease register width for the index calculation.
5637   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5638     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5639     // Reverse each half, then reassemble them in reverse order.
5640     // NOTE: It's also possible that after splitting that VLMAX no longer
5641     // requires vrgatherei16.vv.
5642     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5643       SDValue Lo, Hi;
5644       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5645       EVT LoVT, HiVT;
5646       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5647       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5648       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5649       // Reassemble the low and high pieces reversed.
5650       // FIXME: This is a CONCAT_VECTORS.
5651       SDValue Res =
5652           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5653                       DAG.getIntPtrConstant(0, DL));
5654       return DAG.getNode(
5655           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5656           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5657     }
5658 
5659     // Just promote the int type to i16 which will double the LMUL.
5660     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5661     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5662   }
5663 
5664   MVT XLenVT = Subtarget.getXLenVT();
5665   SDValue Mask, VL;
5666   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5667 
5668   // Calculate VLMAX-1 for the desired SEW.
5669   unsigned MinElts = VecVT.getVectorMinNumElements();
5670   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5671                               DAG.getConstant(MinElts, DL, XLenVT));
5672   SDValue VLMinus1 =
5673       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5674 
5675   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5676   bool IsRV32E64 =
5677       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5678   SDValue SplatVL;
5679   if (!IsRV32E64)
5680     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5681   else
5682     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5683                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5684 
5685   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5686   SDValue Indices =
5687       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5688 
5689   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5690 }
5691 
5692 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5693                                                 SelectionDAG &DAG) const {
5694   SDLoc DL(Op);
5695   SDValue V1 = Op.getOperand(0);
5696   SDValue V2 = Op.getOperand(1);
5697   MVT XLenVT = Subtarget.getXLenVT();
5698   MVT VecVT = Op.getSimpleValueType();
5699 
5700   unsigned MinElts = VecVT.getVectorMinNumElements();
5701   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5702                               DAG.getConstant(MinElts, DL, XLenVT));
5703 
5704   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5705   SDValue DownOffset, UpOffset;
5706   if (ImmValue >= 0) {
5707     // The operand is a TargetConstant, we need to rebuild it as a regular
5708     // constant.
5709     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5710     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5711   } else {
5712     // The operand is a TargetConstant, we need to rebuild it as a regular
5713     // constant rather than negating the original operand.
5714     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5715     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5716   }
5717 
5718   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5719 
5720   SDValue SlideDown =
5721       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5722                   DownOffset, TrueMask, UpOffset);
5723   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5724                      TrueMask,
5725                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5726 }
5727 
5728 SDValue
5729 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5730                                                      SelectionDAG &DAG) const {
5731   SDLoc DL(Op);
5732   auto *Load = cast<LoadSDNode>(Op);
5733 
5734   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5735                                         Load->getMemoryVT(),
5736                                         *Load->getMemOperand()) &&
5737          "Expecting a correctly-aligned load");
5738 
5739   MVT VT = Op.getSimpleValueType();
5740   MVT XLenVT = Subtarget.getXLenVT();
5741   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5742 
5743   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5744 
5745   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5746   SDValue IntID = DAG.getTargetConstant(
5747       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5748   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5749   if (!IsMaskOp)
5750     Ops.push_back(DAG.getUNDEF(ContainerVT));
5751   Ops.push_back(Load->getBasePtr());
5752   Ops.push_back(VL);
5753   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5754   SDValue NewLoad =
5755       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5756                               Load->getMemoryVT(), Load->getMemOperand());
5757 
5758   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5759   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5760 }
5761 
5762 SDValue
5763 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5764                                                       SelectionDAG &DAG) const {
5765   SDLoc DL(Op);
5766   auto *Store = cast<StoreSDNode>(Op);
5767 
5768   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5769                                         Store->getMemoryVT(),
5770                                         *Store->getMemOperand()) &&
5771          "Expecting a correctly-aligned store");
5772 
5773   SDValue StoreVal = Store->getValue();
5774   MVT VT = StoreVal.getSimpleValueType();
5775   MVT XLenVT = Subtarget.getXLenVT();
5776 
5777   // If the size less than a byte, we need to pad with zeros to make a byte.
5778   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5779     VT = MVT::v8i1;
5780     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5781                            DAG.getConstant(0, DL, VT), StoreVal,
5782                            DAG.getIntPtrConstant(0, DL));
5783   }
5784 
5785   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5786 
5787   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5788 
5789   SDValue NewValue =
5790       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5791 
5792   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5793   SDValue IntID = DAG.getTargetConstant(
5794       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5795   return DAG.getMemIntrinsicNode(
5796       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5797       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5798       Store->getMemoryVT(), Store->getMemOperand());
5799 }
5800 
5801 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5802                                              SelectionDAG &DAG) const {
5803   SDLoc DL(Op);
5804   MVT VT = Op.getSimpleValueType();
5805 
5806   const auto *MemSD = cast<MemSDNode>(Op);
5807   EVT MemVT = MemSD->getMemoryVT();
5808   MachineMemOperand *MMO = MemSD->getMemOperand();
5809   SDValue Chain = MemSD->getChain();
5810   SDValue BasePtr = MemSD->getBasePtr();
5811 
5812   SDValue Mask, PassThru, VL;
5813   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5814     Mask = VPLoad->getMask();
5815     PassThru = DAG.getUNDEF(VT);
5816     VL = VPLoad->getVectorLength();
5817   } else {
5818     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5819     Mask = MLoad->getMask();
5820     PassThru = MLoad->getPassThru();
5821   }
5822 
5823   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5824 
5825   MVT XLenVT = Subtarget.getXLenVT();
5826 
5827   MVT ContainerVT = VT;
5828   if (VT.isFixedLengthVector()) {
5829     ContainerVT = getContainerForFixedLengthVector(VT);
5830     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5831     if (!IsUnmasked) {
5832       MVT MaskVT = getMaskTypeFor(ContainerVT);
5833       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5834     }
5835   }
5836 
5837   if (!VL)
5838     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5839 
5840   unsigned IntID =
5841       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5842   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5843   if (IsUnmasked)
5844     Ops.push_back(DAG.getUNDEF(ContainerVT));
5845   else
5846     Ops.push_back(PassThru);
5847   Ops.push_back(BasePtr);
5848   if (!IsUnmasked)
5849     Ops.push_back(Mask);
5850   Ops.push_back(VL);
5851   if (!IsUnmasked)
5852     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5853 
5854   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5855 
5856   SDValue Result =
5857       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5858   Chain = Result.getValue(1);
5859 
5860   if (VT.isFixedLengthVector())
5861     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5862 
5863   return DAG.getMergeValues({Result, Chain}, DL);
5864 }
5865 
5866 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5867                                               SelectionDAG &DAG) const {
5868   SDLoc DL(Op);
5869 
5870   const auto *MemSD = cast<MemSDNode>(Op);
5871   EVT MemVT = MemSD->getMemoryVT();
5872   MachineMemOperand *MMO = MemSD->getMemOperand();
5873   SDValue Chain = MemSD->getChain();
5874   SDValue BasePtr = MemSD->getBasePtr();
5875   SDValue Val, Mask, VL;
5876 
5877   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5878     Val = VPStore->getValue();
5879     Mask = VPStore->getMask();
5880     VL = VPStore->getVectorLength();
5881   } else {
5882     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5883     Val = MStore->getValue();
5884     Mask = MStore->getMask();
5885   }
5886 
5887   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5888 
5889   MVT VT = Val.getSimpleValueType();
5890   MVT XLenVT = Subtarget.getXLenVT();
5891 
5892   MVT ContainerVT = VT;
5893   if (VT.isFixedLengthVector()) {
5894     ContainerVT = getContainerForFixedLengthVector(VT);
5895 
5896     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5897     if (!IsUnmasked) {
5898       MVT MaskVT = getMaskTypeFor(ContainerVT);
5899       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5900     }
5901   }
5902 
5903   if (!VL)
5904     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5905 
5906   unsigned IntID =
5907       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5908   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5909   Ops.push_back(Val);
5910   Ops.push_back(BasePtr);
5911   if (!IsUnmasked)
5912     Ops.push_back(Mask);
5913   Ops.push_back(VL);
5914 
5915   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5916                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5917 }
5918 
5919 SDValue
5920 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5921                                                       SelectionDAG &DAG) const {
5922   MVT InVT = Op.getOperand(0).getSimpleValueType();
5923   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5924 
5925   MVT VT = Op.getSimpleValueType();
5926 
5927   SDValue Op1 =
5928       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5929   SDValue Op2 =
5930       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5931 
5932   SDLoc DL(Op);
5933   SDValue VL =
5934       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5935 
5936   MVT MaskVT = getMaskTypeFor(ContainerVT);
5937   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
5938 
5939   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5940                             Op.getOperand(2), Mask, VL);
5941 
5942   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5943 }
5944 
5945 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5946     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5947   MVT VT = Op.getSimpleValueType();
5948 
5949   if (VT.getVectorElementType() == MVT::i1)
5950     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5951 
5952   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5953 }
5954 
5955 SDValue
5956 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5957                                                       SelectionDAG &DAG) const {
5958   unsigned Opc;
5959   switch (Op.getOpcode()) {
5960   default: llvm_unreachable("Unexpected opcode!");
5961   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5962   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5963   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5964   }
5965 
5966   return lowerToScalableOp(Op, DAG, Opc);
5967 }
5968 
5969 // Lower vector ABS to smax(X, sub(0, X)).
5970 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5971   SDLoc DL(Op);
5972   MVT VT = Op.getSimpleValueType();
5973   SDValue X = Op.getOperand(0);
5974 
5975   assert(VT.isFixedLengthVector() && "Unexpected type");
5976 
5977   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5978   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5979 
5980   SDValue Mask, VL;
5981   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5982 
5983   SDValue SplatZero = DAG.getNode(
5984       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5985       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5986   SDValue NegX =
5987       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5988   SDValue Max =
5989       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5990 
5991   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5992 }
5993 
5994 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5995     SDValue Op, SelectionDAG &DAG) const {
5996   SDLoc DL(Op);
5997   MVT VT = Op.getSimpleValueType();
5998   SDValue Mag = Op.getOperand(0);
5999   SDValue Sign = Op.getOperand(1);
6000   assert(Mag.getValueType() == Sign.getValueType() &&
6001          "Can only handle COPYSIGN with matching types.");
6002 
6003   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6004   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6005   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6006 
6007   SDValue Mask, VL;
6008   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6009 
6010   SDValue CopySign =
6011       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6012 
6013   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6014 }
6015 
6016 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6017     SDValue Op, SelectionDAG &DAG) const {
6018   MVT VT = Op.getSimpleValueType();
6019   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6020 
6021   MVT I1ContainerVT =
6022       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6023 
6024   SDValue CC =
6025       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6026   SDValue Op1 =
6027       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6028   SDValue Op2 =
6029       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6030 
6031   SDLoc DL(Op);
6032   SDValue Mask, VL;
6033   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6034 
6035   SDValue Select =
6036       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6037 
6038   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6039 }
6040 
6041 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6042                                                unsigned NewOpc,
6043                                                bool HasMask) const {
6044   MVT VT = Op.getSimpleValueType();
6045   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6046 
6047   // Create list of operands by converting existing ones to scalable types.
6048   SmallVector<SDValue, 6> Ops;
6049   for (const SDValue &V : Op->op_values()) {
6050     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6051 
6052     // Pass through non-vector operands.
6053     if (!V.getValueType().isVector()) {
6054       Ops.push_back(V);
6055       continue;
6056     }
6057 
6058     // "cast" fixed length vector to a scalable vector.
6059     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6060            "Only fixed length vectors are supported!");
6061     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6062   }
6063 
6064   SDLoc DL(Op);
6065   SDValue Mask, VL;
6066   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6067   if (HasMask)
6068     Ops.push_back(Mask);
6069   Ops.push_back(VL);
6070 
6071   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6072   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6073 }
6074 
6075 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6076 // * Operands of each node are assumed to be in the same order.
6077 // * The EVL operand is promoted from i32 to i64 on RV64.
6078 // * Fixed-length vectors are converted to their scalable-vector container
6079 //   types.
6080 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6081                                        unsigned RISCVISDOpc) const {
6082   SDLoc DL(Op);
6083   MVT VT = Op.getSimpleValueType();
6084   SmallVector<SDValue, 4> Ops;
6085 
6086   for (const auto &OpIdx : enumerate(Op->ops())) {
6087     SDValue V = OpIdx.value();
6088     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6089     // Pass through operands which aren't fixed-length vectors.
6090     if (!V.getValueType().isFixedLengthVector()) {
6091       Ops.push_back(V);
6092       continue;
6093     }
6094     // "cast" fixed length vector to a scalable vector.
6095     MVT OpVT = V.getSimpleValueType();
6096     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6097     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6098            "Only fixed length vectors are supported!");
6099     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6100   }
6101 
6102   if (!VT.isFixedLengthVector())
6103     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6104 
6105   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6106 
6107   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6108 
6109   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6110 }
6111 
6112 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6113                                               SelectionDAG &DAG) const {
6114   SDLoc DL(Op);
6115   MVT VT = Op.getSimpleValueType();
6116 
6117   SDValue Src = Op.getOperand(0);
6118   // NOTE: Mask is dropped.
6119   SDValue VL = Op.getOperand(2);
6120 
6121   MVT ContainerVT = VT;
6122   if (VT.isFixedLengthVector()) {
6123     ContainerVT = getContainerForFixedLengthVector(VT);
6124     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6125     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6126   }
6127 
6128   MVT XLenVT = Subtarget.getXLenVT();
6129   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6130   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6131                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6132 
6133   SDValue SplatValue = DAG.getConstant(
6134       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6135   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6136                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6137 
6138   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6139                                Splat, ZeroSplat, VL);
6140   if (!VT.isFixedLengthVector())
6141     return Result;
6142   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6143 }
6144 
6145 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6146                                                 SelectionDAG &DAG) const {
6147   SDLoc DL(Op);
6148   MVT VT = Op.getSimpleValueType();
6149 
6150   SDValue Op1 = Op.getOperand(0);
6151   SDValue Op2 = Op.getOperand(1);
6152   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6153   // NOTE: Mask is dropped.
6154   SDValue VL = Op.getOperand(4);
6155 
6156   MVT ContainerVT = VT;
6157   if (VT.isFixedLengthVector()) {
6158     ContainerVT = getContainerForFixedLengthVector(VT);
6159     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6160     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6161   }
6162 
6163   SDValue Result;
6164   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6165 
6166   switch (Condition) {
6167   default:
6168     break;
6169   // X != Y  --> (X^Y)
6170   case ISD::SETNE:
6171     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6172     break;
6173   // X == Y  --> ~(X^Y)
6174   case ISD::SETEQ: {
6175     SDValue Temp =
6176         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6177     Result =
6178         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6179     break;
6180   }
6181   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6182   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6183   case ISD::SETGT:
6184   case ISD::SETULT: {
6185     SDValue Temp =
6186         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6187     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6188     break;
6189   }
6190   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6191   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6192   case ISD::SETLT:
6193   case ISD::SETUGT: {
6194     SDValue Temp =
6195         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6196     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6197     break;
6198   }
6199   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6200   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6201   case ISD::SETGE:
6202   case ISD::SETULE: {
6203     SDValue Temp =
6204         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6205     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6206     break;
6207   }
6208   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6209   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6210   case ISD::SETLE:
6211   case ISD::SETUGE: {
6212     SDValue Temp =
6213         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6214     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6215     break;
6216   }
6217   }
6218 
6219   if (!VT.isFixedLengthVector())
6220     return Result;
6221   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6222 }
6223 
6224 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6225 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6226                                                 unsigned RISCVISDOpc) const {
6227   SDLoc DL(Op);
6228 
6229   SDValue Src = Op.getOperand(0);
6230   SDValue Mask = Op.getOperand(1);
6231   SDValue VL = Op.getOperand(2);
6232 
6233   MVT DstVT = Op.getSimpleValueType();
6234   MVT SrcVT = Src.getSimpleValueType();
6235   if (DstVT.isFixedLengthVector()) {
6236     DstVT = getContainerForFixedLengthVector(DstVT);
6237     SrcVT = getContainerForFixedLengthVector(SrcVT);
6238     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6239     MVT MaskVT = getMaskTypeFor(DstVT);
6240     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6241   }
6242 
6243   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6244                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6245                                 ? RISCVISD::VSEXT_VL
6246                                 : RISCVISD::VZEXT_VL;
6247 
6248   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6249   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6250 
6251   SDValue Result;
6252   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6253     if (SrcVT.isInteger()) {
6254       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6255 
6256       // Do we need to do any pre-widening before converting?
6257       if (SrcEltSize == 1) {
6258         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6259         MVT XLenVT = Subtarget.getXLenVT();
6260         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6261         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6262                                         DAG.getUNDEF(IntVT), Zero, VL);
6263         SDValue One = DAG.getConstant(
6264             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6265         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6266                                        DAG.getUNDEF(IntVT), One, VL);
6267         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6268                           ZeroSplat, VL);
6269       } else if (DstEltSize > (2 * SrcEltSize)) {
6270         // Widen before converting.
6271         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6272                                      DstVT.getVectorElementCount());
6273         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6274       }
6275 
6276       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6277     } else {
6278       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6279              "Wrong input/output vector types");
6280 
6281       // Convert f16 to f32 then convert f32 to i64.
6282       if (DstEltSize > (2 * SrcEltSize)) {
6283         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6284         MVT InterimFVT =
6285             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6286         Src =
6287             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6288       }
6289 
6290       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6291     }
6292   } else { // Narrowing + Conversion
6293     if (SrcVT.isInteger()) {
6294       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6295       // First do a narrowing convert to an FP type half the size, then round
6296       // the FP type to a small FP type if needed.
6297 
6298       MVT InterimFVT = DstVT;
6299       if (SrcEltSize > (2 * DstEltSize)) {
6300         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6301         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6302         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6303       }
6304 
6305       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6306 
6307       if (InterimFVT != DstVT) {
6308         Src = Result;
6309         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6310       }
6311     } else {
6312       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6313              "Wrong input/output vector types");
6314       // First do a narrowing conversion to an integer half the size, then
6315       // truncate if needed.
6316 
6317       if (DstEltSize == 1) {
6318         // First convert to the same size integer, then convert to mask using
6319         // setcc.
6320         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6321         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6322                                           DstVT.getVectorElementCount());
6323         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6324 
6325         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6326         // otherwise the conversion was undefined.
6327         MVT XLenVT = Subtarget.getXLenVT();
6328         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6329         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6330                                 DAG.getUNDEF(InterimIVT), SplatZero);
6331         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6332                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6333       } else {
6334         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6335                                           DstVT.getVectorElementCount());
6336 
6337         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6338 
6339         while (InterimIVT != DstVT) {
6340           SrcEltSize /= 2;
6341           Src = Result;
6342           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6343                                         DstVT.getVectorElementCount());
6344           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6345                                Src, Mask, VL);
6346         }
6347       }
6348     }
6349   }
6350 
6351   MVT VT = Op.getSimpleValueType();
6352   if (!VT.isFixedLengthVector())
6353     return Result;
6354   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6355 }
6356 
6357 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6358                                             unsigned MaskOpc,
6359                                             unsigned VecOpc) const {
6360   MVT VT = Op.getSimpleValueType();
6361   if (VT.getVectorElementType() != MVT::i1)
6362     return lowerVPOp(Op, DAG, VecOpc);
6363 
6364   // It is safe to drop mask parameter as masked-off elements are undef.
6365   SDValue Op1 = Op->getOperand(0);
6366   SDValue Op2 = Op->getOperand(1);
6367   SDValue VL = Op->getOperand(3);
6368 
6369   MVT ContainerVT = VT;
6370   const bool IsFixed = VT.isFixedLengthVector();
6371   if (IsFixed) {
6372     ContainerVT = getContainerForFixedLengthVector(VT);
6373     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6374     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6375   }
6376 
6377   SDLoc DL(Op);
6378   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6379   if (!IsFixed)
6380     return Val;
6381   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6382 }
6383 
6384 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6385 // matched to a RVV indexed load. The RVV indexed load instructions only
6386 // support the "unsigned unscaled" addressing mode; indices are implicitly
6387 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6388 // signed or scaled indexing is extended to the XLEN value type and scaled
6389 // accordingly.
6390 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6391                                                SelectionDAG &DAG) const {
6392   SDLoc DL(Op);
6393   MVT VT = Op.getSimpleValueType();
6394 
6395   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6396   EVT MemVT = MemSD->getMemoryVT();
6397   MachineMemOperand *MMO = MemSD->getMemOperand();
6398   SDValue Chain = MemSD->getChain();
6399   SDValue BasePtr = MemSD->getBasePtr();
6400 
6401   ISD::LoadExtType LoadExtType;
6402   SDValue Index, Mask, PassThru, VL;
6403 
6404   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6405     Index = VPGN->getIndex();
6406     Mask = VPGN->getMask();
6407     PassThru = DAG.getUNDEF(VT);
6408     VL = VPGN->getVectorLength();
6409     // VP doesn't support extending loads.
6410     LoadExtType = ISD::NON_EXTLOAD;
6411   } else {
6412     // Else it must be a MGATHER.
6413     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6414     Index = MGN->getIndex();
6415     Mask = MGN->getMask();
6416     PassThru = MGN->getPassThru();
6417     LoadExtType = MGN->getExtensionType();
6418   }
6419 
6420   MVT IndexVT = Index.getSimpleValueType();
6421   MVT XLenVT = Subtarget.getXLenVT();
6422 
6423   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6424          "Unexpected VTs!");
6425   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6426   // Targets have to explicitly opt-in for extending vector loads.
6427   assert(LoadExtType == ISD::NON_EXTLOAD &&
6428          "Unexpected extending MGATHER/VP_GATHER");
6429   (void)LoadExtType;
6430 
6431   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6432   // the selection of the masked intrinsics doesn't do this for us.
6433   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6434 
6435   MVT ContainerVT = VT;
6436   if (VT.isFixedLengthVector()) {
6437     ContainerVT = getContainerForFixedLengthVector(VT);
6438     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6439                                ContainerVT.getVectorElementCount());
6440 
6441     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6442 
6443     if (!IsUnmasked) {
6444       MVT MaskVT = getMaskTypeFor(ContainerVT);
6445       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6446       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6447     }
6448   }
6449 
6450   if (!VL)
6451     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6452 
6453   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6454     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6455     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6456                                    VL);
6457     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6458                         TrueMask, VL);
6459   }
6460 
6461   unsigned IntID =
6462       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6463   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6464   if (IsUnmasked)
6465     Ops.push_back(DAG.getUNDEF(ContainerVT));
6466   else
6467     Ops.push_back(PassThru);
6468   Ops.push_back(BasePtr);
6469   Ops.push_back(Index);
6470   if (!IsUnmasked)
6471     Ops.push_back(Mask);
6472   Ops.push_back(VL);
6473   if (!IsUnmasked)
6474     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6475 
6476   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6477   SDValue Result =
6478       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6479   Chain = Result.getValue(1);
6480 
6481   if (VT.isFixedLengthVector())
6482     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6483 
6484   return DAG.getMergeValues({Result, Chain}, DL);
6485 }
6486 
6487 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6488 // matched to a RVV indexed store. The RVV indexed store instructions only
6489 // support the "unsigned unscaled" addressing mode; indices are implicitly
6490 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6491 // signed or scaled indexing is extended to the XLEN value type and scaled
6492 // accordingly.
6493 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6494                                                 SelectionDAG &DAG) const {
6495   SDLoc DL(Op);
6496   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6497   EVT MemVT = MemSD->getMemoryVT();
6498   MachineMemOperand *MMO = MemSD->getMemOperand();
6499   SDValue Chain = MemSD->getChain();
6500   SDValue BasePtr = MemSD->getBasePtr();
6501 
6502   bool IsTruncatingStore = false;
6503   SDValue Index, Mask, Val, VL;
6504 
6505   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6506     Index = VPSN->getIndex();
6507     Mask = VPSN->getMask();
6508     Val = VPSN->getValue();
6509     VL = VPSN->getVectorLength();
6510     // VP doesn't support truncating stores.
6511     IsTruncatingStore = false;
6512   } else {
6513     // Else it must be a MSCATTER.
6514     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6515     Index = MSN->getIndex();
6516     Mask = MSN->getMask();
6517     Val = MSN->getValue();
6518     IsTruncatingStore = MSN->isTruncatingStore();
6519   }
6520 
6521   MVT VT = Val.getSimpleValueType();
6522   MVT IndexVT = Index.getSimpleValueType();
6523   MVT XLenVT = Subtarget.getXLenVT();
6524 
6525   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6526          "Unexpected VTs!");
6527   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6528   // Targets have to explicitly opt-in for extending vector loads and
6529   // truncating vector stores.
6530   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6531   (void)IsTruncatingStore;
6532 
6533   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6534   // the selection of the masked intrinsics doesn't do this for us.
6535   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6536 
6537   MVT ContainerVT = VT;
6538   if (VT.isFixedLengthVector()) {
6539     ContainerVT = getContainerForFixedLengthVector(VT);
6540     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6541                                ContainerVT.getVectorElementCount());
6542 
6543     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6544     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6545 
6546     if (!IsUnmasked) {
6547       MVT MaskVT = getMaskTypeFor(ContainerVT);
6548       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6549     }
6550   }
6551 
6552   if (!VL)
6553     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6554 
6555   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6556     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6557     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6558                                    VL);
6559     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6560                         TrueMask, VL);
6561   }
6562 
6563   unsigned IntID =
6564       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6565   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6566   Ops.push_back(Val);
6567   Ops.push_back(BasePtr);
6568   Ops.push_back(Index);
6569   if (!IsUnmasked)
6570     Ops.push_back(Mask);
6571   Ops.push_back(VL);
6572 
6573   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6574                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6575 }
6576 
6577 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6578                                                SelectionDAG &DAG) const {
6579   const MVT XLenVT = Subtarget.getXLenVT();
6580   SDLoc DL(Op);
6581   SDValue Chain = Op->getOperand(0);
6582   SDValue SysRegNo = DAG.getTargetConstant(
6583       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6584   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6585   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6586 
6587   // Encoding used for rounding mode in RISCV differs from that used in
6588   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6589   // table, which consists of a sequence of 4-bit fields, each representing
6590   // corresponding FLT_ROUNDS mode.
6591   static const int Table =
6592       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6593       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6594       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6595       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6596       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6597 
6598   SDValue Shift =
6599       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6600   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6601                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6602   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6603                                DAG.getConstant(7, DL, XLenVT));
6604 
6605   return DAG.getMergeValues({Masked, Chain}, DL);
6606 }
6607 
6608 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6609                                                SelectionDAG &DAG) const {
6610   const MVT XLenVT = Subtarget.getXLenVT();
6611   SDLoc DL(Op);
6612   SDValue Chain = Op->getOperand(0);
6613   SDValue RMValue = Op->getOperand(1);
6614   SDValue SysRegNo = DAG.getTargetConstant(
6615       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6616 
6617   // Encoding used for rounding mode in RISCV differs from that used in
6618   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6619   // a table, which consists of a sequence of 4-bit fields, each representing
6620   // corresponding RISCV mode.
6621   static const unsigned Table =
6622       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6623       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6624       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6625       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6626       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6627 
6628   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6629                               DAG.getConstant(2, DL, XLenVT));
6630   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6631                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6632   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6633                         DAG.getConstant(0x7, DL, XLenVT));
6634   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6635                      RMValue);
6636 }
6637 
6638 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6639                                                SelectionDAG &DAG) const {
6640   MachineFunction &MF = DAG.getMachineFunction();
6641 
6642   bool isRISCV64 = Subtarget.is64Bit();
6643   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6644 
6645   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6646   return DAG.getFrameIndex(FI, PtrVT);
6647 }
6648 
6649 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6650   switch (IntNo) {
6651   default:
6652     llvm_unreachable("Unexpected Intrinsic");
6653   case Intrinsic::riscv_bcompress:
6654     return RISCVISD::BCOMPRESSW;
6655   case Intrinsic::riscv_bdecompress:
6656     return RISCVISD::BDECOMPRESSW;
6657   case Intrinsic::riscv_bfp:
6658     return RISCVISD::BFPW;
6659   case Intrinsic::riscv_fsl:
6660     return RISCVISD::FSLW;
6661   case Intrinsic::riscv_fsr:
6662     return RISCVISD::FSRW;
6663   }
6664 }
6665 
6666 // Converts the given intrinsic to a i64 operation with any extension.
6667 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6668                                          unsigned IntNo) {
6669   SDLoc DL(N);
6670   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6671   // Deal with the Instruction Operands
6672   SmallVector<SDValue, 3> NewOps;
6673   for (SDValue Op : drop_begin(N->ops()))
6674     // Promote the operand to i64 type
6675     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6676   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6677   // ReplaceNodeResults requires we maintain the same type for the return value.
6678   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6679 }
6680 
6681 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6682 // form of the given Opcode.
6683 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6684   switch (Opcode) {
6685   default:
6686     llvm_unreachable("Unexpected opcode");
6687   case ISD::SHL:
6688     return RISCVISD::SLLW;
6689   case ISD::SRA:
6690     return RISCVISD::SRAW;
6691   case ISD::SRL:
6692     return RISCVISD::SRLW;
6693   case ISD::SDIV:
6694     return RISCVISD::DIVW;
6695   case ISD::UDIV:
6696     return RISCVISD::DIVUW;
6697   case ISD::UREM:
6698     return RISCVISD::REMUW;
6699   case ISD::ROTL:
6700     return RISCVISD::ROLW;
6701   case ISD::ROTR:
6702     return RISCVISD::RORW;
6703   }
6704 }
6705 
6706 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6707 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6708 // otherwise be promoted to i64, making it difficult to select the
6709 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6710 // type i8/i16/i32 is lost.
6711 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6712                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6713   SDLoc DL(N);
6714   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6715   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6716   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6717   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6718   // ReplaceNodeResults requires we maintain the same type for the return value.
6719   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6720 }
6721 
6722 // Converts the given 32-bit operation to a i64 operation with signed extension
6723 // semantic to reduce the signed extension instructions.
6724 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6725   SDLoc DL(N);
6726   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6727   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6728   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6729   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6730                                DAG.getValueType(MVT::i32));
6731   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6732 }
6733 
6734 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6735                                              SmallVectorImpl<SDValue> &Results,
6736                                              SelectionDAG &DAG) const {
6737   SDLoc DL(N);
6738   switch (N->getOpcode()) {
6739   default:
6740     llvm_unreachable("Don't know how to custom type legalize this operation!");
6741   case ISD::STRICT_FP_TO_SINT:
6742   case ISD::STRICT_FP_TO_UINT:
6743   case ISD::FP_TO_SINT:
6744   case ISD::FP_TO_UINT: {
6745     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6746            "Unexpected custom legalisation");
6747     bool IsStrict = N->isStrictFPOpcode();
6748     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6749                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6750     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6751     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6752         TargetLowering::TypeSoftenFloat) {
6753       if (!isTypeLegal(Op0.getValueType()))
6754         return;
6755       if (IsStrict) {
6756         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6757                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6758         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6759         SDValue Res = DAG.getNode(
6760             Opc, DL, VTs, N->getOperand(0), Op0,
6761             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6762         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6763         Results.push_back(Res.getValue(1));
6764         return;
6765       }
6766       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6767       SDValue Res =
6768           DAG.getNode(Opc, DL, MVT::i64, Op0,
6769                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6770       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6771       return;
6772     }
6773     // If the FP type needs to be softened, emit a library call using the 'si'
6774     // version. If we left it to default legalization we'd end up with 'di'. If
6775     // the FP type doesn't need to be softened just let generic type
6776     // legalization promote the result type.
6777     RTLIB::Libcall LC;
6778     if (IsSigned)
6779       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6780     else
6781       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6782     MakeLibCallOptions CallOptions;
6783     EVT OpVT = Op0.getValueType();
6784     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6785     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6786     SDValue Result;
6787     std::tie(Result, Chain) =
6788         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6789     Results.push_back(Result);
6790     if (IsStrict)
6791       Results.push_back(Chain);
6792     break;
6793   }
6794   case ISD::READCYCLECOUNTER: {
6795     assert(!Subtarget.is64Bit() &&
6796            "READCYCLECOUNTER only has custom type legalization on riscv32");
6797 
6798     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6799     SDValue RCW =
6800         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6801 
6802     Results.push_back(
6803         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6804     Results.push_back(RCW.getValue(2));
6805     break;
6806   }
6807   case ISD::MUL: {
6808     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6809     unsigned XLen = Subtarget.getXLen();
6810     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6811     if (Size > XLen) {
6812       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6813       SDValue LHS = N->getOperand(0);
6814       SDValue RHS = N->getOperand(1);
6815       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6816 
6817       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6818       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6819       // We need exactly one side to be unsigned.
6820       if (LHSIsU == RHSIsU)
6821         return;
6822 
6823       auto MakeMULPair = [&](SDValue S, SDValue U) {
6824         MVT XLenVT = Subtarget.getXLenVT();
6825         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6826         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6827         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6828         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6829         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6830       };
6831 
6832       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6833       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6834 
6835       // The other operand should be signed, but still prefer MULH when
6836       // possible.
6837       if (RHSIsU && LHSIsS && !RHSIsS)
6838         Results.push_back(MakeMULPair(LHS, RHS));
6839       else if (LHSIsU && RHSIsS && !LHSIsS)
6840         Results.push_back(MakeMULPair(RHS, LHS));
6841 
6842       return;
6843     }
6844     LLVM_FALLTHROUGH;
6845   }
6846   case ISD::ADD:
6847   case ISD::SUB:
6848     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6849            "Unexpected custom legalisation");
6850     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6851     break;
6852   case ISD::SHL:
6853   case ISD::SRA:
6854   case ISD::SRL:
6855     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6856            "Unexpected custom legalisation");
6857     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6858       // If we can use a BSET instruction, allow default promotion to apply.
6859       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6860           isOneConstant(N->getOperand(0)))
6861         break;
6862       Results.push_back(customLegalizeToWOp(N, DAG));
6863       break;
6864     }
6865 
6866     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6867     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6868     // shift amount.
6869     if (N->getOpcode() == ISD::SHL) {
6870       SDLoc DL(N);
6871       SDValue NewOp0 =
6872           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6873       SDValue NewOp1 =
6874           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6875       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6876       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6877                                    DAG.getValueType(MVT::i32));
6878       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6879     }
6880 
6881     break;
6882   case ISD::ROTL:
6883   case ISD::ROTR:
6884     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6885            "Unexpected custom legalisation");
6886     Results.push_back(customLegalizeToWOp(N, DAG));
6887     break;
6888   case ISD::CTTZ:
6889   case ISD::CTTZ_ZERO_UNDEF:
6890   case ISD::CTLZ:
6891   case ISD::CTLZ_ZERO_UNDEF: {
6892     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6893            "Unexpected custom legalisation");
6894 
6895     SDValue NewOp0 =
6896         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6897     bool IsCTZ =
6898         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6899     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6900     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6901     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6902     return;
6903   }
6904   case ISD::SDIV:
6905   case ISD::UDIV:
6906   case ISD::UREM: {
6907     MVT VT = N->getSimpleValueType(0);
6908     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6909            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6910            "Unexpected custom legalisation");
6911     // Don't promote division/remainder by constant since we should expand those
6912     // to multiply by magic constant.
6913     // FIXME: What if the expansion is disabled for minsize.
6914     if (N->getOperand(1).getOpcode() == ISD::Constant)
6915       return;
6916 
6917     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6918     // the upper 32 bits. For other types we need to sign or zero extend
6919     // based on the opcode.
6920     unsigned ExtOpc = ISD::ANY_EXTEND;
6921     if (VT != MVT::i32)
6922       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6923                                            : ISD::ZERO_EXTEND;
6924 
6925     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6926     break;
6927   }
6928   case ISD::UADDO:
6929   case ISD::USUBO: {
6930     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6931            "Unexpected custom legalisation");
6932     bool IsAdd = N->getOpcode() == ISD::UADDO;
6933     // Create an ADDW or SUBW.
6934     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6935     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6936     SDValue Res =
6937         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6938     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6939                       DAG.getValueType(MVT::i32));
6940 
6941     SDValue Overflow;
6942     if (IsAdd && isOneConstant(RHS)) {
6943       // Special case uaddo X, 1 overflowed if the addition result is 0.
6944       // The general case (X + C) < C is not necessarily beneficial. Although we
6945       // reduce the live range of X, we may introduce the materialization of
6946       // constant C, especially when the setcc result is used by branch. We have
6947       // no compare with constant and branch instructions.
6948       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6949                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6950     } else {
6951       // Sign extend the LHS and perform an unsigned compare with the ADDW
6952       // result. Since the inputs are sign extended from i32, this is equivalent
6953       // to comparing the lower 32 bits.
6954       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6955       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6956                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6957     }
6958 
6959     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6960     Results.push_back(Overflow);
6961     return;
6962   }
6963   case ISD::UADDSAT:
6964   case ISD::USUBSAT: {
6965     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6966            "Unexpected custom legalisation");
6967     if (Subtarget.hasStdExtZbb()) {
6968       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6969       // sign extend allows overflow of the lower 32 bits to be detected on
6970       // the promoted size.
6971       SDValue LHS =
6972           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6973       SDValue RHS =
6974           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6975       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6976       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6977       return;
6978     }
6979 
6980     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6981     // promotion for UADDO/USUBO.
6982     Results.push_back(expandAddSubSat(N, DAG));
6983     return;
6984   }
6985   case ISD::ABS: {
6986     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6987            "Unexpected custom legalisation");
6988           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6989 
6990     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6991 
6992     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6993 
6994     // Freeze the source so we can increase it's use count.
6995     Src = DAG.getFreeze(Src);
6996 
6997     // Copy sign bit to all bits using the sraiw pattern.
6998     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6999                                    DAG.getValueType(MVT::i32));
7000     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7001                            DAG.getConstant(31, DL, MVT::i64));
7002 
7003     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7004     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7005 
7006     // NOTE: The result is only required to be anyextended, but sext is
7007     // consistent with type legalization of sub.
7008     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7009                          DAG.getValueType(MVT::i32));
7010     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7011     return;
7012   }
7013   case ISD::BITCAST: {
7014     EVT VT = N->getValueType(0);
7015     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7016     SDValue Op0 = N->getOperand(0);
7017     EVT Op0VT = Op0.getValueType();
7018     MVT XLenVT = Subtarget.getXLenVT();
7019     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7020       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7021       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7022     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7023                Subtarget.hasStdExtF()) {
7024       SDValue FPConv =
7025           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7026       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7027     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7028                isTypeLegal(Op0VT)) {
7029       // Custom-legalize bitcasts from fixed-length vector types to illegal
7030       // scalar types in order to improve codegen. Bitcast the vector to a
7031       // one-element vector type whose element type is the same as the result
7032       // type, and extract the first element.
7033       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7034       if (isTypeLegal(BVT)) {
7035         SDValue BVec = DAG.getBitcast(BVT, Op0);
7036         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7037                                       DAG.getConstant(0, DL, XLenVT)));
7038       }
7039     }
7040     break;
7041   }
7042   case RISCVISD::GREV:
7043   case RISCVISD::GORC:
7044   case RISCVISD::SHFL: {
7045     MVT VT = N->getSimpleValueType(0);
7046     MVT XLenVT = Subtarget.getXLenVT();
7047     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7048            "Unexpected custom legalisation");
7049     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7050     assert((Subtarget.hasStdExtZbp() ||
7051             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7052              N->getConstantOperandVal(1) == 7)) &&
7053            "Unexpected extension");
7054     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7055     SDValue NewOp1 =
7056         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7057     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7058     // ReplaceNodeResults requires we maintain the same type for the return
7059     // value.
7060     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7061     break;
7062   }
7063   case ISD::BSWAP:
7064   case ISD::BITREVERSE: {
7065     MVT VT = N->getSimpleValueType(0);
7066     MVT XLenVT = Subtarget.getXLenVT();
7067     assert((VT == MVT::i8 || VT == MVT::i16 ||
7068             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7069            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7070     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7071     unsigned Imm = VT.getSizeInBits() - 1;
7072     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7073     if (N->getOpcode() == ISD::BSWAP)
7074       Imm &= ~0x7U;
7075     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7076                                 DAG.getConstant(Imm, DL, XLenVT));
7077     // ReplaceNodeResults requires we maintain the same type for the return
7078     // value.
7079     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7080     break;
7081   }
7082   case ISD::FSHL:
7083   case ISD::FSHR: {
7084     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7085            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7086     SDValue NewOp0 =
7087         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7088     SDValue NewOp1 =
7089         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7090     SDValue NewShAmt =
7091         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7092     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7093     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7094     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7095                            DAG.getConstant(0x1f, DL, MVT::i64));
7096     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7097     // instruction use different orders. fshl will return its first operand for
7098     // shift of zero, fshr will return its second operand. fsl and fsr both
7099     // return rs1 so the ISD nodes need to have different operand orders.
7100     // Shift amount is in rs2.
7101     unsigned Opc = RISCVISD::FSLW;
7102     if (N->getOpcode() == ISD::FSHR) {
7103       std::swap(NewOp0, NewOp1);
7104       Opc = RISCVISD::FSRW;
7105     }
7106     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7107     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7108     break;
7109   }
7110   case ISD::EXTRACT_VECTOR_ELT: {
7111     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7112     // type is illegal (currently only vXi64 RV32).
7113     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7114     // transferred to the destination register. We issue two of these from the
7115     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7116     // first element.
7117     SDValue Vec = N->getOperand(0);
7118     SDValue Idx = N->getOperand(1);
7119 
7120     // The vector type hasn't been legalized yet so we can't issue target
7121     // specific nodes if it needs legalization.
7122     // FIXME: We would manually legalize if it's important.
7123     if (!isTypeLegal(Vec.getValueType()))
7124       return;
7125 
7126     MVT VecVT = Vec.getSimpleValueType();
7127 
7128     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7129            VecVT.getVectorElementType() == MVT::i64 &&
7130            "Unexpected EXTRACT_VECTOR_ELT legalization");
7131 
7132     // If this is a fixed vector, we need to convert it to a scalable vector.
7133     MVT ContainerVT = VecVT;
7134     if (VecVT.isFixedLengthVector()) {
7135       ContainerVT = getContainerForFixedLengthVector(VecVT);
7136       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7137     }
7138 
7139     MVT XLenVT = Subtarget.getXLenVT();
7140 
7141     // Use a VL of 1 to avoid processing more elements than we need.
7142     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7143     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7144 
7145     // Unless the index is known to be 0, we must slide the vector down to get
7146     // the desired element into index 0.
7147     if (!isNullConstant(Idx)) {
7148       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7149                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7150     }
7151 
7152     // Extract the lower XLEN bits of the correct vector element.
7153     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7154 
7155     // To extract the upper XLEN bits of the vector element, shift the first
7156     // element right by 32 bits and re-extract the lower XLEN bits.
7157     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7158                                      DAG.getUNDEF(ContainerVT),
7159                                      DAG.getConstant(32, DL, XLenVT), VL);
7160     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7161                                  ThirtyTwoV, Mask, VL);
7162 
7163     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7164 
7165     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7166     break;
7167   }
7168   case ISD::INTRINSIC_WO_CHAIN: {
7169     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7170     switch (IntNo) {
7171     default:
7172       llvm_unreachable(
7173           "Don't know how to custom type legalize this intrinsic!");
7174     case Intrinsic::riscv_grev:
7175     case Intrinsic::riscv_gorc: {
7176       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7177              "Unexpected custom legalisation");
7178       SDValue NewOp1 =
7179           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7180       SDValue NewOp2 =
7181           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7182       unsigned Opc =
7183           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7184       // If the control is a constant, promote the node by clearing any extra
7185       // bits bits in the control. isel will form greviw/gorciw if the result is
7186       // sign extended.
7187       if (isa<ConstantSDNode>(NewOp2)) {
7188         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7189                              DAG.getConstant(0x1f, DL, MVT::i64));
7190         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7191       }
7192       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7193       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7194       break;
7195     }
7196     case Intrinsic::riscv_bcompress:
7197     case Intrinsic::riscv_bdecompress:
7198     case Intrinsic::riscv_bfp:
7199     case Intrinsic::riscv_fsl:
7200     case Intrinsic::riscv_fsr: {
7201       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7202              "Unexpected custom legalisation");
7203       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7204       break;
7205     }
7206     case Intrinsic::riscv_orc_b: {
7207       // Lower to the GORCI encoding for orc.b with the operand extended.
7208       SDValue NewOp =
7209           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7210       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7211                                 DAG.getConstant(7, DL, MVT::i64));
7212       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7213       return;
7214     }
7215     case Intrinsic::riscv_shfl:
7216     case Intrinsic::riscv_unshfl: {
7217       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7218              "Unexpected custom legalisation");
7219       SDValue NewOp1 =
7220           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7221       SDValue NewOp2 =
7222           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7223       unsigned Opc =
7224           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7225       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7226       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7227       // will be shuffled the same way as the lower 32 bit half, but the two
7228       // halves won't cross.
7229       if (isa<ConstantSDNode>(NewOp2)) {
7230         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7231                              DAG.getConstant(0xf, DL, MVT::i64));
7232         Opc =
7233             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7234       }
7235       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7236       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7237       break;
7238     }
7239     case Intrinsic::riscv_vmv_x_s: {
7240       EVT VT = N->getValueType(0);
7241       MVT XLenVT = Subtarget.getXLenVT();
7242       if (VT.bitsLT(XLenVT)) {
7243         // Simple case just extract using vmv.x.s and truncate.
7244         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7245                                       Subtarget.getXLenVT(), N->getOperand(1));
7246         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7247         return;
7248       }
7249 
7250       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7251              "Unexpected custom legalization");
7252 
7253       // We need to do the move in two steps.
7254       SDValue Vec = N->getOperand(1);
7255       MVT VecVT = Vec.getSimpleValueType();
7256 
7257       // First extract the lower XLEN bits of the element.
7258       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7259 
7260       // To extract the upper XLEN bits of the vector element, shift the first
7261       // element right by 32 bits and re-extract the lower XLEN bits.
7262       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7263       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7264 
7265       SDValue ThirtyTwoV =
7266           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7267                       DAG.getConstant(32, DL, XLenVT), VL);
7268       SDValue LShr32 =
7269           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7270       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7271 
7272       Results.push_back(
7273           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7274       break;
7275     }
7276     }
7277     break;
7278   }
7279   case ISD::VECREDUCE_ADD:
7280   case ISD::VECREDUCE_AND:
7281   case ISD::VECREDUCE_OR:
7282   case ISD::VECREDUCE_XOR:
7283   case ISD::VECREDUCE_SMAX:
7284   case ISD::VECREDUCE_UMAX:
7285   case ISD::VECREDUCE_SMIN:
7286   case ISD::VECREDUCE_UMIN:
7287     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7288       Results.push_back(V);
7289     break;
7290   case ISD::VP_REDUCE_ADD:
7291   case ISD::VP_REDUCE_AND:
7292   case ISD::VP_REDUCE_OR:
7293   case ISD::VP_REDUCE_XOR:
7294   case ISD::VP_REDUCE_SMAX:
7295   case ISD::VP_REDUCE_UMAX:
7296   case ISD::VP_REDUCE_SMIN:
7297   case ISD::VP_REDUCE_UMIN:
7298     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7299       Results.push_back(V);
7300     break;
7301   case ISD::FLT_ROUNDS_: {
7302     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7303     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7304     Results.push_back(Res.getValue(0));
7305     Results.push_back(Res.getValue(1));
7306     break;
7307   }
7308   }
7309 }
7310 
7311 // A structure to hold one of the bit-manipulation patterns below. Together, a
7312 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7313 //   (or (and (shl x, 1), 0xAAAAAAAA),
7314 //       (and (srl x, 1), 0x55555555))
7315 struct RISCVBitmanipPat {
7316   SDValue Op;
7317   unsigned ShAmt;
7318   bool IsSHL;
7319 
7320   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7321     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7322   }
7323 };
7324 
7325 // Matches patterns of the form
7326 //   (and (shl x, C2), (C1 << C2))
7327 //   (and (srl x, C2), C1)
7328 //   (shl (and x, C1), C2)
7329 //   (srl (and x, (C1 << C2)), C2)
7330 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7331 // The expected masks for each shift amount are specified in BitmanipMasks where
7332 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7333 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7334 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7335 // XLen is 64.
7336 static Optional<RISCVBitmanipPat>
7337 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7338   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7339          "Unexpected number of masks");
7340   Optional<uint64_t> Mask;
7341   // Optionally consume a mask around the shift operation.
7342   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7343     Mask = Op.getConstantOperandVal(1);
7344     Op = Op.getOperand(0);
7345   }
7346   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7347     return None;
7348   bool IsSHL = Op.getOpcode() == ISD::SHL;
7349 
7350   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7351     return None;
7352   uint64_t ShAmt = Op.getConstantOperandVal(1);
7353 
7354   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7355   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7356     return None;
7357   // If we don't have enough masks for 64 bit, then we must be trying to
7358   // match SHFL so we're only allowed to shift 1/4 of the width.
7359   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7360     return None;
7361 
7362   SDValue Src = Op.getOperand(0);
7363 
7364   // The expected mask is shifted left when the AND is found around SHL
7365   // patterns.
7366   //   ((x >> 1) & 0x55555555)
7367   //   ((x << 1) & 0xAAAAAAAA)
7368   bool SHLExpMask = IsSHL;
7369 
7370   if (!Mask) {
7371     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7372     // the mask is all ones: consume that now.
7373     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7374       Mask = Src.getConstantOperandVal(1);
7375       Src = Src.getOperand(0);
7376       // The expected mask is now in fact shifted left for SRL, so reverse the
7377       // decision.
7378       //   ((x & 0xAAAAAAAA) >> 1)
7379       //   ((x & 0x55555555) << 1)
7380       SHLExpMask = !SHLExpMask;
7381     } else {
7382       // Use a default shifted mask of all-ones if there's no AND, truncated
7383       // down to the expected width. This simplifies the logic later on.
7384       Mask = maskTrailingOnes<uint64_t>(Width);
7385       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7386     }
7387   }
7388 
7389   unsigned MaskIdx = Log2_32(ShAmt);
7390   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7391 
7392   if (SHLExpMask)
7393     ExpMask <<= ShAmt;
7394 
7395   if (Mask != ExpMask)
7396     return None;
7397 
7398   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7399 }
7400 
7401 // Matches any of the following bit-manipulation patterns:
7402 //   (and (shl x, 1), (0x55555555 << 1))
7403 //   (and (srl x, 1), 0x55555555)
7404 //   (shl (and x, 0x55555555), 1)
7405 //   (srl (and x, (0x55555555 << 1)), 1)
7406 // where the shift amount and mask may vary thus:
7407 //   [1]  = 0x55555555 / 0xAAAAAAAA
7408 //   [2]  = 0x33333333 / 0xCCCCCCCC
7409 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7410 //   [8]  = 0x00FF00FF / 0xFF00FF00
7411 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7412 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7413 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7414   // These are the unshifted masks which we use to match bit-manipulation
7415   // patterns. They may be shifted left in certain circumstances.
7416   static const uint64_t BitmanipMasks[] = {
7417       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7418       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7419 
7420   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7421 }
7422 
7423 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7424 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7425   auto BinOpToRVVReduce = [](unsigned Opc) {
7426     switch (Opc) {
7427     default:
7428       llvm_unreachable("Unhandled binary to transfrom reduction");
7429     case ISD::ADD:
7430       return RISCVISD::VECREDUCE_ADD_VL;
7431     case ISD::UMAX:
7432       return RISCVISD::VECREDUCE_UMAX_VL;
7433     case ISD::SMAX:
7434       return RISCVISD::VECREDUCE_SMAX_VL;
7435     case ISD::UMIN:
7436       return RISCVISD::VECREDUCE_UMIN_VL;
7437     case ISD::SMIN:
7438       return RISCVISD::VECREDUCE_SMIN_VL;
7439     case ISD::AND:
7440       return RISCVISD::VECREDUCE_AND_VL;
7441     case ISD::OR:
7442       return RISCVISD::VECREDUCE_OR_VL;
7443     case ISD::XOR:
7444       return RISCVISD::VECREDUCE_XOR_VL;
7445     case ISD::FADD:
7446       return RISCVISD::VECREDUCE_FADD_VL;
7447     case ISD::FMAXNUM:
7448       return RISCVISD::VECREDUCE_FMAX_VL;
7449     case ISD::FMINNUM:
7450       return RISCVISD::VECREDUCE_FMIN_VL;
7451     }
7452   };
7453 
7454   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7455     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7456            isNullConstant(V.getOperand(1)) &&
7457            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7458   };
7459 
7460   unsigned Opc = N->getOpcode();
7461   unsigned ReduceIdx;
7462   if (IsReduction(N->getOperand(0), Opc))
7463     ReduceIdx = 0;
7464   else if (IsReduction(N->getOperand(1), Opc))
7465     ReduceIdx = 1;
7466   else
7467     return SDValue();
7468 
7469   // Skip if FADD disallows reassociation but the combiner needs.
7470   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7471     return SDValue();
7472 
7473   SDValue Extract = N->getOperand(ReduceIdx);
7474   SDValue Reduce = Extract.getOperand(0);
7475   if (!Reduce.hasOneUse())
7476     return SDValue();
7477 
7478   SDValue ScalarV = Reduce.getOperand(2);
7479 
7480   // Make sure that ScalarV is a splat with VL=1.
7481   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7482       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7483       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7484     return SDValue();
7485 
7486   if (!isOneConstant(ScalarV.getOperand(2)))
7487     return SDValue();
7488 
7489   // TODO: Deal with value other than neutral element.
7490   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7491     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7492         isNullFPConstant(V))
7493       return true;
7494     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7495                                  N->getFlags()) == V;
7496   };
7497 
7498   // Check the scalar of ScalarV is neutral element
7499   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7500     return SDValue();
7501 
7502   if (!ScalarV.hasOneUse())
7503     return SDValue();
7504 
7505   EVT SplatVT = ScalarV.getValueType();
7506   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7507   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7508   if (SplatVT.isInteger()) {
7509     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7510     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7511       SplatOpc = RISCVISD::VMV_S_X_VL;
7512     else
7513       SplatOpc = RISCVISD::VMV_V_X_VL;
7514   }
7515 
7516   SDValue NewScalarV =
7517       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7518                   ScalarV.getOperand(2));
7519   SDValue NewReduce =
7520       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7521                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7522                   Reduce.getOperand(3), Reduce.getOperand(4));
7523   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7524                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7525 }
7526 
7527 // Match the following pattern as a GREVI(W) operation
7528 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7529 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7530                                const RISCVSubtarget &Subtarget) {
7531   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7532   EVT VT = Op.getValueType();
7533 
7534   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7535     auto LHS = matchGREVIPat(Op.getOperand(0));
7536     auto RHS = matchGREVIPat(Op.getOperand(1));
7537     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7538       SDLoc DL(Op);
7539       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7540                          DAG.getConstant(LHS->ShAmt, DL, VT));
7541     }
7542   }
7543   return SDValue();
7544 }
7545 
7546 // Matches any the following pattern as a GORCI(W) operation
7547 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7548 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7549 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7550 // Note that with the variant of 3.,
7551 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7552 // the inner pattern will first be matched as GREVI and then the outer
7553 // pattern will be matched to GORC via the first rule above.
7554 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7555 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7556                                const RISCVSubtarget &Subtarget) {
7557   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7558   EVT VT = Op.getValueType();
7559 
7560   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7561     SDLoc DL(Op);
7562     SDValue Op0 = Op.getOperand(0);
7563     SDValue Op1 = Op.getOperand(1);
7564 
7565     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7566       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7567           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7568           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7569         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7570       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7571       if ((Reverse.getOpcode() == ISD::ROTL ||
7572            Reverse.getOpcode() == ISD::ROTR) &&
7573           Reverse.getOperand(0) == X &&
7574           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7575         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7576         if (RotAmt == (VT.getSizeInBits() / 2))
7577           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7578                              DAG.getConstant(RotAmt, DL, VT));
7579       }
7580       return SDValue();
7581     };
7582 
7583     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7584     if (SDValue V = MatchOROfReverse(Op0, Op1))
7585       return V;
7586     if (SDValue V = MatchOROfReverse(Op1, Op0))
7587       return V;
7588 
7589     // OR is commutable so canonicalize its OR operand to the left
7590     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7591       std::swap(Op0, Op1);
7592     if (Op0.getOpcode() != ISD::OR)
7593       return SDValue();
7594     SDValue OrOp0 = Op0.getOperand(0);
7595     SDValue OrOp1 = Op0.getOperand(1);
7596     auto LHS = matchGREVIPat(OrOp0);
7597     // OR is commutable so swap the operands and try again: x might have been
7598     // on the left
7599     if (!LHS) {
7600       std::swap(OrOp0, OrOp1);
7601       LHS = matchGREVIPat(OrOp0);
7602     }
7603     auto RHS = matchGREVIPat(Op1);
7604     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7605       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7606                          DAG.getConstant(LHS->ShAmt, DL, VT));
7607     }
7608   }
7609   return SDValue();
7610 }
7611 
7612 // Matches any of the following bit-manipulation patterns:
7613 //   (and (shl x, 1), (0x22222222 << 1))
7614 //   (and (srl x, 1), 0x22222222)
7615 //   (shl (and x, 0x22222222), 1)
7616 //   (srl (and x, (0x22222222 << 1)), 1)
7617 // where the shift amount and mask may vary thus:
7618 //   [1]  = 0x22222222 / 0x44444444
7619 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7620 //   [4]  = 0x00F000F0 / 0x0F000F00
7621 //   [8]  = 0x0000FF00 / 0x00FF0000
7622 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7623 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7624   // These are the unshifted masks which we use to match bit-manipulation
7625   // patterns. They may be shifted left in certain circumstances.
7626   static const uint64_t BitmanipMasks[] = {
7627       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7628       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7629 
7630   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7631 }
7632 
7633 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7634 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7635                                const RISCVSubtarget &Subtarget) {
7636   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7637   EVT VT = Op.getValueType();
7638 
7639   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7640     return SDValue();
7641 
7642   SDValue Op0 = Op.getOperand(0);
7643   SDValue Op1 = Op.getOperand(1);
7644 
7645   // Or is commutable so canonicalize the second OR to the LHS.
7646   if (Op0.getOpcode() != ISD::OR)
7647     std::swap(Op0, Op1);
7648   if (Op0.getOpcode() != ISD::OR)
7649     return SDValue();
7650 
7651   // We found an inner OR, so our operands are the operands of the inner OR
7652   // and the other operand of the outer OR.
7653   SDValue A = Op0.getOperand(0);
7654   SDValue B = Op0.getOperand(1);
7655   SDValue C = Op1;
7656 
7657   auto Match1 = matchSHFLPat(A);
7658   auto Match2 = matchSHFLPat(B);
7659 
7660   // If neither matched, we failed.
7661   if (!Match1 && !Match2)
7662     return SDValue();
7663 
7664   // We had at least one match. if one failed, try the remaining C operand.
7665   if (!Match1) {
7666     std::swap(A, C);
7667     Match1 = matchSHFLPat(A);
7668     if (!Match1)
7669       return SDValue();
7670   } else if (!Match2) {
7671     std::swap(B, C);
7672     Match2 = matchSHFLPat(B);
7673     if (!Match2)
7674       return SDValue();
7675   }
7676   assert(Match1 && Match2);
7677 
7678   // Make sure our matches pair up.
7679   if (!Match1->formsPairWith(*Match2))
7680     return SDValue();
7681 
7682   // All the remains is to make sure C is an AND with the same input, that masks
7683   // out the bits that are being shuffled.
7684   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7685       C.getOperand(0) != Match1->Op)
7686     return SDValue();
7687 
7688   uint64_t Mask = C.getConstantOperandVal(1);
7689 
7690   static const uint64_t BitmanipMasks[] = {
7691       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7692       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7693   };
7694 
7695   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7696   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7697   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7698 
7699   if (Mask != ExpMask)
7700     return SDValue();
7701 
7702   SDLoc DL(Op);
7703   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7704                      DAG.getConstant(Match1->ShAmt, DL, VT));
7705 }
7706 
7707 // Optimize (add (shl x, c0), (shl y, c1)) ->
7708 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7709 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7710                                   const RISCVSubtarget &Subtarget) {
7711   // Perform this optimization only in the zba extension.
7712   if (!Subtarget.hasStdExtZba())
7713     return SDValue();
7714 
7715   // Skip for vector types and larger types.
7716   EVT VT = N->getValueType(0);
7717   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7718     return SDValue();
7719 
7720   // The two operand nodes must be SHL and have no other use.
7721   SDValue N0 = N->getOperand(0);
7722   SDValue N1 = N->getOperand(1);
7723   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7724       !N0->hasOneUse() || !N1->hasOneUse())
7725     return SDValue();
7726 
7727   // Check c0 and c1.
7728   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7729   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7730   if (!N0C || !N1C)
7731     return SDValue();
7732   int64_t C0 = N0C->getSExtValue();
7733   int64_t C1 = N1C->getSExtValue();
7734   if (C0 <= 0 || C1 <= 0)
7735     return SDValue();
7736 
7737   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7738   int64_t Bits = std::min(C0, C1);
7739   int64_t Diff = std::abs(C0 - C1);
7740   if (Diff != 1 && Diff != 2 && Diff != 3)
7741     return SDValue();
7742 
7743   // Build nodes.
7744   SDLoc DL(N);
7745   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7746   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7747   SDValue NA0 =
7748       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7749   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7750   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7751 }
7752 
7753 // Combine
7754 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7755 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7756 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7757 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7758 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7759 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7760 // The grev patterns represents BSWAP.
7761 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7762 // off the grev.
7763 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7764                                           const RISCVSubtarget &Subtarget) {
7765   bool IsWInstruction =
7766       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7767   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7768           IsWInstruction) &&
7769          "Unexpected opcode!");
7770   SDValue Src = N->getOperand(0);
7771   EVT VT = N->getValueType(0);
7772   SDLoc DL(N);
7773 
7774   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7775     return SDValue();
7776 
7777   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7778       !isa<ConstantSDNode>(Src.getOperand(1)))
7779     return SDValue();
7780 
7781   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7782   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7783 
7784   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7785   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7786   unsigned ShAmt1 = N->getConstantOperandVal(1);
7787   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7788   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7789     return SDValue();
7790 
7791   Src = Src.getOperand(0);
7792 
7793   // Toggle bit the MSB of the shift.
7794   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7795   if (CombinedShAmt == 0)
7796     return Src;
7797 
7798   SDValue Res = DAG.getNode(
7799       RISCVISD::GREV, DL, VT, Src,
7800       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7801   if (!IsWInstruction)
7802     return Res;
7803 
7804   // Sign extend the result to match the behavior of the rotate. This will be
7805   // selected to GREVIW in isel.
7806   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7807                      DAG.getValueType(MVT::i32));
7808 }
7809 
7810 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7811 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7812 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7813 // not undo itself, but they are redundant.
7814 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7815   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7816   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7817   SDValue Src = N->getOperand(0);
7818 
7819   if (Src.getOpcode() != N->getOpcode())
7820     return SDValue();
7821 
7822   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7823       !isa<ConstantSDNode>(Src.getOperand(1)))
7824     return SDValue();
7825 
7826   unsigned ShAmt1 = N->getConstantOperandVal(1);
7827   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7828   Src = Src.getOperand(0);
7829 
7830   unsigned CombinedShAmt;
7831   if (IsGORC)
7832     CombinedShAmt = ShAmt1 | ShAmt2;
7833   else
7834     CombinedShAmt = ShAmt1 ^ ShAmt2;
7835 
7836   if (CombinedShAmt == 0)
7837     return Src;
7838 
7839   SDLoc DL(N);
7840   return DAG.getNode(
7841       N->getOpcode(), DL, N->getValueType(0), Src,
7842       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7843 }
7844 
7845 // Combine a constant select operand into its use:
7846 //
7847 // (and (select cond, -1, c), x)
7848 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7849 // (or  (select cond, 0, c), x)
7850 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7851 // (xor (select cond, 0, c), x)
7852 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7853 // (add (select cond, 0, c), x)
7854 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7855 // (sub x, (select cond, 0, c))
7856 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7857 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7858                                    SelectionDAG &DAG, bool AllOnes) {
7859   EVT VT = N->getValueType(0);
7860 
7861   // Skip vectors.
7862   if (VT.isVector())
7863     return SDValue();
7864 
7865   if ((Slct.getOpcode() != ISD::SELECT &&
7866        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7867       !Slct.hasOneUse())
7868     return SDValue();
7869 
7870   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7871     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7872   };
7873 
7874   bool SwapSelectOps;
7875   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7876   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7877   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7878   SDValue NonConstantVal;
7879   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7880     SwapSelectOps = false;
7881     NonConstantVal = FalseVal;
7882   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7883     SwapSelectOps = true;
7884     NonConstantVal = TrueVal;
7885   } else
7886     return SDValue();
7887 
7888   // Slct is now know to be the desired identity constant when CC is true.
7889   TrueVal = OtherOp;
7890   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7891   // Unless SwapSelectOps says the condition should be false.
7892   if (SwapSelectOps)
7893     std::swap(TrueVal, FalseVal);
7894 
7895   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7896     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7897                        {Slct.getOperand(0), Slct.getOperand(1),
7898                         Slct.getOperand(2), TrueVal, FalseVal});
7899 
7900   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7901                      {Slct.getOperand(0), TrueVal, FalseVal});
7902 }
7903 
7904 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7905 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7906                                               bool AllOnes) {
7907   SDValue N0 = N->getOperand(0);
7908   SDValue N1 = N->getOperand(1);
7909   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7910     return Result;
7911   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7912     return Result;
7913   return SDValue();
7914 }
7915 
7916 // Transform (add (mul x, c0), c1) ->
7917 //           (add (mul (add x, c1/c0), c0), c1%c0).
7918 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7919 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7920 // to an infinite loop in DAGCombine if transformed.
7921 // Or transform (add (mul x, c0), c1) ->
7922 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7923 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7924 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7925 // lead to an infinite loop in DAGCombine if transformed.
7926 // Or transform (add (mul x, c0), c1) ->
7927 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7928 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7929 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7930 // lead to an infinite loop in DAGCombine if transformed.
7931 // Or transform (add (mul x, c0), c1) ->
7932 //              (mul (add x, c1/c0), c0).
7933 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7934 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7935                                      const RISCVSubtarget &Subtarget) {
7936   // Skip for vector types and larger types.
7937   EVT VT = N->getValueType(0);
7938   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7939     return SDValue();
7940   // The first operand node must be a MUL and has no other use.
7941   SDValue N0 = N->getOperand(0);
7942   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7943     return SDValue();
7944   // Check if c0 and c1 match above conditions.
7945   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7946   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7947   if (!N0C || !N1C)
7948     return SDValue();
7949   // If N0C has multiple uses it's possible one of the cases in
7950   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7951   // in an infinite loop.
7952   if (!N0C->hasOneUse())
7953     return SDValue();
7954   int64_t C0 = N0C->getSExtValue();
7955   int64_t C1 = N1C->getSExtValue();
7956   int64_t CA, CB;
7957   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7958     return SDValue();
7959   // Search for proper CA (non-zero) and CB that both are simm12.
7960   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7961       !isInt<12>(C0 * (C1 / C0))) {
7962     CA = C1 / C0;
7963     CB = C1 % C0;
7964   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7965              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7966     CA = C1 / C0 + 1;
7967     CB = C1 % C0 - C0;
7968   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7969              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7970     CA = C1 / C0 - 1;
7971     CB = C1 % C0 + C0;
7972   } else
7973     return SDValue();
7974   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7975   SDLoc DL(N);
7976   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7977                              DAG.getConstant(CA, DL, VT));
7978   SDValue New1 =
7979       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7980   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7981 }
7982 
7983 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7984                                  const RISCVSubtarget &Subtarget) {
7985   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7986     return V;
7987   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7988     return V;
7989   if (SDValue V = combineBinOpToReduce(N, DAG))
7990     return V;
7991   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7992   //      (select lhs, rhs, cc, x, (add x, y))
7993   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7994 }
7995 
7996 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7997   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7998   //      (select lhs, rhs, cc, x, (sub x, y))
7999   SDValue N0 = N->getOperand(0);
8000   SDValue N1 = N->getOperand(1);
8001   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8002 }
8003 
8004 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8005                                  const RISCVSubtarget &Subtarget) {
8006   SDValue N0 = N->getOperand(0);
8007   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8008   // extending X. This is safe since we only need the LSB after the shift and
8009   // shift amounts larger than 31 would produce poison. If we wait until
8010   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8011   // to use a BEXT instruction.
8012   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8013       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8014       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8015       N0.hasOneUse()) {
8016     SDLoc DL(N);
8017     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8018     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8019     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8020     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8021                               DAG.getConstant(1, DL, MVT::i64));
8022     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8023   }
8024 
8025   if (SDValue V = combineBinOpToReduce(N, DAG))
8026     return V;
8027 
8028   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8029   //      (select lhs, rhs, cc, x, (and x, y))
8030   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8031 }
8032 
8033 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8034                                 const RISCVSubtarget &Subtarget) {
8035   if (Subtarget.hasStdExtZbp()) {
8036     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8037       return GREV;
8038     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8039       return GORC;
8040     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8041       return SHFL;
8042   }
8043 
8044   if (SDValue V = combineBinOpToReduce(N, DAG))
8045     return V;
8046   // fold (or (select cond, 0, y), x) ->
8047   //      (select cond, x, (or x, y))
8048   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8049 }
8050 
8051 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8052   SDValue N0 = N->getOperand(0);
8053   SDValue N1 = N->getOperand(1);
8054 
8055   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8056   // NOTE: Assumes ROL being legal means ROLW is legal.
8057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8058   if (N0.getOpcode() == RISCVISD::SLLW &&
8059       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8060       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8061     SDLoc DL(N);
8062     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8063                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8064   }
8065 
8066   if (SDValue V = combineBinOpToReduce(N, DAG))
8067     return V;
8068   // fold (xor (select cond, 0, y), x) ->
8069   //      (select cond, x, (xor x, y))
8070   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8071 }
8072 
8073 static SDValue
8074 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8075                                 const RISCVSubtarget &Subtarget) {
8076   SDValue Src = N->getOperand(0);
8077   EVT VT = N->getValueType(0);
8078 
8079   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8080   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8081       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8082     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8083                        Src.getOperand(0));
8084 
8085   // Fold (i64 (sext_inreg (abs X), i32)) ->
8086   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8087   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8088   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8089   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8090   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8091   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8092   // may get combined into an earlier operation so we need to use
8093   // ComputeNumSignBits.
8094   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8095   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8096   // we can't assume that X has 33 sign bits. We must check.
8097   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8098       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8099       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8100       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8101     SDLoc DL(N);
8102     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8103     SDValue Neg =
8104         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8105     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8106                       DAG.getValueType(MVT::i32));
8107     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8108   }
8109 
8110   return SDValue();
8111 }
8112 
8113 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8114 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8115 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8116                                              bool Commute = false) {
8117   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8118           N->getOpcode() == RISCVISD::SUB_VL) &&
8119          "Unexpected opcode");
8120   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8121   SDValue Op0 = N->getOperand(0);
8122   SDValue Op1 = N->getOperand(1);
8123   if (Commute)
8124     std::swap(Op0, Op1);
8125 
8126   MVT VT = N->getSimpleValueType(0);
8127 
8128   // Determine the narrow size for a widening add/sub.
8129   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8130   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8131                                   VT.getVectorElementCount());
8132 
8133   SDValue Mask = N->getOperand(2);
8134   SDValue VL = N->getOperand(3);
8135 
8136   SDLoc DL(N);
8137 
8138   // If the RHS is a sext or zext, we can form a widening op.
8139   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8140        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8141       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8142     unsigned ExtOpc = Op1.getOpcode();
8143     Op1 = Op1.getOperand(0);
8144     // Re-introduce narrower extends if needed.
8145     if (Op1.getValueType() != NarrowVT)
8146       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8147 
8148     unsigned WOpc;
8149     if (ExtOpc == RISCVISD::VSEXT_VL)
8150       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8151     else
8152       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8153 
8154     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8155   }
8156 
8157   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8158   // sext/zext?
8159 
8160   return SDValue();
8161 }
8162 
8163 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8164 // vwsub(u).vv/vx.
8165 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8166   SDValue Op0 = N->getOperand(0);
8167   SDValue Op1 = N->getOperand(1);
8168   SDValue Mask = N->getOperand(2);
8169   SDValue VL = N->getOperand(3);
8170 
8171   MVT VT = N->getSimpleValueType(0);
8172   MVT NarrowVT = Op1.getSimpleValueType();
8173   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8174 
8175   unsigned VOpc;
8176   switch (N->getOpcode()) {
8177   default: llvm_unreachable("Unexpected opcode");
8178   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8179   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8180   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8181   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8182   }
8183 
8184   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8185                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8186 
8187   SDLoc DL(N);
8188 
8189   // If the LHS is a sext or zext, we can narrow this op to the same size as
8190   // the RHS.
8191   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8192        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8193       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8194     unsigned ExtOpc = Op0.getOpcode();
8195     Op0 = Op0.getOperand(0);
8196     // Re-introduce narrower extends if needed.
8197     if (Op0.getValueType() != NarrowVT)
8198       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8199     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8200   }
8201 
8202   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8203                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8204 
8205   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8206   // to commute and use a vwadd(u).vx instead.
8207   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8208       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8209     Op0 = Op0.getOperand(1);
8210 
8211     // See if have enough sign bits or zero bits in the scalar to use a
8212     // widening add/sub by splatting to smaller element size.
8213     unsigned EltBits = VT.getScalarSizeInBits();
8214     unsigned ScalarBits = Op0.getValueSizeInBits();
8215     // Make sure we're getting all element bits from the scalar register.
8216     // FIXME: Support implicit sign extension of vmv.v.x?
8217     if (ScalarBits < EltBits)
8218       return SDValue();
8219 
8220     if (IsSigned) {
8221       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8222         return SDValue();
8223     } else {
8224       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8225       if (!DAG.MaskedValueIsZero(Op0, Mask))
8226         return SDValue();
8227     }
8228 
8229     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8230                       DAG.getUNDEF(NarrowVT), Op0, VL);
8231     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8232   }
8233 
8234   return SDValue();
8235 }
8236 
8237 // Try to form VWMUL, VWMULU or VWMULSU.
8238 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8239 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8240                                        bool Commute) {
8241   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8242   SDValue Op0 = N->getOperand(0);
8243   SDValue Op1 = N->getOperand(1);
8244   if (Commute)
8245     std::swap(Op0, Op1);
8246 
8247   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8248   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8249   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8250   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8251     return SDValue();
8252 
8253   SDValue Mask = N->getOperand(2);
8254   SDValue VL = N->getOperand(3);
8255 
8256   // Make sure the mask and VL match.
8257   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8258     return SDValue();
8259 
8260   MVT VT = N->getSimpleValueType(0);
8261 
8262   // Determine the narrow size for a widening multiply.
8263   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8264   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8265                                   VT.getVectorElementCount());
8266 
8267   SDLoc DL(N);
8268 
8269   // See if the other operand is the same opcode.
8270   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8271     if (!Op1.hasOneUse())
8272       return SDValue();
8273 
8274     // Make sure the mask and VL match.
8275     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8276       return SDValue();
8277 
8278     Op1 = Op1.getOperand(0);
8279   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8280     // The operand is a splat of a scalar.
8281 
8282     // The pasthru must be undef for tail agnostic
8283     if (!Op1.getOperand(0).isUndef())
8284       return SDValue();
8285     // The VL must be the same.
8286     if (Op1.getOperand(2) != VL)
8287       return SDValue();
8288 
8289     // Get the scalar value.
8290     Op1 = Op1.getOperand(1);
8291 
8292     // See if have enough sign bits or zero bits in the scalar to use a
8293     // widening multiply by splatting to smaller element size.
8294     unsigned EltBits = VT.getScalarSizeInBits();
8295     unsigned ScalarBits = Op1.getValueSizeInBits();
8296     // Make sure we're getting all element bits from the scalar register.
8297     // FIXME: Support implicit sign extension of vmv.v.x?
8298     if (ScalarBits < EltBits)
8299       return SDValue();
8300 
8301     // If the LHS is a sign extend, try to use vwmul.
8302     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8303       // Can use vwmul.
8304     } else {
8305       // Otherwise try to use vwmulu or vwmulsu.
8306       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8307       if (DAG.MaskedValueIsZero(Op1, Mask))
8308         IsVWMULSU = IsSignExt;
8309       else
8310         return SDValue();
8311     }
8312 
8313     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8314                       DAG.getUNDEF(NarrowVT), Op1, VL);
8315   } else
8316     return SDValue();
8317 
8318   Op0 = Op0.getOperand(0);
8319 
8320   // Re-introduce narrower extends if needed.
8321   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8322   if (Op0.getValueType() != NarrowVT)
8323     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8324   // vwmulsu requires second operand to be zero extended.
8325   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8326   if (Op1.getValueType() != NarrowVT)
8327     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8328 
8329   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8330   if (!IsVWMULSU)
8331     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8332   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8333 }
8334 
8335 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8336   switch (Op.getOpcode()) {
8337   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8338   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8339   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8340   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8341   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8342   }
8343 
8344   return RISCVFPRndMode::Invalid;
8345 }
8346 
8347 // Fold
8348 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8349 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8350 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8351 //   (fp_to_int (fceil X))      -> fcvt X, rup
8352 //   (fp_to_int (fround X))     -> fcvt X, rmm
8353 static SDValue performFP_TO_INTCombine(SDNode *N,
8354                                        TargetLowering::DAGCombinerInfo &DCI,
8355                                        const RISCVSubtarget &Subtarget) {
8356   SelectionDAG &DAG = DCI.DAG;
8357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8358   MVT XLenVT = Subtarget.getXLenVT();
8359 
8360   // Only handle XLen or i32 types. Other types narrower than XLen will
8361   // eventually be legalized to XLenVT.
8362   EVT VT = N->getValueType(0);
8363   if (VT != MVT::i32 && VT != XLenVT)
8364     return SDValue();
8365 
8366   SDValue Src = N->getOperand(0);
8367 
8368   // Ensure the FP type is also legal.
8369   if (!TLI.isTypeLegal(Src.getValueType()))
8370     return SDValue();
8371 
8372   // Don't do this for f16 with Zfhmin and not Zfh.
8373   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8374     return SDValue();
8375 
8376   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8377   if (FRM == RISCVFPRndMode::Invalid)
8378     return SDValue();
8379 
8380   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8381 
8382   unsigned Opc;
8383   if (VT == XLenVT)
8384     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8385   else
8386     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8387 
8388   SDLoc DL(N);
8389   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8390                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8391   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8392 }
8393 
8394 // Fold
8395 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8396 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8397 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8398 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8399 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8400 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8401                                        TargetLowering::DAGCombinerInfo &DCI,
8402                                        const RISCVSubtarget &Subtarget) {
8403   SelectionDAG &DAG = DCI.DAG;
8404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8405   MVT XLenVT = Subtarget.getXLenVT();
8406 
8407   // Only handle XLen types. Other types narrower than XLen will eventually be
8408   // legalized to XLenVT.
8409   EVT DstVT = N->getValueType(0);
8410   if (DstVT != XLenVT)
8411     return SDValue();
8412 
8413   SDValue Src = N->getOperand(0);
8414 
8415   // Ensure the FP type is also legal.
8416   if (!TLI.isTypeLegal(Src.getValueType()))
8417     return SDValue();
8418 
8419   // Don't do this for f16 with Zfhmin and not Zfh.
8420   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8421     return SDValue();
8422 
8423   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8424 
8425   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8426   if (FRM == RISCVFPRndMode::Invalid)
8427     return SDValue();
8428 
8429   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8430 
8431   unsigned Opc;
8432   if (SatVT == DstVT)
8433     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8434   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8435     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8436   else
8437     return SDValue();
8438   // FIXME: Support other SatVTs by clamping before or after the conversion.
8439 
8440   Src = Src.getOperand(0);
8441 
8442   SDLoc DL(N);
8443   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8444                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8445 
8446   // RISCV FP-to-int conversions saturate to the destination register size, but
8447   // don't produce 0 for nan.
8448   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8449   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8450 }
8451 
8452 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8453 // smaller than XLenVT.
8454 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8455                                         const RISCVSubtarget &Subtarget) {
8456   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8457 
8458   SDValue Src = N->getOperand(0);
8459   if (Src.getOpcode() != ISD::BSWAP)
8460     return SDValue();
8461 
8462   EVT VT = N->getValueType(0);
8463   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8464       !isPowerOf2_32(VT.getSizeInBits()))
8465     return SDValue();
8466 
8467   SDLoc DL(N);
8468   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8469                      DAG.getConstant(7, DL, VT));
8470 }
8471 
8472 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8473                                                DAGCombinerInfo &DCI) const {
8474   SelectionDAG &DAG = DCI.DAG;
8475 
8476   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8477   // bits are demanded. N will be added to the Worklist if it was not deleted.
8478   // Caller should return SDValue(N, 0) if this returns true.
8479   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8480     SDValue Op = N->getOperand(OpNo);
8481     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8482     if (!SimplifyDemandedBits(Op, Mask, DCI))
8483       return false;
8484 
8485     if (N->getOpcode() != ISD::DELETED_NODE)
8486       DCI.AddToWorklist(N);
8487     return true;
8488   };
8489 
8490   switch (N->getOpcode()) {
8491   default:
8492     break;
8493   case RISCVISD::SplitF64: {
8494     SDValue Op0 = N->getOperand(0);
8495     // If the input to SplitF64 is just BuildPairF64 then the operation is
8496     // redundant. Instead, use BuildPairF64's operands directly.
8497     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8498       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8499 
8500     if (Op0->isUndef()) {
8501       SDValue Lo = DAG.getUNDEF(MVT::i32);
8502       SDValue Hi = DAG.getUNDEF(MVT::i32);
8503       return DCI.CombineTo(N, Lo, Hi);
8504     }
8505 
8506     SDLoc DL(N);
8507 
8508     // It's cheaper to materialise two 32-bit integers than to load a double
8509     // from the constant pool and transfer it to integer registers through the
8510     // stack.
8511     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8512       APInt V = C->getValueAPF().bitcastToAPInt();
8513       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8514       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8515       return DCI.CombineTo(N, Lo, Hi);
8516     }
8517 
8518     // This is a target-specific version of a DAGCombine performed in
8519     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8520     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8521     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8522     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8523         !Op0.getNode()->hasOneUse())
8524       break;
8525     SDValue NewSplitF64 =
8526         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8527                     Op0.getOperand(0));
8528     SDValue Lo = NewSplitF64.getValue(0);
8529     SDValue Hi = NewSplitF64.getValue(1);
8530     APInt SignBit = APInt::getSignMask(32);
8531     if (Op0.getOpcode() == ISD::FNEG) {
8532       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8533                                   DAG.getConstant(SignBit, DL, MVT::i32));
8534       return DCI.CombineTo(N, Lo, NewHi);
8535     }
8536     assert(Op0.getOpcode() == ISD::FABS);
8537     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8538                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8539     return DCI.CombineTo(N, Lo, NewHi);
8540   }
8541   case RISCVISD::SLLW:
8542   case RISCVISD::SRAW:
8543   case RISCVISD::SRLW: {
8544     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8545     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8546         SimplifyDemandedLowBitsHelper(1, 5))
8547       return SDValue(N, 0);
8548 
8549     break;
8550   }
8551   case ISD::ROTR:
8552   case ISD::ROTL:
8553   case RISCVISD::RORW:
8554   case RISCVISD::ROLW: {
8555     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8556       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8557       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8558           SimplifyDemandedLowBitsHelper(1, 5))
8559         return SDValue(N, 0);
8560     }
8561 
8562     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8563   }
8564   case RISCVISD::CLZW:
8565   case RISCVISD::CTZW: {
8566     // Only the lower 32 bits of the first operand are read
8567     if (SimplifyDemandedLowBitsHelper(0, 32))
8568       return SDValue(N, 0);
8569     break;
8570   }
8571   case RISCVISD::GREV:
8572   case RISCVISD::GORC: {
8573     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8574     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8575     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8576     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8577       return SDValue(N, 0);
8578 
8579     return combineGREVI_GORCI(N, DAG);
8580   }
8581   case RISCVISD::GREVW:
8582   case RISCVISD::GORCW: {
8583     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8584     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8585         SimplifyDemandedLowBitsHelper(1, 5))
8586       return SDValue(N, 0);
8587 
8588     break;
8589   }
8590   case RISCVISD::SHFL:
8591   case RISCVISD::UNSHFL: {
8592     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8593     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8594     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8595     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8596       return SDValue(N, 0);
8597 
8598     break;
8599   }
8600   case RISCVISD::SHFLW:
8601   case RISCVISD::UNSHFLW: {
8602     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8603     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8604         SimplifyDemandedLowBitsHelper(1, 4))
8605       return SDValue(N, 0);
8606 
8607     break;
8608   }
8609   case RISCVISD::BCOMPRESSW:
8610   case RISCVISD::BDECOMPRESSW: {
8611     // Only the lower 32 bits of LHS and RHS are read.
8612     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8613         SimplifyDemandedLowBitsHelper(1, 32))
8614       return SDValue(N, 0);
8615 
8616     break;
8617   }
8618   case RISCVISD::FSR:
8619   case RISCVISD::FSL:
8620   case RISCVISD::FSRW:
8621   case RISCVISD::FSLW: {
8622     bool IsWInstruction =
8623         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8624     unsigned BitWidth =
8625         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8626     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8627     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8628     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8629       return SDValue(N, 0);
8630 
8631     break;
8632   }
8633   case RISCVISD::FMV_X_ANYEXTH:
8634   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8635     SDLoc DL(N);
8636     SDValue Op0 = N->getOperand(0);
8637     MVT VT = N->getSimpleValueType(0);
8638     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8639     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8640     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8641     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8642          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8643         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8644          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8645       assert(Op0.getOperand(0).getValueType() == VT &&
8646              "Unexpected value type!");
8647       return Op0.getOperand(0);
8648     }
8649 
8650     // This is a target-specific version of a DAGCombine performed in
8651     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8652     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8653     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8654     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8655         !Op0.getNode()->hasOneUse())
8656       break;
8657     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8658     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8659     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8660     if (Op0.getOpcode() == ISD::FNEG)
8661       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8662                          DAG.getConstant(SignBit, DL, VT));
8663 
8664     assert(Op0.getOpcode() == ISD::FABS);
8665     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8666                        DAG.getConstant(~SignBit, DL, VT));
8667   }
8668   case ISD::ADD:
8669     return performADDCombine(N, DAG, Subtarget);
8670   case ISD::SUB:
8671     return performSUBCombine(N, DAG);
8672   case ISD::AND:
8673     return performANDCombine(N, DAG, Subtarget);
8674   case ISD::OR:
8675     return performORCombine(N, DAG, Subtarget);
8676   case ISD::XOR:
8677     return performXORCombine(N, DAG);
8678   case ISD::FADD:
8679   case ISD::UMAX:
8680   case ISD::UMIN:
8681   case ISD::SMAX:
8682   case ISD::SMIN:
8683   case ISD::FMAXNUM:
8684   case ISD::FMINNUM:
8685     return combineBinOpToReduce(N, DAG);
8686   case ISD::SIGN_EXTEND_INREG:
8687     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8688   case ISD::ZERO_EXTEND:
8689     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8690     // type legalization. This is safe because fp_to_uint produces poison if
8691     // it overflows.
8692     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8693       SDValue Src = N->getOperand(0);
8694       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8695           isTypeLegal(Src.getOperand(0).getValueType()))
8696         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8697                            Src.getOperand(0));
8698       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8699           isTypeLegal(Src.getOperand(1).getValueType())) {
8700         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8701         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8702                                   Src.getOperand(0), Src.getOperand(1));
8703         DCI.CombineTo(N, Res);
8704         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8705         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8706         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8707       }
8708     }
8709     return SDValue();
8710   case RISCVISD::SELECT_CC: {
8711     // Transform
8712     SDValue LHS = N->getOperand(0);
8713     SDValue RHS = N->getOperand(1);
8714     SDValue TrueV = N->getOperand(3);
8715     SDValue FalseV = N->getOperand(4);
8716 
8717     // If the True and False values are the same, we don't need a select_cc.
8718     if (TrueV == FalseV)
8719       return TrueV;
8720 
8721     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8722     if (!ISD::isIntEqualitySetCC(CCVal))
8723       break;
8724 
8725     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8726     //      (select_cc X, Y, lt, trueV, falseV)
8727     // Sometimes the setcc is introduced after select_cc has been formed.
8728     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8729         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8730       // If we're looking for eq 0 instead of ne 0, we need to invert the
8731       // condition.
8732       bool Invert = CCVal == ISD::SETEQ;
8733       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8734       if (Invert)
8735         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8736 
8737       SDLoc DL(N);
8738       RHS = LHS.getOperand(1);
8739       LHS = LHS.getOperand(0);
8740       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8741 
8742       SDValue TargetCC = DAG.getCondCode(CCVal);
8743       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8744                          {LHS, RHS, TargetCC, TrueV, FalseV});
8745     }
8746 
8747     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8748     //      (select_cc X, Y, eq/ne, trueV, falseV)
8749     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8750       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8751                          {LHS.getOperand(0), LHS.getOperand(1),
8752                           N->getOperand(2), TrueV, FalseV});
8753     // (select_cc X, 1, setne, trueV, falseV) ->
8754     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8755     // This can occur when legalizing some floating point comparisons.
8756     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8757     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8758       SDLoc DL(N);
8759       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8760       SDValue TargetCC = DAG.getCondCode(CCVal);
8761       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8762       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8763                          {LHS, RHS, TargetCC, TrueV, FalseV});
8764     }
8765 
8766     break;
8767   }
8768   case RISCVISD::BR_CC: {
8769     SDValue LHS = N->getOperand(1);
8770     SDValue RHS = N->getOperand(2);
8771     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8772     if (!ISD::isIntEqualitySetCC(CCVal))
8773       break;
8774 
8775     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8776     //      (br_cc X, Y, lt, dest)
8777     // Sometimes the setcc is introduced after br_cc has been formed.
8778     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8779         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8780       // If we're looking for eq 0 instead of ne 0, we need to invert the
8781       // condition.
8782       bool Invert = CCVal == ISD::SETEQ;
8783       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8784       if (Invert)
8785         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8786 
8787       SDLoc DL(N);
8788       RHS = LHS.getOperand(1);
8789       LHS = LHS.getOperand(0);
8790       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8791 
8792       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8793                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8794                          N->getOperand(4));
8795     }
8796 
8797     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8798     //      (br_cc X, Y, eq/ne, trueV, falseV)
8799     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8800       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8801                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8802                          N->getOperand(3), N->getOperand(4));
8803 
8804     // (br_cc X, 1, setne, br_cc) ->
8805     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8806     // This can occur when legalizing some floating point comparisons.
8807     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8808     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8809       SDLoc DL(N);
8810       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8811       SDValue TargetCC = DAG.getCondCode(CCVal);
8812       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8813       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8814                          N->getOperand(0), LHS, RHS, TargetCC,
8815                          N->getOperand(4));
8816     }
8817     break;
8818   }
8819   case ISD::BITREVERSE:
8820     return performBITREVERSECombine(N, DAG, Subtarget);
8821   case ISD::FP_TO_SINT:
8822   case ISD::FP_TO_UINT:
8823     return performFP_TO_INTCombine(N, DCI, Subtarget);
8824   case ISD::FP_TO_SINT_SAT:
8825   case ISD::FP_TO_UINT_SAT:
8826     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8827   case ISD::FCOPYSIGN: {
8828     EVT VT = N->getValueType(0);
8829     if (!VT.isVector())
8830       break;
8831     // There is a form of VFSGNJ which injects the negated sign of its second
8832     // operand. Try and bubble any FNEG up after the extend/round to produce
8833     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8834     // TRUNC=1.
8835     SDValue In2 = N->getOperand(1);
8836     // Avoid cases where the extend/round has multiple uses, as duplicating
8837     // those is typically more expensive than removing a fneg.
8838     if (!In2.hasOneUse())
8839       break;
8840     if (In2.getOpcode() != ISD::FP_EXTEND &&
8841         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8842       break;
8843     In2 = In2.getOperand(0);
8844     if (In2.getOpcode() != ISD::FNEG)
8845       break;
8846     SDLoc DL(N);
8847     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8848     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8849                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8850   }
8851   case ISD::MGATHER:
8852   case ISD::MSCATTER:
8853   case ISD::VP_GATHER:
8854   case ISD::VP_SCATTER: {
8855     if (!DCI.isBeforeLegalize())
8856       break;
8857     SDValue Index, ScaleOp;
8858     bool IsIndexScaled = false;
8859     bool IsIndexSigned = false;
8860     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8861       Index = VPGSN->getIndex();
8862       ScaleOp = VPGSN->getScale();
8863       IsIndexScaled = VPGSN->isIndexScaled();
8864       IsIndexSigned = VPGSN->isIndexSigned();
8865     } else {
8866       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8867       Index = MGSN->getIndex();
8868       ScaleOp = MGSN->getScale();
8869       IsIndexScaled = MGSN->isIndexScaled();
8870       IsIndexSigned = MGSN->isIndexSigned();
8871     }
8872     EVT IndexVT = Index.getValueType();
8873     MVT XLenVT = Subtarget.getXLenVT();
8874     // RISCV indexed loads only support the "unsigned unscaled" addressing
8875     // mode, so anything else must be manually legalized.
8876     bool NeedsIdxLegalization =
8877         IsIndexScaled ||
8878         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8879     if (!NeedsIdxLegalization)
8880       break;
8881 
8882     SDLoc DL(N);
8883 
8884     // Any index legalization should first promote to XLenVT, so we don't lose
8885     // bits when scaling. This may create an illegal index type so we let
8886     // LLVM's legalization take care of the splitting.
8887     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8888     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8889       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8890       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8891                           DL, IndexVT, Index);
8892     }
8893 
8894     if (IsIndexScaled) {
8895       // Manually scale the indices.
8896       // TODO: Sanitize the scale operand here?
8897       // TODO: For VP nodes, should we use VP_SHL here?
8898       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8899       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8900       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8901       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8902       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
8903     }
8904 
8905     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
8906     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8907       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8908                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8909                               ScaleOp, VPGN->getMask(),
8910                               VPGN->getVectorLength()},
8911                              VPGN->getMemOperand(), NewIndexTy);
8912     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8913       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8914                               {VPSN->getChain(), VPSN->getValue(),
8915                                VPSN->getBasePtr(), Index, ScaleOp,
8916                                VPSN->getMask(), VPSN->getVectorLength()},
8917                               VPSN->getMemOperand(), NewIndexTy);
8918     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8919       return DAG.getMaskedGather(
8920           N->getVTList(), MGN->getMemoryVT(), DL,
8921           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8922            MGN->getBasePtr(), Index, ScaleOp},
8923           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8924     const auto *MSN = cast<MaskedScatterSDNode>(N);
8925     return DAG.getMaskedScatter(
8926         N->getVTList(), MSN->getMemoryVT(), DL,
8927         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8928          Index, ScaleOp},
8929         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8930   }
8931   case RISCVISD::SRA_VL:
8932   case RISCVISD::SRL_VL:
8933   case RISCVISD::SHL_VL: {
8934     SDValue ShAmt = N->getOperand(1);
8935     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8936       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8937       SDLoc DL(N);
8938       SDValue VL = N->getOperand(3);
8939       EVT VT = N->getValueType(0);
8940       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8941                           ShAmt.getOperand(1), VL);
8942       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8943                          N->getOperand(2), N->getOperand(3));
8944     }
8945     break;
8946   }
8947   case ISD::SRA:
8948   case ISD::SRL:
8949   case ISD::SHL: {
8950     SDValue ShAmt = N->getOperand(1);
8951     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8952       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8953       SDLoc DL(N);
8954       EVT VT = N->getValueType(0);
8955       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8956                           ShAmt.getOperand(1),
8957                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8958       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8959     }
8960     break;
8961   }
8962   case RISCVISD::ADD_VL:
8963     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8964       return V;
8965     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8966   case RISCVISD::SUB_VL:
8967     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8968   case RISCVISD::VWADD_W_VL:
8969   case RISCVISD::VWADDU_W_VL:
8970   case RISCVISD::VWSUB_W_VL:
8971   case RISCVISD::VWSUBU_W_VL:
8972     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8973   case RISCVISD::MUL_VL:
8974     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8975       return V;
8976     // Mul is commutative.
8977     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8978   case ISD::STORE: {
8979     auto *Store = cast<StoreSDNode>(N);
8980     SDValue Val = Store->getValue();
8981     // Combine store of vmv.x.s to vse with VL of 1.
8982     // FIXME: Support FP.
8983     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8984       SDValue Src = Val.getOperand(0);
8985       EVT VecVT = Src.getValueType();
8986       EVT MemVT = Store->getMemoryVT();
8987       // The memory VT and the element type must match.
8988       if (VecVT.getVectorElementType() == MemVT) {
8989         SDLoc DL(N);
8990         MVT MaskVT = getMaskTypeFor(VecVT);
8991         return DAG.getStoreVP(
8992             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8993             DAG.getConstant(1, DL, MaskVT),
8994             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8995             Store->getMemOperand(), Store->getAddressingMode(),
8996             Store->isTruncatingStore(), /*IsCompress*/ false);
8997       }
8998     }
8999 
9000     break;
9001   }
9002   case ISD::SPLAT_VECTOR: {
9003     EVT VT = N->getValueType(0);
9004     // Only perform this combine on legal MVT types.
9005     if (!isTypeLegal(VT))
9006       break;
9007     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9008                                          DAG, Subtarget))
9009       return Gather;
9010     break;
9011   }
9012   case RISCVISD::VMV_V_X_VL: {
9013     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9014     // scalar input.
9015     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9016     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9017     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9018       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9019         return SDValue(N, 0);
9020 
9021     break;
9022   }
9023   case ISD::INTRINSIC_WO_CHAIN: {
9024     unsigned IntNo = N->getConstantOperandVal(0);
9025     switch (IntNo) {
9026       // By default we do not combine any intrinsic.
9027     default:
9028       return SDValue();
9029     case Intrinsic::riscv_vcpop:
9030     case Intrinsic::riscv_vcpop_mask:
9031     case Intrinsic::riscv_vfirst:
9032     case Intrinsic::riscv_vfirst_mask: {
9033       SDValue VL = N->getOperand(2);
9034       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9035           IntNo == Intrinsic::riscv_vfirst_mask)
9036         VL = N->getOperand(3);
9037       if (!isNullConstant(VL))
9038         return SDValue();
9039       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9040       SDLoc DL(N);
9041       EVT VT = N->getValueType(0);
9042       if (IntNo == Intrinsic::riscv_vfirst ||
9043           IntNo == Intrinsic::riscv_vfirst_mask)
9044         return DAG.getConstant(-1, DL, VT);
9045       return DAG.getConstant(0, DL, VT);
9046     }
9047     }
9048   }
9049   }
9050 
9051   return SDValue();
9052 }
9053 
9054 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9055     const SDNode *N, CombineLevel Level) const {
9056   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9057   // materialised in fewer instructions than `(OP _, c1)`:
9058   //
9059   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9060   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9061   SDValue N0 = N->getOperand(0);
9062   EVT Ty = N0.getValueType();
9063   if (Ty.isScalarInteger() &&
9064       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9065     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9066     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9067     if (C1 && C2) {
9068       const APInt &C1Int = C1->getAPIntValue();
9069       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9070 
9071       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9072       // and the combine should happen, to potentially allow further combines
9073       // later.
9074       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9075           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9076         return true;
9077 
9078       // We can materialise `c1` in an add immediate, so it's "free", and the
9079       // combine should be prevented.
9080       if (C1Int.getMinSignedBits() <= 64 &&
9081           isLegalAddImmediate(C1Int.getSExtValue()))
9082         return false;
9083 
9084       // Neither constant will fit into an immediate, so find materialisation
9085       // costs.
9086       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9087                                               Subtarget.getFeatureBits(),
9088                                               /*CompressionCost*/true);
9089       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9090           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9091           /*CompressionCost*/true);
9092 
9093       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9094       // combine should be prevented.
9095       if (C1Cost < ShiftedC1Cost)
9096         return false;
9097     }
9098   }
9099   return true;
9100 }
9101 
9102 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9103     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9104     TargetLoweringOpt &TLO) const {
9105   // Delay this optimization as late as possible.
9106   if (!TLO.LegalOps)
9107     return false;
9108 
9109   EVT VT = Op.getValueType();
9110   if (VT.isVector())
9111     return false;
9112 
9113   // Only handle AND for now.
9114   if (Op.getOpcode() != ISD::AND)
9115     return false;
9116 
9117   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9118   if (!C)
9119     return false;
9120 
9121   const APInt &Mask = C->getAPIntValue();
9122 
9123   // Clear all non-demanded bits initially.
9124   APInt ShrunkMask = Mask & DemandedBits;
9125 
9126   // Try to make a smaller immediate by setting undemanded bits.
9127 
9128   APInt ExpandedMask = Mask | ~DemandedBits;
9129 
9130   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9131     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9132   };
9133   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9134     if (NewMask == Mask)
9135       return true;
9136     SDLoc DL(Op);
9137     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9138     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9139     return TLO.CombineTo(Op, NewOp);
9140   };
9141 
9142   // If the shrunk mask fits in sign extended 12 bits, let the target
9143   // independent code apply it.
9144   if (ShrunkMask.isSignedIntN(12))
9145     return false;
9146 
9147   // Preserve (and X, 0xffff) when zext.h is supported.
9148   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9149     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9150     if (IsLegalMask(NewMask))
9151       return UseMask(NewMask);
9152   }
9153 
9154   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9155   if (VT == MVT::i64) {
9156     APInt NewMask = APInt(64, 0xffffffff);
9157     if (IsLegalMask(NewMask))
9158       return UseMask(NewMask);
9159   }
9160 
9161   // For the remaining optimizations, we need to be able to make a negative
9162   // number through a combination of mask and undemanded bits.
9163   if (!ExpandedMask.isNegative())
9164     return false;
9165 
9166   // What is the fewest number of bits we need to represent the negative number.
9167   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9168 
9169   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9170   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9171   APInt NewMask = ShrunkMask;
9172   if (MinSignedBits <= 12)
9173     NewMask.setBitsFrom(11);
9174   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9175     NewMask.setBitsFrom(31);
9176   else
9177     return false;
9178 
9179   // Check that our new mask is a subset of the demanded mask.
9180   assert(IsLegalMask(NewMask));
9181   return UseMask(NewMask);
9182 }
9183 
9184 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9185   static const uint64_t GREVMasks[] = {
9186       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9187       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9188 
9189   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9190     unsigned Shift = 1 << Stage;
9191     if (ShAmt & Shift) {
9192       uint64_t Mask = GREVMasks[Stage];
9193       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9194       if (IsGORC)
9195         Res |= x;
9196       x = Res;
9197     }
9198   }
9199 
9200   return x;
9201 }
9202 
9203 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9204                                                         KnownBits &Known,
9205                                                         const APInt &DemandedElts,
9206                                                         const SelectionDAG &DAG,
9207                                                         unsigned Depth) const {
9208   unsigned BitWidth = Known.getBitWidth();
9209   unsigned Opc = Op.getOpcode();
9210   assert((Opc >= ISD::BUILTIN_OP_END ||
9211           Opc == ISD::INTRINSIC_WO_CHAIN ||
9212           Opc == ISD::INTRINSIC_W_CHAIN ||
9213           Opc == ISD::INTRINSIC_VOID) &&
9214          "Should use MaskedValueIsZero if you don't know whether Op"
9215          " is a target node!");
9216 
9217   Known.resetAll();
9218   switch (Opc) {
9219   default: break;
9220   case RISCVISD::SELECT_CC: {
9221     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9222     // If we don't know any bits, early out.
9223     if (Known.isUnknown())
9224       break;
9225     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9226 
9227     // Only known if known in both the LHS and RHS.
9228     Known = KnownBits::commonBits(Known, Known2);
9229     break;
9230   }
9231   case RISCVISD::REMUW: {
9232     KnownBits Known2;
9233     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9234     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9235     // We only care about the lower 32 bits.
9236     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9237     // Restore the original width by sign extending.
9238     Known = Known.sext(BitWidth);
9239     break;
9240   }
9241   case RISCVISD::DIVUW: {
9242     KnownBits Known2;
9243     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9244     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9245     // We only care about the lower 32 bits.
9246     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9247     // Restore the original width by sign extending.
9248     Known = Known.sext(BitWidth);
9249     break;
9250   }
9251   case RISCVISD::CTZW: {
9252     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9253     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9254     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9255     Known.Zero.setBitsFrom(LowBits);
9256     break;
9257   }
9258   case RISCVISD::CLZW: {
9259     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9260     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9261     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9262     Known.Zero.setBitsFrom(LowBits);
9263     break;
9264   }
9265   case RISCVISD::GREV:
9266   case RISCVISD::GORC: {
9267     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9268       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9269       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9270       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9271       // To compute zeros, we need to invert the value and invert it back after.
9272       Known.Zero =
9273           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9274       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9275     }
9276     break;
9277   }
9278   case RISCVISD::READ_VLENB: {
9279     // If we know the minimum VLen from Zvl extensions, we can use that to
9280     // determine the trailing zeros of VLENB.
9281     // FIXME: Limit to 128 bit vectors until we have more testing.
9282     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9283     if (MinVLenB > 0)
9284       Known.Zero.setLowBits(Log2_32(MinVLenB));
9285     // We assume VLENB is no more than 65536 / 8 bytes.
9286     Known.Zero.setBitsFrom(14);
9287     break;
9288   }
9289   case ISD::INTRINSIC_W_CHAIN:
9290   case ISD::INTRINSIC_WO_CHAIN: {
9291     unsigned IntNo =
9292         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9293     switch (IntNo) {
9294     default:
9295       // We can't do anything for most intrinsics.
9296       break;
9297     case Intrinsic::riscv_vsetvli:
9298     case Intrinsic::riscv_vsetvlimax:
9299     case Intrinsic::riscv_vsetvli_opt:
9300     case Intrinsic::riscv_vsetvlimax_opt:
9301       // Assume that VL output is positive and would fit in an int32_t.
9302       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9303       if (BitWidth >= 32)
9304         Known.Zero.setBitsFrom(31);
9305       break;
9306     }
9307     break;
9308   }
9309   }
9310 }
9311 
9312 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9313     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9314     unsigned Depth) const {
9315   switch (Op.getOpcode()) {
9316   default:
9317     break;
9318   case RISCVISD::SELECT_CC: {
9319     unsigned Tmp =
9320         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9321     if (Tmp == 1) return 1;  // Early out.
9322     unsigned Tmp2 =
9323         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9324     return std::min(Tmp, Tmp2);
9325   }
9326   case RISCVISD::SLLW:
9327   case RISCVISD::SRAW:
9328   case RISCVISD::SRLW:
9329   case RISCVISD::DIVW:
9330   case RISCVISD::DIVUW:
9331   case RISCVISD::REMUW:
9332   case RISCVISD::ROLW:
9333   case RISCVISD::RORW:
9334   case RISCVISD::GREVW:
9335   case RISCVISD::GORCW:
9336   case RISCVISD::FSLW:
9337   case RISCVISD::FSRW:
9338   case RISCVISD::SHFLW:
9339   case RISCVISD::UNSHFLW:
9340   case RISCVISD::BCOMPRESSW:
9341   case RISCVISD::BDECOMPRESSW:
9342   case RISCVISD::BFPW:
9343   case RISCVISD::FCVT_W_RV64:
9344   case RISCVISD::FCVT_WU_RV64:
9345   case RISCVISD::STRICT_FCVT_W_RV64:
9346   case RISCVISD::STRICT_FCVT_WU_RV64:
9347     // TODO: As the result is sign-extended, this is conservatively correct. A
9348     // more precise answer could be calculated for SRAW depending on known
9349     // bits in the shift amount.
9350     return 33;
9351   case RISCVISD::SHFL:
9352   case RISCVISD::UNSHFL: {
9353     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9354     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9355     // will stay within the upper 32 bits. If there were more than 32 sign bits
9356     // before there will be at least 33 sign bits after.
9357     if (Op.getValueType() == MVT::i64 &&
9358         isa<ConstantSDNode>(Op.getOperand(1)) &&
9359         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9360       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9361       if (Tmp > 32)
9362         return 33;
9363     }
9364     break;
9365   }
9366   case RISCVISD::VMV_X_S: {
9367     // The number of sign bits of the scalar result is computed by obtaining the
9368     // element type of the input vector operand, subtracting its width from the
9369     // XLEN, and then adding one (sign bit within the element type). If the
9370     // element type is wider than XLen, the least-significant XLEN bits are
9371     // taken.
9372     unsigned XLen = Subtarget.getXLen();
9373     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9374     if (EltBits <= XLen)
9375       return XLen - EltBits + 1;
9376     break;
9377   }
9378   }
9379 
9380   return 1;
9381 }
9382 
9383 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9384                                                   MachineBasicBlock *BB) {
9385   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9386 
9387   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9388   // Should the count have wrapped while it was being read, we need to try
9389   // again.
9390   // ...
9391   // read:
9392   // rdcycleh x3 # load high word of cycle
9393   // rdcycle  x2 # load low word of cycle
9394   // rdcycleh x4 # load high word of cycle
9395   // bne x3, x4, read # check if high word reads match, otherwise try again
9396   // ...
9397 
9398   MachineFunction &MF = *BB->getParent();
9399   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9400   MachineFunction::iterator It = ++BB->getIterator();
9401 
9402   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9403   MF.insert(It, LoopMBB);
9404 
9405   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9406   MF.insert(It, DoneMBB);
9407 
9408   // Transfer the remainder of BB and its successor edges to DoneMBB.
9409   DoneMBB->splice(DoneMBB->begin(), BB,
9410                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9411   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9412 
9413   BB->addSuccessor(LoopMBB);
9414 
9415   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9416   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9417   Register LoReg = MI.getOperand(0).getReg();
9418   Register HiReg = MI.getOperand(1).getReg();
9419   DebugLoc DL = MI.getDebugLoc();
9420 
9421   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9422   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9423       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9424       .addReg(RISCV::X0);
9425   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9426       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9427       .addReg(RISCV::X0);
9428   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9429       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9430       .addReg(RISCV::X0);
9431 
9432   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9433       .addReg(HiReg)
9434       .addReg(ReadAgainReg)
9435       .addMBB(LoopMBB);
9436 
9437   LoopMBB->addSuccessor(LoopMBB);
9438   LoopMBB->addSuccessor(DoneMBB);
9439 
9440   MI.eraseFromParent();
9441 
9442   return DoneMBB;
9443 }
9444 
9445 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9446                                              MachineBasicBlock *BB) {
9447   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9448 
9449   MachineFunction &MF = *BB->getParent();
9450   DebugLoc DL = MI.getDebugLoc();
9451   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9452   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9453   Register LoReg = MI.getOperand(0).getReg();
9454   Register HiReg = MI.getOperand(1).getReg();
9455   Register SrcReg = MI.getOperand(2).getReg();
9456   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9457   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9458 
9459   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9460                           RI);
9461   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9462   MachineMemOperand *MMOLo =
9463       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9464   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9465       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9466   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9467       .addFrameIndex(FI)
9468       .addImm(0)
9469       .addMemOperand(MMOLo);
9470   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9471       .addFrameIndex(FI)
9472       .addImm(4)
9473       .addMemOperand(MMOHi);
9474   MI.eraseFromParent(); // The pseudo instruction is gone now.
9475   return BB;
9476 }
9477 
9478 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9479                                                  MachineBasicBlock *BB) {
9480   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9481          "Unexpected instruction");
9482 
9483   MachineFunction &MF = *BB->getParent();
9484   DebugLoc DL = MI.getDebugLoc();
9485   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9486   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9487   Register DstReg = MI.getOperand(0).getReg();
9488   Register LoReg = MI.getOperand(1).getReg();
9489   Register HiReg = MI.getOperand(2).getReg();
9490   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9491   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9492 
9493   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9494   MachineMemOperand *MMOLo =
9495       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9496   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9497       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9498   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9499       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9500       .addFrameIndex(FI)
9501       .addImm(0)
9502       .addMemOperand(MMOLo);
9503   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9504       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9505       .addFrameIndex(FI)
9506       .addImm(4)
9507       .addMemOperand(MMOHi);
9508   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9509   MI.eraseFromParent(); // The pseudo instruction is gone now.
9510   return BB;
9511 }
9512 
9513 static bool isSelectPseudo(MachineInstr &MI) {
9514   switch (MI.getOpcode()) {
9515   default:
9516     return false;
9517   case RISCV::Select_GPR_Using_CC_GPR:
9518   case RISCV::Select_FPR16_Using_CC_GPR:
9519   case RISCV::Select_FPR32_Using_CC_GPR:
9520   case RISCV::Select_FPR64_Using_CC_GPR:
9521     return true;
9522   }
9523 }
9524 
9525 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9526                                         unsigned RelOpcode, unsigned EqOpcode,
9527                                         const RISCVSubtarget &Subtarget) {
9528   DebugLoc DL = MI.getDebugLoc();
9529   Register DstReg = MI.getOperand(0).getReg();
9530   Register Src1Reg = MI.getOperand(1).getReg();
9531   Register Src2Reg = MI.getOperand(2).getReg();
9532   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9533   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9534   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9535 
9536   // Save the current FFLAGS.
9537   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9538 
9539   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9540                  .addReg(Src1Reg)
9541                  .addReg(Src2Reg);
9542   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9543     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9544 
9545   // Restore the FFLAGS.
9546   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9547       .addReg(SavedFFlags, RegState::Kill);
9548 
9549   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9550   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9551                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9552                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9553   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9554     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9555 
9556   // Erase the pseudoinstruction.
9557   MI.eraseFromParent();
9558   return BB;
9559 }
9560 
9561 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9562                                            MachineBasicBlock *BB,
9563                                            const RISCVSubtarget &Subtarget) {
9564   // To "insert" Select_* instructions, we actually have to insert the triangle
9565   // control-flow pattern.  The incoming instructions know the destination vreg
9566   // to set, the condition code register to branch on, the true/false values to
9567   // select between, and the condcode to use to select the appropriate branch.
9568   //
9569   // We produce the following control flow:
9570   //     HeadMBB
9571   //     |  \
9572   //     |  IfFalseMBB
9573   //     | /
9574   //    TailMBB
9575   //
9576   // When we find a sequence of selects we attempt to optimize their emission
9577   // by sharing the control flow. Currently we only handle cases where we have
9578   // multiple selects with the exact same condition (same LHS, RHS and CC).
9579   // The selects may be interleaved with other instructions if the other
9580   // instructions meet some requirements we deem safe:
9581   // - They are debug instructions. Otherwise,
9582   // - They do not have side-effects, do not access memory and their inputs do
9583   //   not depend on the results of the select pseudo-instructions.
9584   // The TrueV/FalseV operands of the selects cannot depend on the result of
9585   // previous selects in the sequence.
9586   // These conditions could be further relaxed. See the X86 target for a
9587   // related approach and more information.
9588   Register LHS = MI.getOperand(1).getReg();
9589   Register RHS = MI.getOperand(2).getReg();
9590   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9591 
9592   SmallVector<MachineInstr *, 4> SelectDebugValues;
9593   SmallSet<Register, 4> SelectDests;
9594   SelectDests.insert(MI.getOperand(0).getReg());
9595 
9596   MachineInstr *LastSelectPseudo = &MI;
9597 
9598   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9599        SequenceMBBI != E; ++SequenceMBBI) {
9600     if (SequenceMBBI->isDebugInstr())
9601       continue;
9602     if (isSelectPseudo(*SequenceMBBI)) {
9603       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9604           SequenceMBBI->getOperand(2).getReg() != RHS ||
9605           SequenceMBBI->getOperand(3).getImm() != CC ||
9606           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9607           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9608         break;
9609       LastSelectPseudo = &*SequenceMBBI;
9610       SequenceMBBI->collectDebugValues(SelectDebugValues);
9611       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9612     } else {
9613       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9614           SequenceMBBI->mayLoadOrStore())
9615         break;
9616       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9617             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9618           }))
9619         break;
9620     }
9621   }
9622 
9623   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9624   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9625   DebugLoc DL = MI.getDebugLoc();
9626   MachineFunction::iterator I = ++BB->getIterator();
9627 
9628   MachineBasicBlock *HeadMBB = BB;
9629   MachineFunction *F = BB->getParent();
9630   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9631   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9632 
9633   F->insert(I, IfFalseMBB);
9634   F->insert(I, TailMBB);
9635 
9636   // Transfer debug instructions associated with the selects to TailMBB.
9637   for (MachineInstr *DebugInstr : SelectDebugValues) {
9638     TailMBB->push_back(DebugInstr->removeFromParent());
9639   }
9640 
9641   // Move all instructions after the sequence to TailMBB.
9642   TailMBB->splice(TailMBB->end(), HeadMBB,
9643                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9644   // Update machine-CFG edges by transferring all successors of the current
9645   // block to the new block which will contain the Phi nodes for the selects.
9646   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9647   // Set the successors for HeadMBB.
9648   HeadMBB->addSuccessor(IfFalseMBB);
9649   HeadMBB->addSuccessor(TailMBB);
9650 
9651   // Insert appropriate branch.
9652   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9653     .addReg(LHS)
9654     .addReg(RHS)
9655     .addMBB(TailMBB);
9656 
9657   // IfFalseMBB just falls through to TailMBB.
9658   IfFalseMBB->addSuccessor(TailMBB);
9659 
9660   // Create PHIs for all of the select pseudo-instructions.
9661   auto SelectMBBI = MI.getIterator();
9662   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9663   auto InsertionPoint = TailMBB->begin();
9664   while (SelectMBBI != SelectEnd) {
9665     auto Next = std::next(SelectMBBI);
9666     if (isSelectPseudo(*SelectMBBI)) {
9667       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9668       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9669               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9670           .addReg(SelectMBBI->getOperand(4).getReg())
9671           .addMBB(HeadMBB)
9672           .addReg(SelectMBBI->getOperand(5).getReg())
9673           .addMBB(IfFalseMBB);
9674       SelectMBBI->eraseFromParent();
9675     }
9676     SelectMBBI = Next;
9677   }
9678 
9679   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9680   return TailMBB;
9681 }
9682 
9683 MachineBasicBlock *
9684 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9685                                                  MachineBasicBlock *BB) const {
9686   switch (MI.getOpcode()) {
9687   default:
9688     llvm_unreachable("Unexpected instr type to insert");
9689   case RISCV::ReadCycleWide:
9690     assert(!Subtarget.is64Bit() &&
9691            "ReadCycleWrite is only to be used on riscv32");
9692     return emitReadCycleWidePseudo(MI, BB);
9693   case RISCV::Select_GPR_Using_CC_GPR:
9694   case RISCV::Select_FPR16_Using_CC_GPR:
9695   case RISCV::Select_FPR32_Using_CC_GPR:
9696   case RISCV::Select_FPR64_Using_CC_GPR:
9697     return emitSelectPseudo(MI, BB, Subtarget);
9698   case RISCV::BuildPairF64Pseudo:
9699     return emitBuildPairF64Pseudo(MI, BB);
9700   case RISCV::SplitF64Pseudo:
9701     return emitSplitF64Pseudo(MI, BB);
9702   case RISCV::PseudoQuietFLE_H:
9703     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9704   case RISCV::PseudoQuietFLT_H:
9705     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9706   case RISCV::PseudoQuietFLE_S:
9707     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9708   case RISCV::PseudoQuietFLT_S:
9709     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9710   case RISCV::PseudoQuietFLE_D:
9711     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9712   case RISCV::PseudoQuietFLT_D:
9713     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9714   }
9715 }
9716 
9717 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9718                                                         SDNode *Node) const {
9719   // Add FRM dependency to any instructions with dynamic rounding mode.
9720   unsigned Opc = MI.getOpcode();
9721   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9722   if (Idx < 0)
9723     return;
9724   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9725     return;
9726   // If the instruction already reads FRM, don't add another read.
9727   if (MI.readsRegister(RISCV::FRM))
9728     return;
9729   MI.addOperand(
9730       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9731 }
9732 
9733 // Calling Convention Implementation.
9734 // The expectations for frontend ABI lowering vary from target to target.
9735 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9736 // details, but this is a longer term goal. For now, we simply try to keep the
9737 // role of the frontend as simple and well-defined as possible. The rules can
9738 // be summarised as:
9739 // * Never split up large scalar arguments. We handle them here.
9740 // * If a hardfloat calling convention is being used, and the struct may be
9741 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9742 // available, then pass as two separate arguments. If either the GPRs or FPRs
9743 // are exhausted, then pass according to the rule below.
9744 // * If a struct could never be passed in registers or directly in a stack
9745 // slot (as it is larger than 2*XLEN and the floating point rules don't
9746 // apply), then pass it using a pointer with the byval attribute.
9747 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9748 // word-sized array or a 2*XLEN scalar (depending on alignment).
9749 // * The frontend can determine whether a struct is returned by reference or
9750 // not based on its size and fields. If it will be returned by reference, the
9751 // frontend must modify the prototype so a pointer with the sret annotation is
9752 // passed as the first argument. This is not necessary for large scalar
9753 // returns.
9754 // * Struct return values and varargs should be coerced to structs containing
9755 // register-size fields in the same situations they would be for fixed
9756 // arguments.
9757 
9758 static const MCPhysReg ArgGPRs[] = {
9759   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9760   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9761 };
9762 static const MCPhysReg ArgFPR16s[] = {
9763   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9764   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9765 };
9766 static const MCPhysReg ArgFPR32s[] = {
9767   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9768   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9769 };
9770 static const MCPhysReg ArgFPR64s[] = {
9771   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9772   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9773 };
9774 // This is an interim calling convention and it may be changed in the future.
9775 static const MCPhysReg ArgVRs[] = {
9776     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9777     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9778     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9779 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9780                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9781                                      RISCV::V20M2, RISCV::V22M2};
9782 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9783                                      RISCV::V20M4};
9784 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9785 
9786 // Pass a 2*XLEN argument that has been split into two XLEN values through
9787 // registers or the stack as necessary.
9788 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9789                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9790                                 MVT ValVT2, MVT LocVT2,
9791                                 ISD::ArgFlagsTy ArgFlags2) {
9792   unsigned XLenInBytes = XLen / 8;
9793   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9794     // At least one half can be passed via register.
9795     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9796                                      VA1.getLocVT(), CCValAssign::Full));
9797   } else {
9798     // Both halves must be passed on the stack, with proper alignment.
9799     Align StackAlign =
9800         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9801     State.addLoc(
9802         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9803                             State.AllocateStack(XLenInBytes, StackAlign),
9804                             VA1.getLocVT(), CCValAssign::Full));
9805     State.addLoc(CCValAssign::getMem(
9806         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9807         LocVT2, CCValAssign::Full));
9808     return false;
9809   }
9810 
9811   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9812     // The second half can also be passed via register.
9813     State.addLoc(
9814         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9815   } else {
9816     // The second half is passed via the stack, without additional alignment.
9817     State.addLoc(CCValAssign::getMem(
9818         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9819         LocVT2, CCValAssign::Full));
9820   }
9821 
9822   return false;
9823 }
9824 
9825 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9826                                Optional<unsigned> FirstMaskArgument,
9827                                CCState &State, const RISCVTargetLowering &TLI) {
9828   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9829   if (RC == &RISCV::VRRegClass) {
9830     // Assign the first mask argument to V0.
9831     // This is an interim calling convention and it may be changed in the
9832     // future.
9833     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9834       return State.AllocateReg(RISCV::V0);
9835     return State.AllocateReg(ArgVRs);
9836   }
9837   if (RC == &RISCV::VRM2RegClass)
9838     return State.AllocateReg(ArgVRM2s);
9839   if (RC == &RISCV::VRM4RegClass)
9840     return State.AllocateReg(ArgVRM4s);
9841   if (RC == &RISCV::VRM8RegClass)
9842     return State.AllocateReg(ArgVRM8s);
9843   llvm_unreachable("Unhandled register class for ValueType");
9844 }
9845 
9846 // Implements the RISC-V calling convention. Returns true upon failure.
9847 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9848                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9849                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9850                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9851                      Optional<unsigned> FirstMaskArgument) {
9852   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9853   assert(XLen == 32 || XLen == 64);
9854   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9855 
9856   // Any return value split in to more than two values can't be returned
9857   // directly. Vectors are returned via the available vector registers.
9858   if (!LocVT.isVector() && IsRet && ValNo > 1)
9859     return true;
9860 
9861   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9862   // variadic argument, or if no F16/F32 argument registers are available.
9863   bool UseGPRForF16_F32 = true;
9864   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9865   // variadic argument, or if no F64 argument registers are available.
9866   bool UseGPRForF64 = true;
9867 
9868   switch (ABI) {
9869   default:
9870     llvm_unreachable("Unexpected ABI");
9871   case RISCVABI::ABI_ILP32:
9872   case RISCVABI::ABI_LP64:
9873     break;
9874   case RISCVABI::ABI_ILP32F:
9875   case RISCVABI::ABI_LP64F:
9876     UseGPRForF16_F32 = !IsFixed;
9877     break;
9878   case RISCVABI::ABI_ILP32D:
9879   case RISCVABI::ABI_LP64D:
9880     UseGPRForF16_F32 = !IsFixed;
9881     UseGPRForF64 = !IsFixed;
9882     break;
9883   }
9884 
9885   // FPR16, FPR32, and FPR64 alias each other.
9886   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9887     UseGPRForF16_F32 = true;
9888     UseGPRForF64 = true;
9889   }
9890 
9891   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9892   // similar local variables rather than directly checking against the target
9893   // ABI.
9894 
9895   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9896     LocVT = XLenVT;
9897     LocInfo = CCValAssign::BCvt;
9898   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9899     LocVT = MVT::i64;
9900     LocInfo = CCValAssign::BCvt;
9901   }
9902 
9903   // If this is a variadic argument, the RISC-V calling convention requires
9904   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9905   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9906   // be used regardless of whether the original argument was split during
9907   // legalisation or not. The argument will not be passed by registers if the
9908   // original type is larger than 2*XLEN, so the register alignment rule does
9909   // not apply.
9910   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9911   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9912       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9913     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9914     // Skip 'odd' register if necessary.
9915     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9916       State.AllocateReg(ArgGPRs);
9917   }
9918 
9919   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9920   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9921       State.getPendingArgFlags();
9922 
9923   assert(PendingLocs.size() == PendingArgFlags.size() &&
9924          "PendingLocs and PendingArgFlags out of sync");
9925 
9926   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9927   // registers are exhausted.
9928   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9929     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9930            "Can't lower f64 if it is split");
9931     // Depending on available argument GPRS, f64 may be passed in a pair of
9932     // GPRs, split between a GPR and the stack, or passed completely on the
9933     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9934     // cases.
9935     Register Reg = State.AllocateReg(ArgGPRs);
9936     LocVT = MVT::i32;
9937     if (!Reg) {
9938       unsigned StackOffset = State.AllocateStack(8, Align(8));
9939       State.addLoc(
9940           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9941       return false;
9942     }
9943     if (!State.AllocateReg(ArgGPRs))
9944       State.AllocateStack(4, Align(4));
9945     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9946     return false;
9947   }
9948 
9949   // Fixed-length vectors are located in the corresponding scalable-vector
9950   // container types.
9951   if (ValVT.isFixedLengthVector())
9952     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9953 
9954   // Split arguments might be passed indirectly, so keep track of the pending
9955   // values. Split vectors are passed via a mix of registers and indirectly, so
9956   // treat them as we would any other argument.
9957   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9958     LocVT = XLenVT;
9959     LocInfo = CCValAssign::Indirect;
9960     PendingLocs.push_back(
9961         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9962     PendingArgFlags.push_back(ArgFlags);
9963     if (!ArgFlags.isSplitEnd()) {
9964       return false;
9965     }
9966   }
9967 
9968   // If the split argument only had two elements, it should be passed directly
9969   // in registers or on the stack.
9970   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9971       PendingLocs.size() <= 2) {
9972     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9973     // Apply the normal calling convention rules to the first half of the
9974     // split argument.
9975     CCValAssign VA = PendingLocs[0];
9976     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9977     PendingLocs.clear();
9978     PendingArgFlags.clear();
9979     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9980                                ArgFlags);
9981   }
9982 
9983   // Allocate to a register if possible, or else a stack slot.
9984   Register Reg;
9985   unsigned StoreSizeBytes = XLen / 8;
9986   Align StackAlign = Align(XLen / 8);
9987 
9988   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9989     Reg = State.AllocateReg(ArgFPR16s);
9990   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9991     Reg = State.AllocateReg(ArgFPR32s);
9992   else if (ValVT == MVT::f64 && !UseGPRForF64)
9993     Reg = State.AllocateReg(ArgFPR64s);
9994   else if (ValVT.isVector()) {
9995     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9996     if (!Reg) {
9997       // For return values, the vector must be passed fully via registers or
9998       // via the stack.
9999       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10000       // but we're using all of them.
10001       if (IsRet)
10002         return true;
10003       // Try using a GPR to pass the address
10004       if ((Reg = State.AllocateReg(ArgGPRs))) {
10005         LocVT = XLenVT;
10006         LocInfo = CCValAssign::Indirect;
10007       } else if (ValVT.isScalableVector()) {
10008         LocVT = XLenVT;
10009         LocInfo = CCValAssign::Indirect;
10010       } else {
10011         // Pass fixed-length vectors on the stack.
10012         LocVT = ValVT;
10013         StoreSizeBytes = ValVT.getStoreSize();
10014         // Align vectors to their element sizes, being careful for vXi1
10015         // vectors.
10016         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10017       }
10018     }
10019   } else {
10020     Reg = State.AllocateReg(ArgGPRs);
10021   }
10022 
10023   unsigned StackOffset =
10024       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10025 
10026   // If we reach this point and PendingLocs is non-empty, we must be at the
10027   // end of a split argument that must be passed indirectly.
10028   if (!PendingLocs.empty()) {
10029     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10030     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10031 
10032     for (auto &It : PendingLocs) {
10033       if (Reg)
10034         It.convertToReg(Reg);
10035       else
10036         It.convertToMem(StackOffset);
10037       State.addLoc(It);
10038     }
10039     PendingLocs.clear();
10040     PendingArgFlags.clear();
10041     return false;
10042   }
10043 
10044   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10045           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10046          "Expected an XLenVT or vector types at this stage");
10047 
10048   if (Reg) {
10049     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10050     return false;
10051   }
10052 
10053   // When a floating-point value is passed on the stack, no bit-conversion is
10054   // needed.
10055   if (ValVT.isFloatingPoint()) {
10056     LocVT = ValVT;
10057     LocInfo = CCValAssign::Full;
10058   }
10059   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10060   return false;
10061 }
10062 
10063 template <typename ArgTy>
10064 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10065   for (const auto &ArgIdx : enumerate(Args)) {
10066     MVT ArgVT = ArgIdx.value().VT;
10067     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10068       return ArgIdx.index();
10069   }
10070   return None;
10071 }
10072 
10073 void RISCVTargetLowering::analyzeInputArgs(
10074     MachineFunction &MF, CCState &CCInfo,
10075     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10076     RISCVCCAssignFn Fn) const {
10077   unsigned NumArgs = Ins.size();
10078   FunctionType *FType = MF.getFunction().getFunctionType();
10079 
10080   Optional<unsigned> FirstMaskArgument;
10081   if (Subtarget.hasVInstructions())
10082     FirstMaskArgument = preAssignMask(Ins);
10083 
10084   for (unsigned i = 0; i != NumArgs; ++i) {
10085     MVT ArgVT = Ins[i].VT;
10086     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10087 
10088     Type *ArgTy = nullptr;
10089     if (IsRet)
10090       ArgTy = FType->getReturnType();
10091     else if (Ins[i].isOrigArg())
10092       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10093 
10094     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10095     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10096            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10097            FirstMaskArgument)) {
10098       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10099                         << EVT(ArgVT).getEVTString() << '\n');
10100       llvm_unreachable(nullptr);
10101     }
10102   }
10103 }
10104 
10105 void RISCVTargetLowering::analyzeOutputArgs(
10106     MachineFunction &MF, CCState &CCInfo,
10107     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10108     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10109   unsigned NumArgs = Outs.size();
10110 
10111   Optional<unsigned> FirstMaskArgument;
10112   if (Subtarget.hasVInstructions())
10113     FirstMaskArgument = preAssignMask(Outs);
10114 
10115   for (unsigned i = 0; i != NumArgs; i++) {
10116     MVT ArgVT = Outs[i].VT;
10117     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10118     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10119 
10120     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10121     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10122            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10123            FirstMaskArgument)) {
10124       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10125                         << EVT(ArgVT).getEVTString() << "\n");
10126       llvm_unreachable(nullptr);
10127     }
10128   }
10129 }
10130 
10131 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10132 // values.
10133 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10134                                    const CCValAssign &VA, const SDLoc &DL,
10135                                    const RISCVSubtarget &Subtarget) {
10136   switch (VA.getLocInfo()) {
10137   default:
10138     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10139   case CCValAssign::Full:
10140     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10141       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10142     break;
10143   case CCValAssign::BCvt:
10144     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10145       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10146     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10147       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10148     else
10149       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10150     break;
10151   }
10152   return Val;
10153 }
10154 
10155 // The caller is responsible for loading the full value if the argument is
10156 // passed with CCValAssign::Indirect.
10157 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10158                                 const CCValAssign &VA, const SDLoc &DL,
10159                                 const RISCVTargetLowering &TLI) {
10160   MachineFunction &MF = DAG.getMachineFunction();
10161   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10162   EVT LocVT = VA.getLocVT();
10163   SDValue Val;
10164   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10165   Register VReg = RegInfo.createVirtualRegister(RC);
10166   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10167   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10168 
10169   if (VA.getLocInfo() == CCValAssign::Indirect)
10170     return Val;
10171 
10172   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10173 }
10174 
10175 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10176                                    const CCValAssign &VA, const SDLoc &DL,
10177                                    const RISCVSubtarget &Subtarget) {
10178   EVT LocVT = VA.getLocVT();
10179 
10180   switch (VA.getLocInfo()) {
10181   default:
10182     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10183   case CCValAssign::Full:
10184     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10185       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10186     break;
10187   case CCValAssign::BCvt:
10188     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10189       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10190     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10191       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10192     else
10193       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10194     break;
10195   }
10196   return Val;
10197 }
10198 
10199 // The caller is responsible for loading the full value if the argument is
10200 // passed with CCValAssign::Indirect.
10201 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10202                                 const CCValAssign &VA, const SDLoc &DL) {
10203   MachineFunction &MF = DAG.getMachineFunction();
10204   MachineFrameInfo &MFI = MF.getFrameInfo();
10205   EVT LocVT = VA.getLocVT();
10206   EVT ValVT = VA.getValVT();
10207   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10208   if (ValVT.isScalableVector()) {
10209     // When the value is a scalable vector, we save the pointer which points to
10210     // the scalable vector value in the stack. The ValVT will be the pointer
10211     // type, instead of the scalable vector type.
10212     ValVT = LocVT;
10213   }
10214   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10215                                  /*IsImmutable=*/true);
10216   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10217   SDValue Val;
10218 
10219   ISD::LoadExtType ExtType;
10220   switch (VA.getLocInfo()) {
10221   default:
10222     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10223   case CCValAssign::Full:
10224   case CCValAssign::Indirect:
10225   case CCValAssign::BCvt:
10226     ExtType = ISD::NON_EXTLOAD;
10227     break;
10228   }
10229   Val = DAG.getExtLoad(
10230       ExtType, DL, LocVT, Chain, FIN,
10231       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10232   return Val;
10233 }
10234 
10235 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10236                                        const CCValAssign &VA, const SDLoc &DL) {
10237   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10238          "Unexpected VA");
10239   MachineFunction &MF = DAG.getMachineFunction();
10240   MachineFrameInfo &MFI = MF.getFrameInfo();
10241   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10242 
10243   if (VA.isMemLoc()) {
10244     // f64 is passed on the stack.
10245     int FI =
10246         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10247     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10248     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10249                        MachinePointerInfo::getFixedStack(MF, FI));
10250   }
10251 
10252   assert(VA.isRegLoc() && "Expected register VA assignment");
10253 
10254   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10255   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10256   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10257   SDValue Hi;
10258   if (VA.getLocReg() == RISCV::X17) {
10259     // Second half of f64 is passed on the stack.
10260     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10261     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10262     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10263                      MachinePointerInfo::getFixedStack(MF, FI));
10264   } else {
10265     // Second half of f64 is passed in another GPR.
10266     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10267     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10268     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10269   }
10270   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10271 }
10272 
10273 // FastCC has less than 1% performance improvement for some particular
10274 // benchmark. But theoretically, it may has benenfit for some cases.
10275 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10276                             unsigned ValNo, MVT ValVT, MVT LocVT,
10277                             CCValAssign::LocInfo LocInfo,
10278                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10279                             bool IsFixed, bool IsRet, Type *OrigTy,
10280                             const RISCVTargetLowering &TLI,
10281                             Optional<unsigned> FirstMaskArgument) {
10282 
10283   // X5 and X6 might be used for save-restore libcall.
10284   static const MCPhysReg GPRList[] = {
10285       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10286       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10287       RISCV::X29, RISCV::X30, RISCV::X31};
10288 
10289   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10290     if (unsigned Reg = State.AllocateReg(GPRList)) {
10291       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10292       return false;
10293     }
10294   }
10295 
10296   if (LocVT == MVT::f16) {
10297     static const MCPhysReg FPR16List[] = {
10298         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10299         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10300         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10301         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10302     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10303       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10304       return false;
10305     }
10306   }
10307 
10308   if (LocVT == MVT::f32) {
10309     static const MCPhysReg FPR32List[] = {
10310         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10311         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10312         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10313         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10314     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10315       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10316       return false;
10317     }
10318   }
10319 
10320   if (LocVT == MVT::f64) {
10321     static const MCPhysReg FPR64List[] = {
10322         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10323         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10324         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10325         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10326     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10327       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10328       return false;
10329     }
10330   }
10331 
10332   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10333     unsigned Offset4 = State.AllocateStack(4, Align(4));
10334     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10335     return false;
10336   }
10337 
10338   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10339     unsigned Offset5 = State.AllocateStack(8, Align(8));
10340     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10341     return false;
10342   }
10343 
10344   if (LocVT.isVector()) {
10345     if (unsigned Reg =
10346             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10347       // Fixed-length vectors are located in the corresponding scalable-vector
10348       // container types.
10349       if (ValVT.isFixedLengthVector())
10350         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10351       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10352     } else {
10353       // Try and pass the address via a "fast" GPR.
10354       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10355         LocInfo = CCValAssign::Indirect;
10356         LocVT = TLI.getSubtarget().getXLenVT();
10357         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10358       } else if (ValVT.isFixedLengthVector()) {
10359         auto StackAlign =
10360             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10361         unsigned StackOffset =
10362             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10363         State.addLoc(
10364             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10365       } else {
10366         // Can't pass scalable vectors on the stack.
10367         return true;
10368       }
10369     }
10370 
10371     return false;
10372   }
10373 
10374   return true; // CC didn't match.
10375 }
10376 
10377 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10378                          CCValAssign::LocInfo LocInfo,
10379                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10380 
10381   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10382     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10383     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10384     static const MCPhysReg GPRList[] = {
10385         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10386         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10387     if (unsigned Reg = State.AllocateReg(GPRList)) {
10388       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10389       return false;
10390     }
10391   }
10392 
10393   if (LocVT == MVT::f32) {
10394     // Pass in STG registers: F1, ..., F6
10395     //                        fs0 ... fs5
10396     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10397                                           RISCV::F18_F, RISCV::F19_F,
10398                                           RISCV::F20_F, RISCV::F21_F};
10399     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10400       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10401       return false;
10402     }
10403   }
10404 
10405   if (LocVT == MVT::f64) {
10406     // Pass in STG registers: D1, ..., D6
10407     //                        fs6 ... fs11
10408     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10409                                           RISCV::F24_D, RISCV::F25_D,
10410                                           RISCV::F26_D, RISCV::F27_D};
10411     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10412       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10413       return false;
10414     }
10415   }
10416 
10417   report_fatal_error("No registers left in GHC calling convention");
10418   return true;
10419 }
10420 
10421 // Transform physical registers into virtual registers.
10422 SDValue RISCVTargetLowering::LowerFormalArguments(
10423     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10424     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10425     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10426 
10427   MachineFunction &MF = DAG.getMachineFunction();
10428 
10429   switch (CallConv) {
10430   default:
10431     report_fatal_error("Unsupported calling convention");
10432   case CallingConv::C:
10433   case CallingConv::Fast:
10434     break;
10435   case CallingConv::GHC:
10436     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10437         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10438       report_fatal_error(
10439         "GHC calling convention requires the F and D instruction set extensions");
10440   }
10441 
10442   const Function &Func = MF.getFunction();
10443   if (Func.hasFnAttribute("interrupt")) {
10444     if (!Func.arg_empty())
10445       report_fatal_error(
10446         "Functions with the interrupt attribute cannot have arguments!");
10447 
10448     StringRef Kind =
10449       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10450 
10451     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10452       report_fatal_error(
10453         "Function interrupt attribute argument not supported!");
10454   }
10455 
10456   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10457   MVT XLenVT = Subtarget.getXLenVT();
10458   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10459   // Used with vargs to acumulate store chains.
10460   std::vector<SDValue> OutChains;
10461 
10462   // Assign locations to all of the incoming arguments.
10463   SmallVector<CCValAssign, 16> ArgLocs;
10464   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10465 
10466   if (CallConv == CallingConv::GHC)
10467     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10468   else
10469     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10470                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10471                                                    : CC_RISCV);
10472 
10473   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10474     CCValAssign &VA = ArgLocs[i];
10475     SDValue ArgValue;
10476     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10477     // case.
10478     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10479       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10480     else if (VA.isRegLoc())
10481       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10482     else
10483       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10484 
10485     if (VA.getLocInfo() == CCValAssign::Indirect) {
10486       // If the original argument was split and passed by reference (e.g. i128
10487       // on RV32), we need to load all parts of it here (using the same
10488       // address). Vectors may be partly split to registers and partly to the
10489       // stack, in which case the base address is partly offset and subsequent
10490       // stores are relative to that.
10491       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10492                                    MachinePointerInfo()));
10493       unsigned ArgIndex = Ins[i].OrigArgIndex;
10494       unsigned ArgPartOffset = Ins[i].PartOffset;
10495       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10496       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10497         CCValAssign &PartVA = ArgLocs[i + 1];
10498         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10499         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10500         if (PartVA.getValVT().isScalableVector())
10501           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10502         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10503         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10504                                      MachinePointerInfo()));
10505         ++i;
10506       }
10507       continue;
10508     }
10509     InVals.push_back(ArgValue);
10510   }
10511 
10512   if (IsVarArg) {
10513     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10514     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10515     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10516     MachineFrameInfo &MFI = MF.getFrameInfo();
10517     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10518     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10519 
10520     // Offset of the first variable argument from stack pointer, and size of
10521     // the vararg save area. For now, the varargs save area is either zero or
10522     // large enough to hold a0-a7.
10523     int VaArgOffset, VarArgsSaveSize;
10524 
10525     // If all registers are allocated, then all varargs must be passed on the
10526     // stack and we don't need to save any argregs.
10527     if (ArgRegs.size() == Idx) {
10528       VaArgOffset = CCInfo.getNextStackOffset();
10529       VarArgsSaveSize = 0;
10530     } else {
10531       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10532       VaArgOffset = -VarArgsSaveSize;
10533     }
10534 
10535     // Record the frame index of the first variable argument
10536     // which is a value necessary to VASTART.
10537     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10538     RVFI->setVarArgsFrameIndex(FI);
10539 
10540     // If saving an odd number of registers then create an extra stack slot to
10541     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10542     // offsets to even-numbered registered remain 2*XLEN-aligned.
10543     if (Idx % 2) {
10544       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10545       VarArgsSaveSize += XLenInBytes;
10546     }
10547 
10548     // Copy the integer registers that may have been used for passing varargs
10549     // to the vararg save area.
10550     for (unsigned I = Idx; I < ArgRegs.size();
10551          ++I, VaArgOffset += XLenInBytes) {
10552       const Register Reg = RegInfo.createVirtualRegister(RC);
10553       RegInfo.addLiveIn(ArgRegs[I], Reg);
10554       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10555       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10556       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10557       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10558                                    MachinePointerInfo::getFixedStack(MF, FI));
10559       cast<StoreSDNode>(Store.getNode())
10560           ->getMemOperand()
10561           ->setValue((Value *)nullptr);
10562       OutChains.push_back(Store);
10563     }
10564     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10565   }
10566 
10567   // All stores are grouped in one node to allow the matching between
10568   // the size of Ins and InVals. This only happens for vararg functions.
10569   if (!OutChains.empty()) {
10570     OutChains.push_back(Chain);
10571     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10572   }
10573 
10574   return Chain;
10575 }
10576 
10577 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10578 /// for tail call optimization.
10579 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10580 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10581     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10582     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10583 
10584   auto &Callee = CLI.Callee;
10585   auto CalleeCC = CLI.CallConv;
10586   auto &Outs = CLI.Outs;
10587   auto &Caller = MF.getFunction();
10588   auto CallerCC = Caller.getCallingConv();
10589 
10590   // Exception-handling functions need a special set of instructions to
10591   // indicate a return to the hardware. Tail-calling another function would
10592   // probably break this.
10593   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10594   // should be expanded as new function attributes are introduced.
10595   if (Caller.hasFnAttribute("interrupt"))
10596     return false;
10597 
10598   // Do not tail call opt if the stack is used to pass parameters.
10599   if (CCInfo.getNextStackOffset() != 0)
10600     return false;
10601 
10602   // Do not tail call opt if any parameters need to be passed indirectly.
10603   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10604   // passed indirectly. So the address of the value will be passed in a
10605   // register, or if not available, then the address is put on the stack. In
10606   // order to pass indirectly, space on the stack often needs to be allocated
10607   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10608   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10609   // are passed CCValAssign::Indirect.
10610   for (auto &VA : ArgLocs)
10611     if (VA.getLocInfo() == CCValAssign::Indirect)
10612       return false;
10613 
10614   // Do not tail call opt if either caller or callee uses struct return
10615   // semantics.
10616   auto IsCallerStructRet = Caller.hasStructRetAttr();
10617   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10618   if (IsCallerStructRet || IsCalleeStructRet)
10619     return false;
10620 
10621   // Externally-defined functions with weak linkage should not be
10622   // tail-called. The behaviour of branch instructions in this situation (as
10623   // used for tail calls) is implementation-defined, so we cannot rely on the
10624   // linker replacing the tail call with a return.
10625   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10626     const GlobalValue *GV = G->getGlobal();
10627     if (GV->hasExternalWeakLinkage())
10628       return false;
10629   }
10630 
10631   // The callee has to preserve all registers the caller needs to preserve.
10632   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10633   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10634   if (CalleeCC != CallerCC) {
10635     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10636     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10637       return false;
10638   }
10639 
10640   // Byval parameters hand the function a pointer directly into the stack area
10641   // we want to reuse during a tail call. Working around this *is* possible
10642   // but less efficient and uglier in LowerCall.
10643   for (auto &Arg : Outs)
10644     if (Arg.Flags.isByVal())
10645       return false;
10646 
10647   return true;
10648 }
10649 
10650 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10651   return DAG.getDataLayout().getPrefTypeAlign(
10652       VT.getTypeForEVT(*DAG.getContext()));
10653 }
10654 
10655 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10656 // and output parameter nodes.
10657 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10658                                        SmallVectorImpl<SDValue> &InVals) const {
10659   SelectionDAG &DAG = CLI.DAG;
10660   SDLoc &DL = CLI.DL;
10661   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10662   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10663   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10664   SDValue Chain = CLI.Chain;
10665   SDValue Callee = CLI.Callee;
10666   bool &IsTailCall = CLI.IsTailCall;
10667   CallingConv::ID CallConv = CLI.CallConv;
10668   bool IsVarArg = CLI.IsVarArg;
10669   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10670   MVT XLenVT = Subtarget.getXLenVT();
10671 
10672   MachineFunction &MF = DAG.getMachineFunction();
10673 
10674   // Analyze the operands of the call, assigning locations to each operand.
10675   SmallVector<CCValAssign, 16> ArgLocs;
10676   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10677 
10678   if (CallConv == CallingConv::GHC)
10679     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10680   else
10681     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10682                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10683                                                     : CC_RISCV);
10684 
10685   // Check if it's really possible to do a tail call.
10686   if (IsTailCall)
10687     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10688 
10689   if (IsTailCall)
10690     ++NumTailCalls;
10691   else if (CLI.CB && CLI.CB->isMustTailCall())
10692     report_fatal_error("failed to perform tail call elimination on a call "
10693                        "site marked musttail");
10694 
10695   // Get a count of how many bytes are to be pushed on the stack.
10696   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10697 
10698   // Create local copies for byval args
10699   SmallVector<SDValue, 8> ByValArgs;
10700   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10701     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10702     if (!Flags.isByVal())
10703       continue;
10704 
10705     SDValue Arg = OutVals[i];
10706     unsigned Size = Flags.getByValSize();
10707     Align Alignment = Flags.getNonZeroByValAlign();
10708 
10709     int FI =
10710         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10711     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10712     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10713 
10714     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10715                           /*IsVolatile=*/false,
10716                           /*AlwaysInline=*/false, IsTailCall,
10717                           MachinePointerInfo(), MachinePointerInfo());
10718     ByValArgs.push_back(FIPtr);
10719   }
10720 
10721   if (!IsTailCall)
10722     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10723 
10724   // Copy argument values to their designated locations.
10725   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10726   SmallVector<SDValue, 8> MemOpChains;
10727   SDValue StackPtr;
10728   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10729     CCValAssign &VA = ArgLocs[i];
10730     SDValue ArgValue = OutVals[i];
10731     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10732 
10733     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10734     bool IsF64OnRV32DSoftABI =
10735         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10736     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10737       SDValue SplitF64 = DAG.getNode(
10738           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10739       SDValue Lo = SplitF64.getValue(0);
10740       SDValue Hi = SplitF64.getValue(1);
10741 
10742       Register RegLo = VA.getLocReg();
10743       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10744 
10745       if (RegLo == RISCV::X17) {
10746         // Second half of f64 is passed on the stack.
10747         // Work out the address of the stack slot.
10748         if (!StackPtr.getNode())
10749           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10750         // Emit the store.
10751         MemOpChains.push_back(
10752             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10753       } else {
10754         // Second half of f64 is passed in another GPR.
10755         assert(RegLo < RISCV::X31 && "Invalid register pair");
10756         Register RegHigh = RegLo + 1;
10757         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10758       }
10759       continue;
10760     }
10761 
10762     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10763     // as any other MemLoc.
10764 
10765     // Promote the value if needed.
10766     // For now, only handle fully promoted and indirect arguments.
10767     if (VA.getLocInfo() == CCValAssign::Indirect) {
10768       // Store the argument in a stack slot and pass its address.
10769       Align StackAlign =
10770           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10771                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10772       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10773       // If the original argument was split (e.g. i128), we need
10774       // to store the required parts of it here (and pass just one address).
10775       // Vectors may be partly split to registers and partly to the stack, in
10776       // which case the base address is partly offset and subsequent stores are
10777       // relative to that.
10778       unsigned ArgIndex = Outs[i].OrigArgIndex;
10779       unsigned ArgPartOffset = Outs[i].PartOffset;
10780       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10781       // Calculate the total size to store. We don't have access to what we're
10782       // actually storing other than performing the loop and collecting the
10783       // info.
10784       SmallVector<std::pair<SDValue, SDValue>> Parts;
10785       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10786         SDValue PartValue = OutVals[i + 1];
10787         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10788         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10789         EVT PartVT = PartValue.getValueType();
10790         if (PartVT.isScalableVector())
10791           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10792         StoredSize += PartVT.getStoreSize();
10793         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10794         Parts.push_back(std::make_pair(PartValue, Offset));
10795         ++i;
10796       }
10797       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10798       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10799       MemOpChains.push_back(
10800           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10801                        MachinePointerInfo::getFixedStack(MF, FI)));
10802       for (const auto &Part : Parts) {
10803         SDValue PartValue = Part.first;
10804         SDValue PartOffset = Part.second;
10805         SDValue Address =
10806             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10807         MemOpChains.push_back(
10808             DAG.getStore(Chain, DL, PartValue, Address,
10809                          MachinePointerInfo::getFixedStack(MF, FI)));
10810       }
10811       ArgValue = SpillSlot;
10812     } else {
10813       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10814     }
10815 
10816     // Use local copy if it is a byval arg.
10817     if (Flags.isByVal())
10818       ArgValue = ByValArgs[j++];
10819 
10820     if (VA.isRegLoc()) {
10821       // Queue up the argument copies and emit them at the end.
10822       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10823     } else {
10824       assert(VA.isMemLoc() && "Argument not register or memory");
10825       assert(!IsTailCall && "Tail call not allowed if stack is used "
10826                             "for passing parameters");
10827 
10828       // Work out the address of the stack slot.
10829       if (!StackPtr.getNode())
10830         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10831       SDValue Address =
10832           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10833                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10834 
10835       // Emit the store.
10836       MemOpChains.push_back(
10837           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10838     }
10839   }
10840 
10841   // Join the stores, which are independent of one another.
10842   if (!MemOpChains.empty())
10843     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10844 
10845   SDValue Glue;
10846 
10847   // Build a sequence of copy-to-reg nodes, chained and glued together.
10848   for (auto &Reg : RegsToPass) {
10849     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10850     Glue = Chain.getValue(1);
10851   }
10852 
10853   // Validate that none of the argument registers have been marked as
10854   // reserved, if so report an error. Do the same for the return address if this
10855   // is not a tailcall.
10856   validateCCReservedRegs(RegsToPass, MF);
10857   if (!IsTailCall &&
10858       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10859     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10860         MF.getFunction(),
10861         "Return address register required, but has been reserved."});
10862 
10863   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10864   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10865   // split it and then direct call can be matched by PseudoCALL.
10866   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10867     const GlobalValue *GV = S->getGlobal();
10868 
10869     unsigned OpFlags = RISCVII::MO_CALL;
10870     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10871       OpFlags = RISCVII::MO_PLT;
10872 
10873     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10874   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10875     unsigned OpFlags = RISCVII::MO_CALL;
10876 
10877     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10878                                                  nullptr))
10879       OpFlags = RISCVII::MO_PLT;
10880 
10881     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10882   }
10883 
10884   // The first call operand is the chain and the second is the target address.
10885   SmallVector<SDValue, 8> Ops;
10886   Ops.push_back(Chain);
10887   Ops.push_back(Callee);
10888 
10889   // Add argument registers to the end of the list so that they are
10890   // known live into the call.
10891   for (auto &Reg : RegsToPass)
10892     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10893 
10894   if (!IsTailCall) {
10895     // Add a register mask operand representing the call-preserved registers.
10896     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10897     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10898     assert(Mask && "Missing call preserved mask for calling convention");
10899     Ops.push_back(DAG.getRegisterMask(Mask));
10900   }
10901 
10902   // Glue the call to the argument copies, if any.
10903   if (Glue.getNode())
10904     Ops.push_back(Glue);
10905 
10906   // Emit the call.
10907   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10908 
10909   if (IsTailCall) {
10910     MF.getFrameInfo().setHasTailCall();
10911     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10912   }
10913 
10914   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10915   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10916   Glue = Chain.getValue(1);
10917 
10918   // Mark the end of the call, which is glued to the call itself.
10919   Chain = DAG.getCALLSEQ_END(Chain,
10920                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10921                              DAG.getConstant(0, DL, PtrVT, true),
10922                              Glue, DL);
10923   Glue = Chain.getValue(1);
10924 
10925   // Assign locations to each value returned by this call.
10926   SmallVector<CCValAssign, 16> RVLocs;
10927   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10928   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10929 
10930   // Copy all of the result registers out of their specified physreg.
10931   for (auto &VA : RVLocs) {
10932     // Copy the value out
10933     SDValue RetValue =
10934         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10935     // Glue the RetValue to the end of the call sequence
10936     Chain = RetValue.getValue(1);
10937     Glue = RetValue.getValue(2);
10938 
10939     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10940       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10941       SDValue RetValue2 =
10942           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10943       Chain = RetValue2.getValue(1);
10944       Glue = RetValue2.getValue(2);
10945       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10946                              RetValue2);
10947     }
10948 
10949     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10950 
10951     InVals.push_back(RetValue);
10952   }
10953 
10954   return Chain;
10955 }
10956 
10957 bool RISCVTargetLowering::CanLowerReturn(
10958     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10959     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10960   SmallVector<CCValAssign, 16> RVLocs;
10961   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10962 
10963   Optional<unsigned> FirstMaskArgument;
10964   if (Subtarget.hasVInstructions())
10965     FirstMaskArgument = preAssignMask(Outs);
10966 
10967   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10968     MVT VT = Outs[i].VT;
10969     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10970     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10971     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10972                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10973                  *this, FirstMaskArgument))
10974       return false;
10975   }
10976   return true;
10977 }
10978 
10979 SDValue
10980 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10981                                  bool IsVarArg,
10982                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10983                                  const SmallVectorImpl<SDValue> &OutVals,
10984                                  const SDLoc &DL, SelectionDAG &DAG) const {
10985   const MachineFunction &MF = DAG.getMachineFunction();
10986   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10987 
10988   // Stores the assignment of the return value to a location.
10989   SmallVector<CCValAssign, 16> RVLocs;
10990 
10991   // Info about the registers and stack slot.
10992   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10993                  *DAG.getContext());
10994 
10995   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10996                     nullptr, CC_RISCV);
10997 
10998   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10999     report_fatal_error("GHC functions return void only");
11000 
11001   SDValue Glue;
11002   SmallVector<SDValue, 4> RetOps(1, Chain);
11003 
11004   // Copy the result values into the output registers.
11005   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11006     SDValue Val = OutVals[i];
11007     CCValAssign &VA = RVLocs[i];
11008     assert(VA.isRegLoc() && "Can only return in registers!");
11009 
11010     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11011       // Handle returning f64 on RV32D with a soft float ABI.
11012       assert(VA.isRegLoc() && "Expected return via registers");
11013       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11014                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11015       SDValue Lo = SplitF64.getValue(0);
11016       SDValue Hi = SplitF64.getValue(1);
11017       Register RegLo = VA.getLocReg();
11018       assert(RegLo < RISCV::X31 && "Invalid register pair");
11019       Register RegHi = RegLo + 1;
11020 
11021       if (STI.isRegisterReservedByUser(RegLo) ||
11022           STI.isRegisterReservedByUser(RegHi))
11023         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11024             MF.getFunction(),
11025             "Return value register required, but has been reserved."});
11026 
11027       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11028       Glue = Chain.getValue(1);
11029       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11030       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11031       Glue = Chain.getValue(1);
11032       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11033     } else {
11034       // Handle a 'normal' return.
11035       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11036       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11037 
11038       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11039         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11040             MF.getFunction(),
11041             "Return value register required, but has been reserved."});
11042 
11043       // Guarantee that all emitted copies are stuck together.
11044       Glue = Chain.getValue(1);
11045       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11046     }
11047   }
11048 
11049   RetOps[0] = Chain; // Update chain.
11050 
11051   // Add the glue node if we have it.
11052   if (Glue.getNode()) {
11053     RetOps.push_back(Glue);
11054   }
11055 
11056   unsigned RetOpc = RISCVISD::RET_FLAG;
11057   // Interrupt service routines use different return instructions.
11058   const Function &Func = DAG.getMachineFunction().getFunction();
11059   if (Func.hasFnAttribute("interrupt")) {
11060     if (!Func.getReturnType()->isVoidTy())
11061       report_fatal_error(
11062           "Functions with the interrupt attribute must have void return type!");
11063 
11064     MachineFunction &MF = DAG.getMachineFunction();
11065     StringRef Kind =
11066       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11067 
11068     if (Kind == "user")
11069       RetOpc = RISCVISD::URET_FLAG;
11070     else if (Kind == "supervisor")
11071       RetOpc = RISCVISD::SRET_FLAG;
11072     else
11073       RetOpc = RISCVISD::MRET_FLAG;
11074   }
11075 
11076   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11077 }
11078 
11079 void RISCVTargetLowering::validateCCReservedRegs(
11080     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11081     MachineFunction &MF) const {
11082   const Function &F = MF.getFunction();
11083   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11084 
11085   if (llvm::any_of(Regs, [&STI](auto Reg) {
11086         return STI.isRegisterReservedByUser(Reg.first);
11087       }))
11088     F.getContext().diagnose(DiagnosticInfoUnsupported{
11089         F, "Argument register required, but has been reserved."});
11090 }
11091 
11092 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11093   return CI->isTailCall();
11094 }
11095 
11096 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11097 #define NODE_NAME_CASE(NODE)                                                   \
11098   case RISCVISD::NODE:                                                         \
11099     return "RISCVISD::" #NODE;
11100   // clang-format off
11101   switch ((RISCVISD::NodeType)Opcode) {
11102   case RISCVISD::FIRST_NUMBER:
11103     break;
11104   NODE_NAME_CASE(RET_FLAG)
11105   NODE_NAME_CASE(URET_FLAG)
11106   NODE_NAME_CASE(SRET_FLAG)
11107   NODE_NAME_CASE(MRET_FLAG)
11108   NODE_NAME_CASE(CALL)
11109   NODE_NAME_CASE(SELECT_CC)
11110   NODE_NAME_CASE(BR_CC)
11111   NODE_NAME_CASE(BuildPairF64)
11112   NODE_NAME_CASE(SplitF64)
11113   NODE_NAME_CASE(TAIL)
11114   NODE_NAME_CASE(MULHSU)
11115   NODE_NAME_CASE(SLLW)
11116   NODE_NAME_CASE(SRAW)
11117   NODE_NAME_CASE(SRLW)
11118   NODE_NAME_CASE(DIVW)
11119   NODE_NAME_CASE(DIVUW)
11120   NODE_NAME_CASE(REMUW)
11121   NODE_NAME_CASE(ROLW)
11122   NODE_NAME_CASE(RORW)
11123   NODE_NAME_CASE(CLZW)
11124   NODE_NAME_CASE(CTZW)
11125   NODE_NAME_CASE(FSLW)
11126   NODE_NAME_CASE(FSRW)
11127   NODE_NAME_CASE(FSL)
11128   NODE_NAME_CASE(FSR)
11129   NODE_NAME_CASE(FMV_H_X)
11130   NODE_NAME_CASE(FMV_X_ANYEXTH)
11131   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11132   NODE_NAME_CASE(FMV_W_X_RV64)
11133   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11134   NODE_NAME_CASE(FCVT_X)
11135   NODE_NAME_CASE(FCVT_XU)
11136   NODE_NAME_CASE(FCVT_W_RV64)
11137   NODE_NAME_CASE(FCVT_WU_RV64)
11138   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11139   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11140   NODE_NAME_CASE(READ_CYCLE_WIDE)
11141   NODE_NAME_CASE(GREV)
11142   NODE_NAME_CASE(GREVW)
11143   NODE_NAME_CASE(GORC)
11144   NODE_NAME_CASE(GORCW)
11145   NODE_NAME_CASE(SHFL)
11146   NODE_NAME_CASE(SHFLW)
11147   NODE_NAME_CASE(UNSHFL)
11148   NODE_NAME_CASE(UNSHFLW)
11149   NODE_NAME_CASE(BFP)
11150   NODE_NAME_CASE(BFPW)
11151   NODE_NAME_CASE(BCOMPRESS)
11152   NODE_NAME_CASE(BCOMPRESSW)
11153   NODE_NAME_CASE(BDECOMPRESS)
11154   NODE_NAME_CASE(BDECOMPRESSW)
11155   NODE_NAME_CASE(VMV_V_X_VL)
11156   NODE_NAME_CASE(VFMV_V_F_VL)
11157   NODE_NAME_CASE(VMV_X_S)
11158   NODE_NAME_CASE(VMV_S_X_VL)
11159   NODE_NAME_CASE(VFMV_S_F_VL)
11160   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11161   NODE_NAME_CASE(READ_VLENB)
11162   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11163   NODE_NAME_CASE(VSLIDEUP_VL)
11164   NODE_NAME_CASE(VSLIDE1UP_VL)
11165   NODE_NAME_CASE(VSLIDEDOWN_VL)
11166   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11167   NODE_NAME_CASE(VID_VL)
11168   NODE_NAME_CASE(VFNCVT_ROD_VL)
11169   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11170   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11171   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11172   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11173   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11174   NODE_NAME_CASE(VECREDUCE_AND_VL)
11175   NODE_NAME_CASE(VECREDUCE_OR_VL)
11176   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11177   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11178   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11179   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11180   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11181   NODE_NAME_CASE(ADD_VL)
11182   NODE_NAME_CASE(AND_VL)
11183   NODE_NAME_CASE(MUL_VL)
11184   NODE_NAME_CASE(OR_VL)
11185   NODE_NAME_CASE(SDIV_VL)
11186   NODE_NAME_CASE(SHL_VL)
11187   NODE_NAME_CASE(SREM_VL)
11188   NODE_NAME_CASE(SRA_VL)
11189   NODE_NAME_CASE(SRL_VL)
11190   NODE_NAME_CASE(SUB_VL)
11191   NODE_NAME_CASE(UDIV_VL)
11192   NODE_NAME_CASE(UREM_VL)
11193   NODE_NAME_CASE(XOR_VL)
11194   NODE_NAME_CASE(SADDSAT_VL)
11195   NODE_NAME_CASE(UADDSAT_VL)
11196   NODE_NAME_CASE(SSUBSAT_VL)
11197   NODE_NAME_CASE(USUBSAT_VL)
11198   NODE_NAME_CASE(FADD_VL)
11199   NODE_NAME_CASE(FSUB_VL)
11200   NODE_NAME_CASE(FMUL_VL)
11201   NODE_NAME_CASE(FDIV_VL)
11202   NODE_NAME_CASE(FNEG_VL)
11203   NODE_NAME_CASE(FABS_VL)
11204   NODE_NAME_CASE(FSQRT_VL)
11205   NODE_NAME_CASE(FMA_VL)
11206   NODE_NAME_CASE(FCOPYSIGN_VL)
11207   NODE_NAME_CASE(SMIN_VL)
11208   NODE_NAME_CASE(SMAX_VL)
11209   NODE_NAME_CASE(UMIN_VL)
11210   NODE_NAME_CASE(UMAX_VL)
11211   NODE_NAME_CASE(FMINNUM_VL)
11212   NODE_NAME_CASE(FMAXNUM_VL)
11213   NODE_NAME_CASE(MULHS_VL)
11214   NODE_NAME_CASE(MULHU_VL)
11215   NODE_NAME_CASE(FP_TO_SINT_VL)
11216   NODE_NAME_CASE(FP_TO_UINT_VL)
11217   NODE_NAME_CASE(SINT_TO_FP_VL)
11218   NODE_NAME_CASE(UINT_TO_FP_VL)
11219   NODE_NAME_CASE(FP_EXTEND_VL)
11220   NODE_NAME_CASE(FP_ROUND_VL)
11221   NODE_NAME_CASE(VWMUL_VL)
11222   NODE_NAME_CASE(VWMULU_VL)
11223   NODE_NAME_CASE(VWMULSU_VL)
11224   NODE_NAME_CASE(VWADD_VL)
11225   NODE_NAME_CASE(VWADDU_VL)
11226   NODE_NAME_CASE(VWSUB_VL)
11227   NODE_NAME_CASE(VWSUBU_VL)
11228   NODE_NAME_CASE(VWADD_W_VL)
11229   NODE_NAME_CASE(VWADDU_W_VL)
11230   NODE_NAME_CASE(VWSUB_W_VL)
11231   NODE_NAME_CASE(VWSUBU_W_VL)
11232   NODE_NAME_CASE(SETCC_VL)
11233   NODE_NAME_CASE(VSELECT_VL)
11234   NODE_NAME_CASE(VP_MERGE_VL)
11235   NODE_NAME_CASE(VMAND_VL)
11236   NODE_NAME_CASE(VMOR_VL)
11237   NODE_NAME_CASE(VMXOR_VL)
11238   NODE_NAME_CASE(VMCLR_VL)
11239   NODE_NAME_CASE(VMSET_VL)
11240   NODE_NAME_CASE(VRGATHER_VX_VL)
11241   NODE_NAME_CASE(VRGATHER_VV_VL)
11242   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11243   NODE_NAME_CASE(VSEXT_VL)
11244   NODE_NAME_CASE(VZEXT_VL)
11245   NODE_NAME_CASE(VCPOP_VL)
11246   NODE_NAME_CASE(READ_CSR)
11247   NODE_NAME_CASE(WRITE_CSR)
11248   NODE_NAME_CASE(SWAP_CSR)
11249   }
11250   // clang-format on
11251   return nullptr;
11252 #undef NODE_NAME_CASE
11253 }
11254 
11255 /// getConstraintType - Given a constraint letter, return the type of
11256 /// constraint it is for this target.
11257 RISCVTargetLowering::ConstraintType
11258 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11259   if (Constraint.size() == 1) {
11260     switch (Constraint[0]) {
11261     default:
11262       break;
11263     case 'f':
11264       return C_RegisterClass;
11265     case 'I':
11266     case 'J':
11267     case 'K':
11268       return C_Immediate;
11269     case 'A':
11270       return C_Memory;
11271     case 'S': // A symbolic address
11272       return C_Other;
11273     }
11274   } else {
11275     if (Constraint == "vr" || Constraint == "vm")
11276       return C_RegisterClass;
11277   }
11278   return TargetLowering::getConstraintType(Constraint);
11279 }
11280 
11281 std::pair<unsigned, const TargetRegisterClass *>
11282 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11283                                                   StringRef Constraint,
11284                                                   MVT VT) const {
11285   // First, see if this is a constraint that directly corresponds to a
11286   // RISCV register class.
11287   if (Constraint.size() == 1) {
11288     switch (Constraint[0]) {
11289     case 'r':
11290       // TODO: Support fixed vectors up to XLen for P extension?
11291       if (VT.isVector())
11292         break;
11293       return std::make_pair(0U, &RISCV::GPRRegClass);
11294     case 'f':
11295       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11296         return std::make_pair(0U, &RISCV::FPR16RegClass);
11297       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11298         return std::make_pair(0U, &RISCV::FPR32RegClass);
11299       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11300         return std::make_pair(0U, &RISCV::FPR64RegClass);
11301       break;
11302     default:
11303       break;
11304     }
11305   } else if (Constraint == "vr") {
11306     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11307                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11308       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11309         return std::make_pair(0U, RC);
11310     }
11311   } else if (Constraint == "vm") {
11312     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11313       return std::make_pair(0U, &RISCV::VMV0RegClass);
11314   }
11315 
11316   // Clang will correctly decode the usage of register name aliases into their
11317   // official names. However, other frontends like `rustc` do not. This allows
11318   // users of these frontends to use the ABI names for registers in LLVM-style
11319   // register constraints.
11320   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11321                                .Case("{zero}", RISCV::X0)
11322                                .Case("{ra}", RISCV::X1)
11323                                .Case("{sp}", RISCV::X2)
11324                                .Case("{gp}", RISCV::X3)
11325                                .Case("{tp}", RISCV::X4)
11326                                .Case("{t0}", RISCV::X5)
11327                                .Case("{t1}", RISCV::X6)
11328                                .Case("{t2}", RISCV::X7)
11329                                .Cases("{s0}", "{fp}", RISCV::X8)
11330                                .Case("{s1}", RISCV::X9)
11331                                .Case("{a0}", RISCV::X10)
11332                                .Case("{a1}", RISCV::X11)
11333                                .Case("{a2}", RISCV::X12)
11334                                .Case("{a3}", RISCV::X13)
11335                                .Case("{a4}", RISCV::X14)
11336                                .Case("{a5}", RISCV::X15)
11337                                .Case("{a6}", RISCV::X16)
11338                                .Case("{a7}", RISCV::X17)
11339                                .Case("{s2}", RISCV::X18)
11340                                .Case("{s3}", RISCV::X19)
11341                                .Case("{s4}", RISCV::X20)
11342                                .Case("{s5}", RISCV::X21)
11343                                .Case("{s6}", RISCV::X22)
11344                                .Case("{s7}", RISCV::X23)
11345                                .Case("{s8}", RISCV::X24)
11346                                .Case("{s9}", RISCV::X25)
11347                                .Case("{s10}", RISCV::X26)
11348                                .Case("{s11}", RISCV::X27)
11349                                .Case("{t3}", RISCV::X28)
11350                                .Case("{t4}", RISCV::X29)
11351                                .Case("{t5}", RISCV::X30)
11352                                .Case("{t6}", RISCV::X31)
11353                                .Default(RISCV::NoRegister);
11354   if (XRegFromAlias != RISCV::NoRegister)
11355     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11356 
11357   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11358   // TableGen record rather than the AsmName to choose registers for InlineAsm
11359   // constraints, plus we want to match those names to the widest floating point
11360   // register type available, manually select floating point registers here.
11361   //
11362   // The second case is the ABI name of the register, so that frontends can also
11363   // use the ABI names in register constraint lists.
11364   if (Subtarget.hasStdExtF()) {
11365     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11366                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11367                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11368                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11369                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11370                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11371                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11372                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11373                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11374                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11375                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11376                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11377                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11378                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11379                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11380                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11381                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11382                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11383                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11384                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11385                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11386                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11387                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11388                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11389                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11390                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11391                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11392                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11393                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11394                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11395                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11396                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11397                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11398                         .Default(RISCV::NoRegister);
11399     if (FReg != RISCV::NoRegister) {
11400       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11401       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11402         unsigned RegNo = FReg - RISCV::F0_F;
11403         unsigned DReg = RISCV::F0_D + RegNo;
11404         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11405       }
11406       if (VT == MVT::f32 || VT == MVT::Other)
11407         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11408       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11409         unsigned RegNo = FReg - RISCV::F0_F;
11410         unsigned HReg = RISCV::F0_H + RegNo;
11411         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11412       }
11413     }
11414   }
11415 
11416   if (Subtarget.hasVInstructions()) {
11417     Register VReg = StringSwitch<Register>(Constraint.lower())
11418                         .Case("{v0}", RISCV::V0)
11419                         .Case("{v1}", RISCV::V1)
11420                         .Case("{v2}", RISCV::V2)
11421                         .Case("{v3}", RISCV::V3)
11422                         .Case("{v4}", RISCV::V4)
11423                         .Case("{v5}", RISCV::V5)
11424                         .Case("{v6}", RISCV::V6)
11425                         .Case("{v7}", RISCV::V7)
11426                         .Case("{v8}", RISCV::V8)
11427                         .Case("{v9}", RISCV::V9)
11428                         .Case("{v10}", RISCV::V10)
11429                         .Case("{v11}", RISCV::V11)
11430                         .Case("{v12}", RISCV::V12)
11431                         .Case("{v13}", RISCV::V13)
11432                         .Case("{v14}", RISCV::V14)
11433                         .Case("{v15}", RISCV::V15)
11434                         .Case("{v16}", RISCV::V16)
11435                         .Case("{v17}", RISCV::V17)
11436                         .Case("{v18}", RISCV::V18)
11437                         .Case("{v19}", RISCV::V19)
11438                         .Case("{v20}", RISCV::V20)
11439                         .Case("{v21}", RISCV::V21)
11440                         .Case("{v22}", RISCV::V22)
11441                         .Case("{v23}", RISCV::V23)
11442                         .Case("{v24}", RISCV::V24)
11443                         .Case("{v25}", RISCV::V25)
11444                         .Case("{v26}", RISCV::V26)
11445                         .Case("{v27}", RISCV::V27)
11446                         .Case("{v28}", RISCV::V28)
11447                         .Case("{v29}", RISCV::V29)
11448                         .Case("{v30}", RISCV::V30)
11449                         .Case("{v31}", RISCV::V31)
11450                         .Default(RISCV::NoRegister);
11451     if (VReg != RISCV::NoRegister) {
11452       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11453         return std::make_pair(VReg, &RISCV::VMRegClass);
11454       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11455         return std::make_pair(VReg, &RISCV::VRRegClass);
11456       for (const auto *RC :
11457            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11458         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11459           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11460           return std::make_pair(VReg, RC);
11461         }
11462       }
11463     }
11464   }
11465 
11466   std::pair<Register, const TargetRegisterClass *> Res =
11467       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11468 
11469   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11470   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11471   // Subtarget into account.
11472   if (Res.second == &RISCV::GPRF16RegClass ||
11473       Res.second == &RISCV::GPRF32RegClass ||
11474       Res.second == &RISCV::GPRF64RegClass)
11475     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11476 
11477   return Res;
11478 }
11479 
11480 unsigned
11481 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11482   // Currently only support length 1 constraints.
11483   if (ConstraintCode.size() == 1) {
11484     switch (ConstraintCode[0]) {
11485     case 'A':
11486       return InlineAsm::Constraint_A;
11487     default:
11488       break;
11489     }
11490   }
11491 
11492   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11493 }
11494 
11495 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11496     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11497     SelectionDAG &DAG) const {
11498   // Currently only support length 1 constraints.
11499   if (Constraint.length() == 1) {
11500     switch (Constraint[0]) {
11501     case 'I':
11502       // Validate & create a 12-bit signed immediate operand.
11503       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11504         uint64_t CVal = C->getSExtValue();
11505         if (isInt<12>(CVal))
11506           Ops.push_back(
11507               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11508       }
11509       return;
11510     case 'J':
11511       // Validate & create an integer zero operand.
11512       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11513         if (C->getZExtValue() == 0)
11514           Ops.push_back(
11515               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11516       return;
11517     case 'K':
11518       // Validate & create a 5-bit unsigned immediate operand.
11519       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11520         uint64_t CVal = C->getZExtValue();
11521         if (isUInt<5>(CVal))
11522           Ops.push_back(
11523               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11524       }
11525       return;
11526     case 'S':
11527       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11528         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11529                                                  GA->getValueType(0)));
11530       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11531         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11532                                                 BA->getValueType(0)));
11533       }
11534       return;
11535     default:
11536       break;
11537     }
11538   }
11539   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11540 }
11541 
11542 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11543                                                    Instruction *Inst,
11544                                                    AtomicOrdering Ord) const {
11545   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11546     return Builder.CreateFence(Ord);
11547   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11548     return Builder.CreateFence(AtomicOrdering::Release);
11549   return nullptr;
11550 }
11551 
11552 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11553                                                     Instruction *Inst,
11554                                                     AtomicOrdering Ord) const {
11555   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11556     return Builder.CreateFence(AtomicOrdering::Acquire);
11557   return nullptr;
11558 }
11559 
11560 TargetLowering::AtomicExpansionKind
11561 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11562   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11563   // point operations can't be used in an lr/sc sequence without breaking the
11564   // forward-progress guarantee.
11565   if (AI->isFloatingPointOperation())
11566     return AtomicExpansionKind::CmpXChg;
11567 
11568   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11569   if (Size == 8 || Size == 16)
11570     return AtomicExpansionKind::MaskedIntrinsic;
11571   return AtomicExpansionKind::None;
11572 }
11573 
11574 static Intrinsic::ID
11575 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11576   if (XLen == 32) {
11577     switch (BinOp) {
11578     default:
11579       llvm_unreachable("Unexpected AtomicRMW BinOp");
11580     case AtomicRMWInst::Xchg:
11581       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11582     case AtomicRMWInst::Add:
11583       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11584     case AtomicRMWInst::Sub:
11585       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11586     case AtomicRMWInst::Nand:
11587       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11588     case AtomicRMWInst::Max:
11589       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11590     case AtomicRMWInst::Min:
11591       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11592     case AtomicRMWInst::UMax:
11593       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11594     case AtomicRMWInst::UMin:
11595       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11596     }
11597   }
11598 
11599   if (XLen == 64) {
11600     switch (BinOp) {
11601     default:
11602       llvm_unreachable("Unexpected AtomicRMW BinOp");
11603     case AtomicRMWInst::Xchg:
11604       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11605     case AtomicRMWInst::Add:
11606       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11607     case AtomicRMWInst::Sub:
11608       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11609     case AtomicRMWInst::Nand:
11610       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11611     case AtomicRMWInst::Max:
11612       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11613     case AtomicRMWInst::Min:
11614       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11615     case AtomicRMWInst::UMax:
11616       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11617     case AtomicRMWInst::UMin:
11618       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11619     }
11620   }
11621 
11622   llvm_unreachable("Unexpected XLen\n");
11623 }
11624 
11625 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11626     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11627     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11628   unsigned XLen = Subtarget.getXLen();
11629   Value *Ordering =
11630       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11631   Type *Tys[] = {AlignedAddr->getType()};
11632   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11633       AI->getModule(),
11634       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11635 
11636   if (XLen == 64) {
11637     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11638     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11639     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11640   }
11641 
11642   Value *Result;
11643 
11644   // Must pass the shift amount needed to sign extend the loaded value prior
11645   // to performing a signed comparison for min/max. ShiftAmt is the number of
11646   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11647   // is the number of bits to left+right shift the value in order to
11648   // sign-extend.
11649   if (AI->getOperation() == AtomicRMWInst::Min ||
11650       AI->getOperation() == AtomicRMWInst::Max) {
11651     const DataLayout &DL = AI->getModule()->getDataLayout();
11652     unsigned ValWidth =
11653         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11654     Value *SextShamt =
11655         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11656     Result = Builder.CreateCall(LrwOpScwLoop,
11657                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11658   } else {
11659     Result =
11660         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11661   }
11662 
11663   if (XLen == 64)
11664     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11665   return Result;
11666 }
11667 
11668 TargetLowering::AtomicExpansionKind
11669 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11670     AtomicCmpXchgInst *CI) const {
11671   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11672   if (Size == 8 || Size == 16)
11673     return AtomicExpansionKind::MaskedIntrinsic;
11674   return AtomicExpansionKind::None;
11675 }
11676 
11677 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11678     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11679     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11680   unsigned XLen = Subtarget.getXLen();
11681   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11682   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11683   if (XLen == 64) {
11684     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11685     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11686     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11687     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11688   }
11689   Type *Tys[] = {AlignedAddr->getType()};
11690   Function *MaskedCmpXchg =
11691       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11692   Value *Result = Builder.CreateCall(
11693       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11694   if (XLen == 64)
11695     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11696   return Result;
11697 }
11698 
11699 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
11700                                                         EVT DataVT) const {
11701   return false;
11702 }
11703 
11704 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11705                                                EVT VT) const {
11706   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11707     return false;
11708 
11709   switch (FPVT.getSimpleVT().SimpleTy) {
11710   case MVT::f16:
11711     return Subtarget.hasStdExtZfh();
11712   case MVT::f32:
11713     return Subtarget.hasStdExtF();
11714   case MVT::f64:
11715     return Subtarget.hasStdExtD();
11716   default:
11717     return false;
11718   }
11719 }
11720 
11721 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11722   // If we are using the small code model, we can reduce size of jump table
11723   // entry to 4 bytes.
11724   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11725       getTargetMachine().getCodeModel() == CodeModel::Small) {
11726     return MachineJumpTableInfo::EK_Custom32;
11727   }
11728   return TargetLowering::getJumpTableEncoding();
11729 }
11730 
11731 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11732     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11733     unsigned uid, MCContext &Ctx) const {
11734   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11735          getTargetMachine().getCodeModel() == CodeModel::Small);
11736   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11737 }
11738 
11739 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11740                                                      EVT VT) const {
11741   VT = VT.getScalarType();
11742 
11743   if (!VT.isSimple())
11744     return false;
11745 
11746   switch (VT.getSimpleVT().SimpleTy) {
11747   case MVT::f16:
11748     return Subtarget.hasStdExtZfh();
11749   case MVT::f32:
11750     return Subtarget.hasStdExtF();
11751   case MVT::f64:
11752     return Subtarget.hasStdExtD();
11753   default:
11754     break;
11755   }
11756 
11757   return false;
11758 }
11759 
11760 Register RISCVTargetLowering::getExceptionPointerRegister(
11761     const Constant *PersonalityFn) const {
11762   return RISCV::X10;
11763 }
11764 
11765 Register RISCVTargetLowering::getExceptionSelectorRegister(
11766     const Constant *PersonalityFn) const {
11767   return RISCV::X11;
11768 }
11769 
11770 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11771   // Return false to suppress the unnecessary extensions if the LibCall
11772   // arguments or return value is f32 type for LP64 ABI.
11773   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11774   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11775     return false;
11776 
11777   return true;
11778 }
11779 
11780 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11781   if (Subtarget.is64Bit() && Type == MVT::i32)
11782     return true;
11783 
11784   return IsSigned;
11785 }
11786 
11787 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11788                                                  SDValue C) const {
11789   // Check integral scalar types.
11790   if (VT.isScalarInteger()) {
11791     // Omit the optimization if the sub target has the M extension and the data
11792     // size exceeds XLen.
11793     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11794       return false;
11795     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11796       // Break the MUL to a SLLI and an ADD/SUB.
11797       const APInt &Imm = ConstNode->getAPIntValue();
11798       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11799           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11800         return true;
11801       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11802       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11803           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11804            (Imm - 8).isPowerOf2()))
11805         return true;
11806       // Omit the following optimization if the sub target has the M extension
11807       // and the data size >= XLen.
11808       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11809         return false;
11810       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11811       // a pair of LUI/ADDI.
11812       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11813         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11814         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11815             (1 - ImmS).isPowerOf2())
11816         return true;
11817       }
11818     }
11819   }
11820 
11821   return false;
11822 }
11823 
11824 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11825                                                       SDValue ConstNode) const {
11826   // Let the DAGCombiner decide for vectors.
11827   EVT VT = AddNode.getValueType();
11828   if (VT.isVector())
11829     return true;
11830 
11831   // Let the DAGCombiner decide for larger types.
11832   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11833     return true;
11834 
11835   // It is worse if c1 is simm12 while c1*c2 is not.
11836   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11837   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11838   const APInt &C1 = C1Node->getAPIntValue();
11839   const APInt &C2 = C2Node->getAPIntValue();
11840   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11841     return false;
11842 
11843   // Default to true and let the DAGCombiner decide.
11844   return true;
11845 }
11846 
11847 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11848     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11849     bool *Fast) const {
11850   if (!VT.isVector()) {
11851     if (Fast)
11852       *Fast = false;
11853     return Subtarget.enableUnalignedScalarMem();
11854   }
11855 
11856   // All vector implementations must support element alignment
11857   EVT ElemVT = VT.getVectorElementType();
11858   if (Alignment >= ElemVT.getStoreSize()) {
11859     if (Fast)
11860       *Fast = true;
11861     return true;
11862   }
11863 
11864   return false;
11865 }
11866 
11867 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11868     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11869     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11870   bool IsABIRegCopy = CC.hasValue();
11871   EVT ValueVT = Val.getValueType();
11872   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11873     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11874     // and cast to f32.
11875     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11876     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11877     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11878                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11879     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11880     Parts[0] = Val;
11881     return true;
11882   }
11883 
11884   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11885     LLVMContext &Context = *DAG.getContext();
11886     EVT ValueEltVT = ValueVT.getVectorElementType();
11887     EVT PartEltVT = PartVT.getVectorElementType();
11888     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11889     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11890     if (PartVTBitSize % ValueVTBitSize == 0) {
11891       assert(PartVTBitSize >= ValueVTBitSize);
11892       // If the element types are different, bitcast to the same element type of
11893       // PartVT first.
11894       // Give an example here, we want copy a <vscale x 1 x i8> value to
11895       // <vscale x 4 x i16>.
11896       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11897       // subvector, then we can bitcast to <vscale x 4 x i16>.
11898       if (ValueEltVT != PartEltVT) {
11899         if (PartVTBitSize > ValueVTBitSize) {
11900           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11901           assert(Count != 0 && "The number of element should not be zero.");
11902           EVT SameEltTypeVT =
11903               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11904           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11905                             DAG.getUNDEF(SameEltTypeVT), Val,
11906                             DAG.getVectorIdxConstant(0, DL));
11907         }
11908         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11909       } else {
11910         Val =
11911             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11912                         Val, DAG.getVectorIdxConstant(0, DL));
11913       }
11914       Parts[0] = Val;
11915       return true;
11916     }
11917   }
11918   return false;
11919 }
11920 
11921 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11922     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11923     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11924   bool IsABIRegCopy = CC.hasValue();
11925   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11926     SDValue Val = Parts[0];
11927 
11928     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11929     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11930     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11931     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11932     return Val;
11933   }
11934 
11935   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11936     LLVMContext &Context = *DAG.getContext();
11937     SDValue Val = Parts[0];
11938     EVT ValueEltVT = ValueVT.getVectorElementType();
11939     EVT PartEltVT = PartVT.getVectorElementType();
11940     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11941     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11942     if (PartVTBitSize % ValueVTBitSize == 0) {
11943       assert(PartVTBitSize >= ValueVTBitSize);
11944       EVT SameEltTypeVT = ValueVT;
11945       // If the element types are different, convert it to the same element type
11946       // of PartVT.
11947       // Give an example here, we want copy a <vscale x 1 x i8> value from
11948       // <vscale x 4 x i16>.
11949       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11950       // then we can extract <vscale x 1 x i8>.
11951       if (ValueEltVT != PartEltVT) {
11952         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11953         assert(Count != 0 && "The number of element should not be zero.");
11954         SameEltTypeVT =
11955             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11956         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11957       }
11958       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11959                         DAG.getVectorIdxConstant(0, DL));
11960       return Val;
11961     }
11962   }
11963   return SDValue();
11964 }
11965 
11966 SDValue
11967 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11968                                    SelectionDAG &DAG,
11969                                    SmallVectorImpl<SDNode *> &Created) const {
11970   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11971   if (isIntDivCheap(N->getValueType(0), Attr))
11972     return SDValue(N, 0); // Lower SDIV as SDIV
11973 
11974   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11975          "Unexpected divisor!");
11976 
11977   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11978   if (!Subtarget.hasStdExtZbt())
11979     return SDValue();
11980 
11981   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11982   // Besides, more critical path instructions will be generated when dividing
11983   // by 2. So we keep using the original DAGs for these cases.
11984   unsigned Lg2 = Divisor.countTrailingZeros();
11985   if (Lg2 == 1 || Lg2 >= 12)
11986     return SDValue();
11987 
11988   // fold (sdiv X, pow2)
11989   EVT VT = N->getValueType(0);
11990   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11991     return SDValue();
11992 
11993   SDLoc DL(N);
11994   SDValue N0 = N->getOperand(0);
11995   SDValue Zero = DAG.getConstant(0, DL, VT);
11996   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11997 
11998   // Add (N0 < 0) ? Pow2 - 1 : 0;
11999   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12000   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12001   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12002 
12003   Created.push_back(Cmp.getNode());
12004   Created.push_back(Add.getNode());
12005   Created.push_back(Sel.getNode());
12006 
12007   // Divide by pow2.
12008   SDValue SRA =
12009       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12010 
12011   // If we're dividing by a positive value, we're done.  Otherwise, we must
12012   // negate the result.
12013   if (Divisor.isNonNegative())
12014     return SRA;
12015 
12016   Created.push_back(SRA.getNode());
12017   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12018 }
12019 
12020 #define GET_REGISTER_MATCHER
12021 #include "RISCVGenAsmMatcher.inc"
12022 
12023 Register
12024 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12025                                        const MachineFunction &MF) const {
12026   Register Reg = MatchRegisterAltName(RegName);
12027   if (Reg == RISCV::NoRegister)
12028     Reg = MatchRegisterName(RegName);
12029   if (Reg == RISCV::NoRegister)
12030     report_fatal_error(
12031         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12032   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12033   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12034     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12035                              StringRef(RegName) + "\"."));
12036   return Reg;
12037 }
12038 
12039 namespace llvm {
12040 namespace RISCVVIntrinsicsTable {
12041 
12042 #define GET_RISCVVIntrinsicsTable_IMPL
12043 #include "RISCVGenSearchableTables.inc"
12044 
12045 } // namespace RISCVVIntrinsicsTable
12046 
12047 } // namespace llvm
12048