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   if (!Subtarget.hasStdExtZbb())
191     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
192 
193   if (Subtarget.is64Bit()) {
194     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
195                        MVT::i32, Custom);
196 
197     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
198                        MVT::i32, Custom);
199   } else {
200     setLibcallName(
201         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
202         nullptr);
203     setLibcallName(RTLIB::MULO_I64, nullptr);
204   }
205 
206   if (!Subtarget.hasStdExtM()) {
207     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
208                         ISD::SREM, ISD::UREM},
209                        XLenVT, Expand);
210   } else {
211     if (Subtarget.is64Bit()) {
212       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
213 
214       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
215                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
216     } else {
217       setOperationAction(ISD::MUL, MVT::i64, Custom);
218     }
219   }
220 
221   setOperationAction(
222       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
223       Expand);
224 
225   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
226                      Custom);
227 
228   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
229       Subtarget.hasStdExtZbkb()) {
230     if (Subtarget.is64Bit())
231       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
232   } else {
233     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
234   }
235 
236   if (Subtarget.hasStdExtZbp()) {
237     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
238     // more combining.
239     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
240 
241     // BSWAP i8 doesn't exist.
242     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
243 
244     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
245 
246     if (Subtarget.is64Bit())
247       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
248   } else {
249     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
250     // pattern match it directly in isel.
251     setOperationAction(ISD::BSWAP, XLenVT,
252                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
253                            ? Legal
254                            : Expand);
255     // Zbkb can use rev8+brev8 to implement bitreverse.
256     setOperationAction(ISD::BITREVERSE, XLenVT,
257                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
258   }
259 
260   if (Subtarget.hasStdExtZbb()) {
261     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
262                        Legal);
263 
264     if (Subtarget.is64Bit())
265       setOperationAction(
266           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
267           MVT::i32, Custom);
268   } else {
269     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
270 
271     if (Subtarget.is64Bit())
272       setOperationAction(ISD::ABS, MVT::i32, Custom);
273   }
274 
275   if (Subtarget.hasStdExtZbt()) {
276     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
277     setOperationAction(ISD::SELECT, XLenVT, Legal);
278 
279     if (Subtarget.is64Bit())
280       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
281   } else {
282     setOperationAction(ISD::SELECT, XLenVT, Custom);
283   }
284 
285   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
286       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
287       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
288       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
289       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
290       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
291       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
292 
293   static const ISD::CondCode FPCCToExpand[] = {
294       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
295       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
296       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
297 
298   static const ISD::NodeType FPOpToExpand[] = {
299       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
300       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
301 
302   if (Subtarget.hasStdExtZfh())
303     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
304 
305   if (Subtarget.hasStdExtZfh()) {
306     for (auto NT : FPLegalNodeTypes)
307       setOperationAction(NT, MVT::f16, Legal);
308     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
309     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
310     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
311     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
312     setOperationAction(ISD::SELECT, MVT::f16, Custom);
313     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
314 
315     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
316                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
317                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
318                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
319                         ISD::FLOG2, ISD::FLOG10},
320                        MVT::f16, Promote);
321 
322     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
323     // complete support for all operations in LegalizeDAG.
324 
325     // We need to custom promote this.
326     if (Subtarget.is64Bit())
327       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
328   }
329 
330   if (Subtarget.hasStdExtF()) {
331     for (auto NT : FPLegalNodeTypes)
332       setOperationAction(NT, MVT::f32, Legal);
333     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
334     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
335     setOperationAction(ISD::SELECT, MVT::f32, Custom);
336     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
337     for (auto Op : FPOpToExpand)
338       setOperationAction(Op, MVT::f32, Expand);
339     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
340     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
341   }
342 
343   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
344     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
345 
346   if (Subtarget.hasStdExtD()) {
347     for (auto NT : FPLegalNodeTypes)
348       setOperationAction(NT, MVT::f64, Legal);
349     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
350     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
351     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
352     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
353     setOperationAction(ISD::SELECT, MVT::f64, Custom);
354     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
355     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
356     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
357     for (auto Op : FPOpToExpand)
358       setOperationAction(Op, MVT::f64, Expand);
359     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
360     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
361   }
362 
363   if (Subtarget.is64Bit())
364     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
365                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
366                        MVT::i32, Custom);
367 
368   if (Subtarget.hasStdExtF()) {
369     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
370                        Custom);
371 
372     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
373                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
374                        XLenVT, Legal);
375 
376     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
377     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
378   }
379 
380   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
381                       ISD::JumpTable},
382                      XLenVT, Custom);
383 
384   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
385 
386   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
387   // Unfortunately this can't be determined just from the ISA naming string.
388   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
389                      Subtarget.is64Bit() ? Legal : Custom);
390 
391   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
392   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
393   if (Subtarget.is64Bit())
394     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
395 
396   if (Subtarget.hasStdExtA()) {
397     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
398     setMinCmpXchgSizeInBits(32);
399   } else {
400     setMaxAtomicSizeInBitsSupported(0);
401   }
402 
403   setBooleanContents(ZeroOrOneBooleanContent);
404 
405   if (Subtarget.hasVInstructions()) {
406     setBooleanVectorContents(ZeroOrOneBooleanContent);
407 
408     setOperationAction(ISD::VSCALE, XLenVT, Custom);
409 
410     // RVV intrinsics may have illegal operands.
411     // We also need to custom legalize vmv.x.s.
412     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
413                        {MVT::i8, MVT::i16}, Custom);
414     if (Subtarget.is64Bit())
415       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
416     else
417       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
418                          MVT::i64, Custom);
419 
420     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
421                        MVT::Other, Custom);
422 
423     static const unsigned IntegerVPOps[] = {
424         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
425         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
426         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
427         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
428         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
429         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
430         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
431         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
432         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
433         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
434 
435     static const unsigned FloatingPointVPOps[] = {
436         ISD::VP_FADD,        ISD::VP_FSUB,
437         ISD::VP_FMUL,        ISD::VP_FDIV,
438         ISD::VP_FNEG,        ISD::VP_FMA,
439         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
440         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
441         ISD::VP_MERGE,       ISD::VP_SELECT,
442         ISD::VP_SITOFP,      ISD::VP_UITOFP,
443         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
444         ISD::VP_FP_EXTEND};
445 
446     if (!Subtarget.is64Bit()) {
447       // We must custom-lower certain vXi64 operations on RV32 due to the vector
448       // element type being illegal.
449       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
450                          MVT::i64, Custom);
451 
452       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
453                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
454                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
455                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
456                          MVT::i64, Custom);
457 
458       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
459                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
460                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
461                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
462                          MVT::i64, Custom);
463     }
464 
465     for (MVT VT : BoolVecVTs) {
466       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
467 
468       // Mask VTs are custom-expanded into a series of standard nodes
469       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
470                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
471                          VT, Custom);
472 
473       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
474                          Custom);
475 
476       setOperationAction(ISD::SELECT, VT, Custom);
477       setOperationAction(
478           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
479           Expand);
480 
481       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
482 
483       setOperationAction(
484           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
485           Custom);
486 
487       setOperationAction(
488           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
489           Custom);
490 
491       // RVV has native int->float & float->int conversions where the
492       // element type sizes are within one power-of-two of each other. Any
493       // wider distances between type sizes have to be lowered as sequences
494       // which progressively narrow the gap in stages.
495       setOperationAction(
496           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
497           VT, Custom);
498 
499       // Expand all extending loads to types larger than this, and truncating
500       // stores from types larger than this.
501       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
502         setTruncStoreAction(OtherVT, VT, Expand);
503         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
504                          VT, Expand);
505       }
506 
507       setOperationAction(
508           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
509           Custom);
510     }
511 
512     for (MVT VT : IntVecVTs) {
513       if (VT.getVectorElementType() == MVT::i64 &&
514           !Subtarget.hasVInstructionsI64())
515         continue;
516 
517       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
518       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
519 
520       // Vectors implement MULHS/MULHU.
521       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
522 
523       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
524       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
525         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
526 
527       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
528                          Legal);
529 
530       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
531 
532       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
533                          Expand);
534 
535       setOperationAction(ISD::BSWAP, VT, Expand);
536 
537       // Custom-lower extensions and truncations from/to mask types.
538       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
539                          VT, Custom);
540 
541       // RVV has native int->float & float->int conversions where the
542       // element type sizes are within one power-of-two of each other. Any
543       // wider distances between type sizes have to be lowered as sequences
544       // which progressively narrow the gap in stages.
545       setOperationAction(
546           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
547           VT, Custom);
548 
549       setOperationAction(
550           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
551 
552       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
553       // nodes which truncate by one power of two at a time.
554       setOperationAction(ISD::TRUNCATE, VT, Custom);
555 
556       // Custom-lower insert/extract operations to simplify patterns.
557       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
558                          Custom);
559 
560       // Custom-lower reduction operations to set up the corresponding custom
561       // nodes' operands.
562       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
563                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
564                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
565                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
566                          VT, Custom);
567 
568       setOperationAction(IntegerVPOps, VT, Custom);
569 
570       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
571 
572       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
573                          VT, Custom);
574 
575       setOperationAction(
576           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
577           Custom);
578 
579       setOperationAction(
580           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
581           VT, Custom);
582 
583       setOperationAction(ISD::SELECT, VT, Custom);
584       setOperationAction(ISD::SELECT_CC, VT, Expand);
585 
586       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
587 
588       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
589         setTruncStoreAction(VT, OtherVT, Expand);
590         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
591                          VT, Expand);
592       }
593 
594       // Splice
595       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
596 
597       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
598       // type that can represent the value exactly.
599       if (VT.getVectorElementType() != MVT::i64) {
600         MVT FloatEltVT =
601             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
602         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
603         if (isTypeLegal(FloatVT)) {
604           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
605                              Custom);
606         }
607       }
608     }
609 
610     // Expand various CCs to best match the RVV ISA, which natively supports UNE
611     // but no other unordered comparisons, and supports all ordered comparisons
612     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
613     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
614     // and we pattern-match those back to the "original", swapping operands once
615     // more. This way we catch both operations and both "vf" and "fv" forms with
616     // fewer patterns.
617     static const ISD::CondCode VFPCCToExpand[] = {
618         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
619         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
620         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
621     };
622 
623     // Sets common operation actions on RVV floating-point vector types.
624     const auto SetCommonVFPActions = [&](MVT VT) {
625       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
626       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
627       // sizes are within one power-of-two of each other. Therefore conversions
628       // between vXf16 and vXf64 must be lowered as sequences which convert via
629       // vXf32.
630       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
631       // Custom-lower insert/extract operations to simplify patterns.
632       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
633                          Custom);
634       // Expand various condition codes (explained above).
635       setCondCodeAction(VFPCCToExpand, VT, Expand);
636 
637       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
638 
639       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
640                          VT, Custom);
641 
642       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
643                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
644                          VT, Custom);
645 
646       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
647 
648       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
649 
650       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
651                          VT, Custom);
652 
653       setOperationAction(
654           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
655           Custom);
656 
657       setOperationAction(ISD::SELECT, VT, Custom);
658       setOperationAction(ISD::SELECT_CC, VT, Expand);
659 
660       setOperationAction(
661           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
662           VT, Custom);
663 
664       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
665 
666       setOperationAction(FloatingPointVPOps, VT, Custom);
667     };
668 
669     // Sets common extload/truncstore actions on RVV floating-point vector
670     // types.
671     const auto SetCommonVFPExtLoadTruncStoreActions =
672         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
673           for (auto SmallVT : SmallerVTs) {
674             setTruncStoreAction(VT, SmallVT, Expand);
675             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
676           }
677         };
678 
679     if (Subtarget.hasVInstructionsF16())
680       for (MVT VT : F16VecVTs)
681         SetCommonVFPActions(VT);
682 
683     for (MVT VT : F32VecVTs) {
684       if (Subtarget.hasVInstructionsF32())
685         SetCommonVFPActions(VT);
686       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
687     }
688 
689     for (MVT VT : F64VecVTs) {
690       if (Subtarget.hasVInstructionsF64())
691         SetCommonVFPActions(VT);
692       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
693       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
694     }
695 
696     if (Subtarget.useRVVForFixedLengthVectors()) {
697       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
698         if (!useRVVForFixedLengthVectorVT(VT))
699           continue;
700 
701         // By default everything must be expanded.
702         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
703           setOperationAction(Op, VT, Expand);
704         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
705           setTruncStoreAction(VT, OtherVT, Expand);
706           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
707                            OtherVT, VT, Expand);
708         }
709 
710         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
711         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
712                            Custom);
713 
714         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
715                            Custom);
716 
717         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
718                            VT, Custom);
719 
720         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
721 
722         setOperationAction(ISD::SETCC, VT, Custom);
723 
724         setOperationAction(ISD::SELECT, VT, Custom);
725 
726         setOperationAction(ISD::TRUNCATE, VT, Custom);
727 
728         setOperationAction(ISD::BITCAST, VT, Custom);
729 
730         setOperationAction(
731             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
732             Custom);
733 
734         setOperationAction(
735             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
736             Custom);
737 
738         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
739                             ISD::FP_TO_UINT},
740                            VT, Custom);
741 
742         // Operations below are different for between masks and other vectors.
743         if (VT.getVectorElementType() == MVT::i1) {
744           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
745                               ISD::OR, ISD::XOR},
746                              VT, Custom);
747 
748           setOperationAction(
749               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
750               VT, Custom);
751           continue;
752         }
753 
754         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
755         // it before type legalization for i64 vectors on RV32. It will then be
756         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
757         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
758         // improvements first.
759         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
760           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
761           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
762         }
763 
764         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
765         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
766 
767         setOperationAction(
768             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
769 
770         setOperationAction(
771             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
772             Custom);
773 
774         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
775                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
776                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
777                            VT, Custom);
778 
779         setOperationAction(
780             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
781 
782         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
783         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
784           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
785 
786         setOperationAction(
787             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
788             Custom);
789 
790         setOperationAction(ISD::VSELECT, VT, Custom);
791         setOperationAction(ISD::SELECT_CC, VT, Expand);
792 
793         setOperationAction(
794             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
795 
796         // Custom-lower reduction operations to set up the corresponding custom
797         // nodes' operands.
798         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
799                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
800                             ISD::VECREDUCE_UMIN},
801                            VT, Custom);
802 
803         setOperationAction(IntegerVPOps, VT, Custom);
804 
805         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
806         // type that can represent the value exactly.
807         if (VT.getVectorElementType() != MVT::i64) {
808           MVT FloatEltVT =
809               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
810           EVT FloatVT =
811               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
812           if (isTypeLegal(FloatVT))
813             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
814                                Custom);
815         }
816       }
817 
818       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
819         if (!useRVVForFixedLengthVectorVT(VT))
820           continue;
821 
822         // By default everything must be expanded.
823         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
824           setOperationAction(Op, VT, Expand);
825         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
826           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
827           setTruncStoreAction(VT, OtherVT, Expand);
828         }
829 
830         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
831         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
832                            Custom);
833 
834         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
835                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
836                             ISD::EXTRACT_VECTOR_ELT},
837                            VT, Custom);
838 
839         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
840                             ISD::MGATHER, ISD::MSCATTER},
841                            VT, Custom);
842 
843         setOperationAction(
844             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
845             Custom);
846 
847         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
848                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
849                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
850                            VT, Custom);
851 
852         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
853 
854         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
855                            VT, Custom);
856 
857         for (auto CC : VFPCCToExpand)
858           setCondCodeAction(CC, VT, Expand);
859 
860         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
861         setOperationAction(ISD::SELECT_CC, VT, Expand);
862 
863         setOperationAction(ISD::BITCAST, VT, Custom);
864 
865         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
866                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
867                            VT, Custom);
868 
869         setOperationAction(FloatingPointVPOps, VT, Custom);
870       }
871 
872       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
873       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
874                          Custom);
875       if (Subtarget.hasStdExtZfh())
876         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
877       if (Subtarget.hasStdExtF())
878         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
879       if (Subtarget.hasStdExtD())
880         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
881     }
882   }
883 
884   // Function alignments.
885   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
886   setMinFunctionAlignment(FunctionAlignment);
887   setPrefFunctionAlignment(FunctionAlignment);
888 
889   setMinimumJumpTableEntries(5);
890 
891   // Jumps are expensive, compared to logic
892   setJumpIsExpensive();
893 
894   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
895                        ISD::OR, ISD::XOR});
896 
897   if (Subtarget.hasStdExtF())
898     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
899 
900   if (Subtarget.hasStdExtZbp())
901     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
902 
903   if (Subtarget.hasStdExtZbb())
904     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
905 
906   if (Subtarget.hasStdExtZbkb())
907     setTargetDAGCombine(ISD::BITREVERSE);
908   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
909     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
910   if (Subtarget.hasStdExtF())
911     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
912                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
913   if (Subtarget.hasVInstructions())
914     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
915                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
916                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
917 
918   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
919   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
920 }
921 
922 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
923                                             LLVMContext &Context,
924                                             EVT VT) const {
925   if (!VT.isVector())
926     return getPointerTy(DL);
927   if (Subtarget.hasVInstructions() &&
928       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
929     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
930   return VT.changeVectorElementTypeToInteger();
931 }
932 
933 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
934   return Subtarget.getXLenVT();
935 }
936 
937 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
938                                              const CallInst &I,
939                                              MachineFunction &MF,
940                                              unsigned Intrinsic) const {
941   auto &DL = I.getModule()->getDataLayout();
942   switch (Intrinsic) {
943   default:
944     return false;
945   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
946   case Intrinsic::riscv_masked_atomicrmw_add_i32:
947   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
948   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
949   case Intrinsic::riscv_masked_atomicrmw_max_i32:
950   case Intrinsic::riscv_masked_atomicrmw_min_i32:
951   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
952   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
953   case Intrinsic::riscv_masked_cmpxchg_i32:
954     Info.opc = ISD::INTRINSIC_W_CHAIN;
955     Info.memVT = MVT::i32;
956     Info.ptrVal = I.getArgOperand(0);
957     Info.offset = 0;
958     Info.align = Align(4);
959     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
960                  MachineMemOperand::MOVolatile;
961     return true;
962   case Intrinsic::riscv_masked_strided_load:
963     Info.opc = ISD::INTRINSIC_W_CHAIN;
964     Info.ptrVal = I.getArgOperand(1);
965     Info.memVT = getValueType(DL, I.getType()->getScalarType());
966     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
967     Info.size = MemoryLocation::UnknownSize;
968     Info.flags |= MachineMemOperand::MOLoad;
969     return true;
970   case Intrinsic::riscv_masked_strided_store:
971     Info.opc = ISD::INTRINSIC_VOID;
972     Info.ptrVal = I.getArgOperand(1);
973     Info.memVT =
974         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
975     Info.align = Align(
976         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
977         8);
978     Info.size = MemoryLocation::UnknownSize;
979     Info.flags |= MachineMemOperand::MOStore;
980     return true;
981   case Intrinsic::riscv_seg2_load:
982   case Intrinsic::riscv_seg3_load:
983   case Intrinsic::riscv_seg4_load:
984   case Intrinsic::riscv_seg5_load:
985   case Intrinsic::riscv_seg6_load:
986   case Intrinsic::riscv_seg7_load:
987   case Intrinsic::riscv_seg8_load:
988     Info.opc = ISD::INTRINSIC_W_CHAIN;
989     Info.ptrVal = I.getArgOperand(0);
990     Info.memVT =
991         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
992     Info.align =
993         Align(DL.getTypeSizeInBits(
994                   I.getType()->getStructElementType(0)->getScalarType()) /
995               8);
996     Info.size = MemoryLocation::UnknownSize;
997     Info.flags |= MachineMemOperand::MOLoad;
998     return true;
999   }
1000 }
1001 
1002 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1003                                                 const AddrMode &AM, Type *Ty,
1004                                                 unsigned AS,
1005                                                 Instruction *I) const {
1006   // No global is ever allowed as a base.
1007   if (AM.BaseGV)
1008     return false;
1009 
1010   // RVV instructions only support register addressing.
1011   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1012     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1013 
1014   // Require a 12-bit signed offset.
1015   if (!isInt<12>(AM.BaseOffs))
1016     return false;
1017 
1018   switch (AM.Scale) {
1019   case 0: // "r+i" or just "i", depending on HasBaseReg.
1020     break;
1021   case 1:
1022     if (!AM.HasBaseReg) // allow "r+i".
1023       break;
1024     return false; // disallow "r+r" or "r+r+i".
1025   default:
1026     return false;
1027   }
1028 
1029   return true;
1030 }
1031 
1032 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1033   return isInt<12>(Imm);
1034 }
1035 
1036 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1037   return isInt<12>(Imm);
1038 }
1039 
1040 // On RV32, 64-bit integers are split into their high and low parts and held
1041 // in two different registers, so the trunc is free since the low register can
1042 // just be used.
1043 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1044   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1045     return false;
1046   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1047   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1048   return (SrcBits == 64 && DestBits == 32);
1049 }
1050 
1051 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1052   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1053       !SrcVT.isInteger() || !DstVT.isInteger())
1054     return false;
1055   unsigned SrcBits = SrcVT.getSizeInBits();
1056   unsigned DestBits = DstVT.getSizeInBits();
1057   return (SrcBits == 64 && DestBits == 32);
1058 }
1059 
1060 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1061   // Zexts are free if they can be combined with a load.
1062   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1063   // poorly with type legalization of compares preferring sext.
1064   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1065     EVT MemVT = LD->getMemoryVT();
1066     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1067         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1068          LD->getExtensionType() == ISD::ZEXTLOAD))
1069       return true;
1070   }
1071 
1072   return TargetLowering::isZExtFree(Val, VT2);
1073 }
1074 
1075 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1076   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1077 }
1078 
1079 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1080   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1081 }
1082 
1083 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1084   return Subtarget.hasStdExtZbb();
1085 }
1086 
1087 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1088   return Subtarget.hasStdExtZbb();
1089 }
1090 
1091 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1092   EVT VT = Y.getValueType();
1093 
1094   // FIXME: Support vectors once we have tests.
1095   if (VT.isVector())
1096     return false;
1097 
1098   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1099           Subtarget.hasStdExtZbkb()) &&
1100          !isa<ConstantSDNode>(Y);
1101 }
1102 
1103 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1104   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1105   auto *C = dyn_cast<ConstantSDNode>(Y);
1106   return C && C->getAPIntValue().ule(10);
1107 }
1108 
1109 bool RISCVTargetLowering::
1110     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1111         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1112         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1113         SelectionDAG &DAG) const {
1114   // One interesting pattern that we'd want to form is 'bit extract':
1115   //   ((1 >> Y) & 1) ==/!= 0
1116   // But we also need to be careful not to try to reverse that fold.
1117 
1118   // Is this '((1 >> Y) & 1)'?
1119   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1120     return false; // Keep the 'bit extract' pattern.
1121 
1122   // Will this be '((1 >> Y) & 1)' after the transform?
1123   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1124     return true; // Do form the 'bit extract' pattern.
1125 
1126   // If 'X' is a constant, and we transform, then we will immediately
1127   // try to undo the fold, thus causing endless combine loop.
1128   // So only do the transform if X is not a constant. This matches the default
1129   // implementation of this function.
1130   return !XC;
1131 }
1132 
1133 /// Check if sinking \p I's operands to I's basic block is profitable, because
1134 /// the operands can be folded into a target instruction, e.g.
1135 /// splats of scalars can fold into vector instructions.
1136 bool RISCVTargetLowering::shouldSinkOperands(
1137     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1138   using namespace llvm::PatternMatch;
1139 
1140   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1141     return false;
1142 
1143   auto IsSinker = [&](Instruction *I, int Operand) {
1144     switch (I->getOpcode()) {
1145     case Instruction::Add:
1146     case Instruction::Sub:
1147     case Instruction::Mul:
1148     case Instruction::And:
1149     case Instruction::Or:
1150     case Instruction::Xor:
1151     case Instruction::FAdd:
1152     case Instruction::FSub:
1153     case Instruction::FMul:
1154     case Instruction::FDiv:
1155     case Instruction::ICmp:
1156     case Instruction::FCmp:
1157       return true;
1158     case Instruction::Shl:
1159     case Instruction::LShr:
1160     case Instruction::AShr:
1161     case Instruction::UDiv:
1162     case Instruction::SDiv:
1163     case Instruction::URem:
1164     case Instruction::SRem:
1165       return Operand == 1;
1166     case Instruction::Call:
1167       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1168         switch (II->getIntrinsicID()) {
1169         case Intrinsic::fma:
1170         case Intrinsic::vp_fma:
1171           return Operand == 0 || Operand == 1;
1172         // FIXME: Our patterns can only match vx/vf instructions when the splat
1173         // it on the RHS, because TableGen doesn't recognize our VP operations
1174         // as commutative.
1175         case Intrinsic::vp_add:
1176         case Intrinsic::vp_mul:
1177         case Intrinsic::vp_and:
1178         case Intrinsic::vp_or:
1179         case Intrinsic::vp_xor:
1180         case Intrinsic::vp_fadd:
1181         case Intrinsic::vp_fmul:
1182         case Intrinsic::vp_shl:
1183         case Intrinsic::vp_lshr:
1184         case Intrinsic::vp_ashr:
1185         case Intrinsic::vp_udiv:
1186         case Intrinsic::vp_sdiv:
1187         case Intrinsic::vp_urem:
1188         case Intrinsic::vp_srem:
1189           return Operand == 1;
1190         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1191         // explicit patterns for both LHS and RHS (as 'vr' versions).
1192         case Intrinsic::vp_sub:
1193         case Intrinsic::vp_fsub:
1194         case Intrinsic::vp_fdiv:
1195           return Operand == 0 || Operand == 1;
1196         default:
1197           return false;
1198         }
1199       }
1200       return false;
1201     default:
1202       return false;
1203     }
1204   };
1205 
1206   for (auto OpIdx : enumerate(I->operands())) {
1207     if (!IsSinker(I, OpIdx.index()))
1208       continue;
1209 
1210     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1211     // Make sure we are not already sinking this operand
1212     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1213       continue;
1214 
1215     // We are looking for a splat that can be sunk.
1216     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1217                              m_Undef(), m_ZeroMask())))
1218       continue;
1219 
1220     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1221     // and vector registers
1222     for (Use &U : Op->uses()) {
1223       Instruction *Insn = cast<Instruction>(U.getUser());
1224       if (!IsSinker(Insn, U.getOperandNo()))
1225         return false;
1226     }
1227 
1228     Ops.push_back(&Op->getOperandUse(0));
1229     Ops.push_back(&OpIdx.value());
1230   }
1231   return true;
1232 }
1233 
1234 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1235                                        bool ForCodeSize) const {
1236   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1237   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1238     return false;
1239   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1240     return false;
1241   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1242     return false;
1243   return Imm.isZero();
1244 }
1245 
1246 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1247   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1248          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1249          (VT == MVT::f64 && Subtarget.hasStdExtD());
1250 }
1251 
1252 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1253                                                       CallingConv::ID CC,
1254                                                       EVT VT) const {
1255   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1256   // We might still end up using a GPR but that will be decided based on ABI.
1257   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1258   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1259     return MVT::f32;
1260 
1261   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1262 }
1263 
1264 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1265                                                            CallingConv::ID CC,
1266                                                            EVT VT) const {
1267   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1268   // We might still end up using a GPR but that will be decided based on ABI.
1269   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1270   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1271     return 1;
1272 
1273   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1274 }
1275 
1276 // Changes the condition code and swaps operands if necessary, so the SetCC
1277 // operation matches one of the comparisons supported directly by branches
1278 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1279 // with 1/-1.
1280 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1281                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1282   // Convert X > -1 to X >= 0.
1283   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1284     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1285     CC = ISD::SETGE;
1286     return;
1287   }
1288   // Convert X < 1 to 0 >= X.
1289   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1290     RHS = LHS;
1291     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1292     CC = ISD::SETGE;
1293     return;
1294   }
1295 
1296   switch (CC) {
1297   default:
1298     break;
1299   case ISD::SETGT:
1300   case ISD::SETLE:
1301   case ISD::SETUGT:
1302   case ISD::SETULE:
1303     CC = ISD::getSetCCSwappedOperands(CC);
1304     std::swap(LHS, RHS);
1305     break;
1306   }
1307 }
1308 
1309 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1310   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1311   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1312   if (VT.getVectorElementType() == MVT::i1)
1313     KnownSize *= 8;
1314 
1315   switch (KnownSize) {
1316   default:
1317     llvm_unreachable("Invalid LMUL.");
1318   case 8:
1319     return RISCVII::VLMUL::LMUL_F8;
1320   case 16:
1321     return RISCVII::VLMUL::LMUL_F4;
1322   case 32:
1323     return RISCVII::VLMUL::LMUL_F2;
1324   case 64:
1325     return RISCVII::VLMUL::LMUL_1;
1326   case 128:
1327     return RISCVII::VLMUL::LMUL_2;
1328   case 256:
1329     return RISCVII::VLMUL::LMUL_4;
1330   case 512:
1331     return RISCVII::VLMUL::LMUL_8;
1332   }
1333 }
1334 
1335 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1336   switch (LMul) {
1337   default:
1338     llvm_unreachable("Invalid LMUL.");
1339   case RISCVII::VLMUL::LMUL_F8:
1340   case RISCVII::VLMUL::LMUL_F4:
1341   case RISCVII::VLMUL::LMUL_F2:
1342   case RISCVII::VLMUL::LMUL_1:
1343     return RISCV::VRRegClassID;
1344   case RISCVII::VLMUL::LMUL_2:
1345     return RISCV::VRM2RegClassID;
1346   case RISCVII::VLMUL::LMUL_4:
1347     return RISCV::VRM4RegClassID;
1348   case RISCVII::VLMUL::LMUL_8:
1349     return RISCV::VRM8RegClassID;
1350   }
1351 }
1352 
1353 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1354   RISCVII::VLMUL LMUL = getLMUL(VT);
1355   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1356       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1357       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1358       LMUL == RISCVII::VLMUL::LMUL_1) {
1359     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1360                   "Unexpected subreg numbering");
1361     return RISCV::sub_vrm1_0 + Index;
1362   }
1363   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1364     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1365                   "Unexpected subreg numbering");
1366     return RISCV::sub_vrm2_0 + Index;
1367   }
1368   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1369     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1370                   "Unexpected subreg numbering");
1371     return RISCV::sub_vrm4_0 + Index;
1372   }
1373   llvm_unreachable("Invalid vector type.");
1374 }
1375 
1376 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1377   if (VT.getVectorElementType() == MVT::i1)
1378     return RISCV::VRRegClassID;
1379   return getRegClassIDForLMUL(getLMUL(VT));
1380 }
1381 
1382 // Attempt to decompose a subvector insert/extract between VecVT and
1383 // SubVecVT via subregister indices. Returns the subregister index that
1384 // can perform the subvector insert/extract with the given element index, as
1385 // well as the index corresponding to any leftover subvectors that must be
1386 // further inserted/extracted within the register class for SubVecVT.
1387 std::pair<unsigned, unsigned>
1388 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1389     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1390     const RISCVRegisterInfo *TRI) {
1391   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1392                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1393                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1394                 "Register classes not ordered");
1395   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1396   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1397   // Try to compose a subregister index that takes us from the incoming
1398   // LMUL>1 register class down to the outgoing one. At each step we half
1399   // the LMUL:
1400   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1401   // Note that this is not guaranteed to find a subregister index, such as
1402   // when we are extracting from one VR type to another.
1403   unsigned SubRegIdx = RISCV::NoSubRegister;
1404   for (const unsigned RCID :
1405        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1406     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1407       VecVT = VecVT.getHalfNumVectorElementsVT();
1408       bool IsHi =
1409           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1410       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1411                                             getSubregIndexByMVT(VecVT, IsHi));
1412       if (IsHi)
1413         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1414     }
1415   return {SubRegIdx, InsertExtractIdx};
1416 }
1417 
1418 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1419 // stores for those types.
1420 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1421   return !Subtarget.useRVVForFixedLengthVectors() ||
1422          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1423 }
1424 
1425 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1426   if (ScalarTy->isPointerTy())
1427     return true;
1428 
1429   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1430       ScalarTy->isIntegerTy(32))
1431     return true;
1432 
1433   if (ScalarTy->isIntegerTy(64))
1434     return Subtarget.hasVInstructionsI64();
1435 
1436   if (ScalarTy->isHalfTy())
1437     return Subtarget.hasVInstructionsF16();
1438   if (ScalarTy->isFloatTy())
1439     return Subtarget.hasVInstructionsF32();
1440   if (ScalarTy->isDoubleTy())
1441     return Subtarget.hasVInstructionsF64();
1442 
1443   return false;
1444 }
1445 
1446 static SDValue getVLOperand(SDValue Op) {
1447   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1448           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1449          "Unexpected opcode");
1450   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1451   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1452   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1453       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1454   if (!II)
1455     return SDValue();
1456   return Op.getOperand(II->VLOperand + 1 + HasChain);
1457 }
1458 
1459 static bool useRVVForFixedLengthVectorVT(MVT VT,
1460                                          const RISCVSubtarget &Subtarget) {
1461   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1462   if (!Subtarget.useRVVForFixedLengthVectors())
1463     return false;
1464 
1465   // We only support a set of vector types with a consistent maximum fixed size
1466   // across all supported vector element types to avoid legalization issues.
1467   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1468   // fixed-length vector type we support is 1024 bytes.
1469   if (VT.getFixedSizeInBits() > 1024 * 8)
1470     return false;
1471 
1472   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1473 
1474   MVT EltVT = VT.getVectorElementType();
1475 
1476   // Don't use RVV for vectors we cannot scalarize if required.
1477   switch (EltVT.SimpleTy) {
1478   // i1 is supported but has different rules.
1479   default:
1480     return false;
1481   case MVT::i1:
1482     // Masks can only use a single register.
1483     if (VT.getVectorNumElements() > MinVLen)
1484       return false;
1485     MinVLen /= 8;
1486     break;
1487   case MVT::i8:
1488   case MVT::i16:
1489   case MVT::i32:
1490     break;
1491   case MVT::i64:
1492     if (!Subtarget.hasVInstructionsI64())
1493       return false;
1494     break;
1495   case MVT::f16:
1496     if (!Subtarget.hasVInstructionsF16())
1497       return false;
1498     break;
1499   case MVT::f32:
1500     if (!Subtarget.hasVInstructionsF32())
1501       return false;
1502     break;
1503   case MVT::f64:
1504     if (!Subtarget.hasVInstructionsF64())
1505       return false;
1506     break;
1507   }
1508 
1509   // Reject elements larger than ELEN.
1510   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1511     return false;
1512 
1513   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1514   // Don't use RVV for types that don't fit.
1515   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1516     return false;
1517 
1518   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1519   // the base fixed length RVV support in place.
1520   if (!VT.isPow2VectorType())
1521     return false;
1522 
1523   return true;
1524 }
1525 
1526 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1527   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1528 }
1529 
1530 // Return the largest legal scalable vector type that matches VT's element type.
1531 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1532                                             const RISCVSubtarget &Subtarget) {
1533   // This may be called before legal types are setup.
1534   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1535           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1536          "Expected legal fixed length vector!");
1537 
1538   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1539   unsigned MaxELen = Subtarget.getELEN();
1540 
1541   MVT EltVT = VT.getVectorElementType();
1542   switch (EltVT.SimpleTy) {
1543   default:
1544     llvm_unreachable("unexpected element type for RVV container");
1545   case MVT::i1:
1546   case MVT::i8:
1547   case MVT::i16:
1548   case MVT::i32:
1549   case MVT::i64:
1550   case MVT::f16:
1551   case MVT::f32:
1552   case MVT::f64: {
1553     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1554     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1555     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1556     unsigned NumElts =
1557         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1558     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1559     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1560     return MVT::getScalableVectorVT(EltVT, NumElts);
1561   }
1562   }
1563 }
1564 
1565 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1566                                             const RISCVSubtarget &Subtarget) {
1567   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1568                                           Subtarget);
1569 }
1570 
1571 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1572   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1573 }
1574 
1575 // Grow V to consume an entire RVV register.
1576 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1577                                        const RISCVSubtarget &Subtarget) {
1578   assert(VT.isScalableVector() &&
1579          "Expected to convert into a scalable vector!");
1580   assert(V.getValueType().isFixedLengthVector() &&
1581          "Expected a fixed length vector operand!");
1582   SDLoc DL(V);
1583   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1584   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1585 }
1586 
1587 // Shrink V so it's just big enough to maintain a VT's worth of data.
1588 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1589                                          const RISCVSubtarget &Subtarget) {
1590   assert(VT.isFixedLengthVector() &&
1591          "Expected to convert into a fixed length vector!");
1592   assert(V.getValueType().isScalableVector() &&
1593          "Expected a scalable vector operand!");
1594   SDLoc DL(V);
1595   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1596   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1597 }
1598 
1599 /// Return the type of the mask type suitable for masking the provided
1600 /// vector type.  This is simply an i1 element type vector of the same
1601 /// (possibly scalable) length.
1602 static MVT getMaskTypeFor(EVT VecVT) {
1603   assert(VecVT.isVector());
1604   ElementCount EC = VecVT.getVectorElementCount();
1605   return MVT::getVectorVT(MVT::i1, EC);
1606 }
1607 
1608 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1609 /// vector length VL.  .
1610 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1611                               SelectionDAG &DAG) {
1612   MVT MaskVT = getMaskTypeFor(VecVT);
1613   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1614 }
1615 
1616 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1617 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1618 // the vector type that it is contained in.
1619 static std::pair<SDValue, SDValue>
1620 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1621                 const RISCVSubtarget &Subtarget) {
1622   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1623   MVT XLenVT = Subtarget.getXLenVT();
1624   SDValue VL = VecVT.isFixedLengthVector()
1625                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1626                    : DAG.getRegister(RISCV::X0, XLenVT);
1627   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1628   return {Mask, VL};
1629 }
1630 
1631 // As above but assuming the given type is a scalable vector type.
1632 static std::pair<SDValue, SDValue>
1633 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1634                         const RISCVSubtarget &Subtarget) {
1635   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1636   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1637 }
1638 
1639 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1640 // of either is (currently) supported. This can get us into an infinite loop
1641 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1642 // as a ..., etc.
1643 // Until either (or both) of these can reliably lower any node, reporting that
1644 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1645 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1646 // which is not desirable.
1647 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1648     EVT VT, unsigned DefinedValues) const {
1649   return false;
1650 }
1651 
1652 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1653                                   const RISCVSubtarget &Subtarget) {
1654   // RISCV FP-to-int conversions saturate to the destination register size, but
1655   // don't produce 0 for nan. We can use a conversion instruction and fix the
1656   // nan case with a compare and a select.
1657   SDValue Src = Op.getOperand(0);
1658 
1659   EVT DstVT = Op.getValueType();
1660   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1661 
1662   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1663   unsigned Opc;
1664   if (SatVT == DstVT)
1665     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1666   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1667     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1668   else
1669     return SDValue();
1670   // FIXME: Support other SatVTs by clamping before or after the conversion.
1671 
1672   SDLoc DL(Op);
1673   SDValue FpToInt = DAG.getNode(
1674       Opc, DL, DstVT, Src,
1675       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1676 
1677   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1678   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1679 }
1680 
1681 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1682 // and back. Taking care to avoid converting values that are nan or already
1683 // correct.
1684 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1685 // have FRM dependencies modeled yet.
1686 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1687   MVT VT = Op.getSimpleValueType();
1688   assert(VT.isVector() && "Unexpected type");
1689 
1690   SDLoc DL(Op);
1691 
1692   // Freeze the source since we are increasing the number of uses.
1693   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1694 
1695   // Truncate to integer and convert back to FP.
1696   MVT IntVT = VT.changeVectorElementTypeToInteger();
1697   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1698   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1699 
1700   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1701 
1702   if (Op.getOpcode() == ISD::FCEIL) {
1703     // If the truncated value is the greater than or equal to the original
1704     // value, we've computed the ceil. Otherwise, we went the wrong way and
1705     // need to increase by 1.
1706     // FIXME: This should use a masked operation. Handle here or in isel?
1707     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1708                                  DAG.getConstantFP(1.0, DL, VT));
1709     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1710     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1711   } else if (Op.getOpcode() == ISD::FFLOOR) {
1712     // If the truncated value is the less than or equal to the original value,
1713     // we've computed the floor. Otherwise, we went the wrong way and need to
1714     // decrease by 1.
1715     // FIXME: This should use a masked operation. Handle here or in isel?
1716     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1717                                  DAG.getConstantFP(1.0, DL, VT));
1718     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1719     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1720   }
1721 
1722   // Restore the original sign so that -0.0 is preserved.
1723   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1724 
1725   // Determine the largest integer that can be represented exactly. This and
1726   // values larger than it don't have any fractional bits so don't need to
1727   // be converted.
1728   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1729   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1730   APFloat MaxVal = APFloat(FltSem);
1731   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1732                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1733   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1734 
1735   // If abs(Src) was larger than MaxVal or nan, keep it.
1736   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1737   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1738   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1739 }
1740 
1741 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1742 // This mode isn't supported in vector hardware on RISCV. But as long as we
1743 // aren't compiling with trapping math, we can emulate this with
1744 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1745 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1746 // dependencies modeled yet.
1747 // FIXME: Use masked operations to avoid final merge.
1748 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1749   MVT VT = Op.getSimpleValueType();
1750   assert(VT.isVector() && "Unexpected type");
1751 
1752   SDLoc DL(Op);
1753 
1754   // Freeze the source since we are increasing the number of uses.
1755   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1756 
1757   // We do the conversion on the absolute value and fix the sign at the end.
1758   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1759 
1760   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1761   bool Ignored;
1762   APFloat Point5Pred = APFloat(0.5f);
1763   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1764   Point5Pred.next(/*nextDown*/ true);
1765 
1766   // Add the adjustment.
1767   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1768                                DAG.getConstantFP(Point5Pred, DL, VT));
1769 
1770   // Truncate to integer and convert back to fp.
1771   MVT IntVT = VT.changeVectorElementTypeToInteger();
1772   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1773   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1774 
1775   // Restore the original sign.
1776   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1777 
1778   // Determine the largest integer that can be represented exactly. This and
1779   // values larger than it don't have any fractional bits so don't need to
1780   // be converted.
1781   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1782   APFloat MaxVal = APFloat(FltSem);
1783   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1784                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1785   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1786 
1787   // If abs(Src) was larger than MaxVal or nan, keep it.
1788   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1789   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1790   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1791 }
1792 
1793 struct VIDSequence {
1794   int64_t StepNumerator;
1795   unsigned StepDenominator;
1796   int64_t Addend;
1797 };
1798 
1799 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1800 // to the (non-zero) step S and start value X. This can be then lowered as the
1801 // RVV sequence (VID * S) + X, for example.
1802 // The step S is represented as an integer numerator divided by a positive
1803 // denominator. Note that the implementation currently only identifies
1804 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1805 // cannot detect 2/3, for example.
1806 // Note that this method will also match potentially unappealing index
1807 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1808 // determine whether this is worth generating code for.
1809 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1810   unsigned NumElts = Op.getNumOperands();
1811   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1812   if (!Op.getValueType().isInteger())
1813     return None;
1814 
1815   Optional<unsigned> SeqStepDenom;
1816   Optional<int64_t> SeqStepNum, SeqAddend;
1817   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1818   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1819   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1820     // Assume undef elements match the sequence; we just have to be careful
1821     // when interpolating across them.
1822     if (Op.getOperand(Idx).isUndef())
1823       continue;
1824     // The BUILD_VECTOR must be all constants.
1825     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1826       return None;
1827 
1828     uint64_t Val = Op.getConstantOperandVal(Idx) &
1829                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1830 
1831     if (PrevElt) {
1832       // Calculate the step since the last non-undef element, and ensure
1833       // it's consistent across the entire sequence.
1834       unsigned IdxDiff = Idx - PrevElt->second;
1835       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1836 
1837       // A zero-value value difference means that we're somewhere in the middle
1838       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1839       // step change before evaluating the sequence.
1840       if (ValDiff == 0)
1841         continue;
1842 
1843       int64_t Remainder = ValDiff % IdxDiff;
1844       // Normalize the step if it's greater than 1.
1845       if (Remainder != ValDiff) {
1846         // The difference must cleanly divide the element span.
1847         if (Remainder != 0)
1848           return None;
1849         ValDiff /= IdxDiff;
1850         IdxDiff = 1;
1851       }
1852 
1853       if (!SeqStepNum)
1854         SeqStepNum = ValDiff;
1855       else if (ValDiff != SeqStepNum)
1856         return None;
1857 
1858       if (!SeqStepDenom)
1859         SeqStepDenom = IdxDiff;
1860       else if (IdxDiff != *SeqStepDenom)
1861         return None;
1862     }
1863 
1864     // Record this non-undef element for later.
1865     if (!PrevElt || PrevElt->first != Val)
1866       PrevElt = std::make_pair(Val, Idx);
1867   }
1868 
1869   // We need to have logged a step for this to count as a legal index sequence.
1870   if (!SeqStepNum || !SeqStepDenom)
1871     return None;
1872 
1873   // Loop back through the sequence and validate elements we might have skipped
1874   // while waiting for a valid step. While doing this, log any sequence addend.
1875   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1876     if (Op.getOperand(Idx).isUndef())
1877       continue;
1878     uint64_t Val = Op.getConstantOperandVal(Idx) &
1879                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1880     uint64_t ExpectedVal =
1881         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1882     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1883     if (!SeqAddend)
1884       SeqAddend = Addend;
1885     else if (Addend != SeqAddend)
1886       return None;
1887   }
1888 
1889   assert(SeqAddend && "Must have an addend if we have a step");
1890 
1891   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1892 }
1893 
1894 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1895 // and lower it as a VRGATHER_VX_VL from the source vector.
1896 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1897                                   SelectionDAG &DAG,
1898                                   const RISCVSubtarget &Subtarget) {
1899   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1900     return SDValue();
1901   SDValue Vec = SplatVal.getOperand(0);
1902   // Only perform this optimization on vectors of the same size for simplicity.
1903   if (Vec.getValueType() != VT)
1904     return SDValue();
1905   SDValue Idx = SplatVal.getOperand(1);
1906   // The index must be a legal type.
1907   if (Idx.getValueType() != Subtarget.getXLenVT())
1908     return SDValue();
1909 
1910   MVT ContainerVT = VT;
1911   if (VT.isFixedLengthVector()) {
1912     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1913     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1914   }
1915 
1916   SDValue Mask, VL;
1917   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1918 
1919   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
1920                                Idx, Mask, VL);
1921 
1922   if (!VT.isFixedLengthVector())
1923     return Gather;
1924 
1925   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1926 }
1927 
1928 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1929                                  const RISCVSubtarget &Subtarget) {
1930   MVT VT = Op.getSimpleValueType();
1931   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1932 
1933   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1934 
1935   SDLoc DL(Op);
1936   SDValue Mask, VL;
1937   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1938 
1939   MVT XLenVT = Subtarget.getXLenVT();
1940   unsigned NumElts = Op.getNumOperands();
1941 
1942   if (VT.getVectorElementType() == MVT::i1) {
1943     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1944       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1945       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1946     }
1947 
1948     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1949       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1950       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1951     }
1952 
1953     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1954     // scalar integer chunks whose bit-width depends on the number of mask
1955     // bits and XLEN.
1956     // First, determine the most appropriate scalar integer type to use. This
1957     // is at most XLenVT, but may be shrunk to a smaller vector element type
1958     // according to the size of the final vector - use i8 chunks rather than
1959     // XLenVT if we're producing a v8i1. This results in more consistent
1960     // codegen across RV32 and RV64.
1961     unsigned NumViaIntegerBits =
1962         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1963     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
1964     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1965       // If we have to use more than one INSERT_VECTOR_ELT then this
1966       // optimization is likely to increase code size; avoid peforming it in
1967       // such a case. We can use a load from a constant pool in this case.
1968       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1969         return SDValue();
1970       // Now we can create our integer vector type. Note that it may be larger
1971       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1972       MVT IntegerViaVecVT =
1973           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1974                            divideCeil(NumElts, NumViaIntegerBits));
1975 
1976       uint64_t Bits = 0;
1977       unsigned BitPos = 0, IntegerEltIdx = 0;
1978       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1979 
1980       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1981         // Once we accumulate enough bits to fill our scalar type, insert into
1982         // our vector and clear our accumulated data.
1983         if (I != 0 && I % NumViaIntegerBits == 0) {
1984           if (NumViaIntegerBits <= 32)
1985             Bits = SignExtend64(Bits, 32);
1986           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1987           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1988                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1989           Bits = 0;
1990           BitPos = 0;
1991           IntegerEltIdx++;
1992         }
1993         SDValue V = Op.getOperand(I);
1994         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1995         Bits |= ((uint64_t)BitValue << BitPos);
1996       }
1997 
1998       // Insert the (remaining) scalar value into position in our integer
1999       // vector type.
2000       if (NumViaIntegerBits <= 32)
2001         Bits = SignExtend64(Bits, 32);
2002       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2003       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2004                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2005 
2006       if (NumElts < NumViaIntegerBits) {
2007         // If we're producing a smaller vector than our minimum legal integer
2008         // type, bitcast to the equivalent (known-legal) mask type, and extract
2009         // our final mask.
2010         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2011         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2012         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2013                           DAG.getConstant(0, DL, XLenVT));
2014       } else {
2015         // Else we must have produced an integer type with the same size as the
2016         // mask type; bitcast for the final result.
2017         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2018         Vec = DAG.getBitcast(VT, Vec);
2019       }
2020 
2021       return Vec;
2022     }
2023 
2024     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2025     // vector type, we have a legal equivalently-sized i8 type, so we can use
2026     // that.
2027     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2028     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2029 
2030     SDValue WideVec;
2031     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2032       // For a splat, perform a scalar truncate before creating the wider
2033       // vector.
2034       assert(Splat.getValueType() == XLenVT &&
2035              "Unexpected type for i1 splat value");
2036       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2037                           DAG.getConstant(1, DL, XLenVT));
2038       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2039     } else {
2040       SmallVector<SDValue, 8> Ops(Op->op_values());
2041       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2042       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2043       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2044     }
2045 
2046     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2047   }
2048 
2049   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2050     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2051       return Gather;
2052     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2053                                         : RISCVISD::VMV_V_X_VL;
2054     Splat =
2055         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2056     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2057   }
2058 
2059   // Try and match index sequences, which we can lower to the vid instruction
2060   // with optional modifications. An all-undef vector is matched by
2061   // getSplatValue, above.
2062   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2063     int64_t StepNumerator = SimpleVID->StepNumerator;
2064     unsigned StepDenominator = SimpleVID->StepDenominator;
2065     int64_t Addend = SimpleVID->Addend;
2066 
2067     assert(StepNumerator != 0 && "Invalid step");
2068     bool Negate = false;
2069     int64_t SplatStepVal = StepNumerator;
2070     unsigned StepOpcode = ISD::MUL;
2071     if (StepNumerator != 1) {
2072       if (isPowerOf2_64(std::abs(StepNumerator))) {
2073         Negate = StepNumerator < 0;
2074         StepOpcode = ISD::SHL;
2075         SplatStepVal = Log2_64(std::abs(StepNumerator));
2076       }
2077     }
2078 
2079     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2080     // threshold since it's the immediate value many RVV instructions accept.
2081     // There is no vmul.vi instruction so ensure multiply constant can fit in
2082     // a single addi instruction.
2083     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2084          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2085         isPowerOf2_32(StepDenominator) &&
2086         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2087       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2088       // Convert right out of the scalable type so we can use standard ISD
2089       // nodes for the rest of the computation. If we used scalable types with
2090       // these, we'd lose the fixed-length vector info and generate worse
2091       // vsetvli code.
2092       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2093       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2094           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2095         SDValue SplatStep = DAG.getSplatBuildVector(
2096             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2097         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2098       }
2099       if (StepDenominator != 1) {
2100         SDValue SplatStep = DAG.getSplatBuildVector(
2101             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2102         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2103       }
2104       if (Addend != 0 || Negate) {
2105         SDValue SplatAddend = DAG.getSplatBuildVector(
2106             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2107         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2108       }
2109       return VID;
2110     }
2111   }
2112 
2113   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2114   // when re-interpreted as a vector with a larger element type. For example,
2115   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2116   // could be instead splat as
2117   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2118   // TODO: This optimization could also work on non-constant splats, but it
2119   // would require bit-manipulation instructions to construct the splat value.
2120   SmallVector<SDValue> Sequence;
2121   unsigned EltBitSize = VT.getScalarSizeInBits();
2122   const auto *BV = cast<BuildVectorSDNode>(Op);
2123   if (VT.isInteger() && EltBitSize < 64 &&
2124       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2125       BV->getRepeatedSequence(Sequence) &&
2126       (Sequence.size() * EltBitSize) <= 64) {
2127     unsigned SeqLen = Sequence.size();
2128     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2129     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2130     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2131             ViaIntVT == MVT::i64) &&
2132            "Unexpected sequence type");
2133 
2134     unsigned EltIdx = 0;
2135     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2136     uint64_t SplatValue = 0;
2137     // Construct the amalgamated value which can be splatted as this larger
2138     // vector type.
2139     for (const auto &SeqV : Sequence) {
2140       if (!SeqV.isUndef())
2141         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2142                        << (EltIdx * EltBitSize));
2143       EltIdx++;
2144     }
2145 
2146     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2147     // achieve better constant materializion.
2148     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2149       SplatValue = SignExtend64(SplatValue, 32);
2150 
2151     // Since we can't introduce illegal i64 types at this stage, we can only
2152     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2153     // way we can use RVV instructions to splat.
2154     assert((ViaIntVT.bitsLE(XLenVT) ||
2155             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2156            "Unexpected bitcast sequence");
2157     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2158       SDValue ViaVL =
2159           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2160       MVT ViaContainerVT =
2161           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2162       SDValue Splat =
2163           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2164                       DAG.getUNDEF(ViaContainerVT),
2165                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2166       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2167       return DAG.getBitcast(VT, Splat);
2168     }
2169   }
2170 
2171   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2172   // which constitute a large proportion of the elements. In such cases we can
2173   // splat a vector with the dominant element and make up the shortfall with
2174   // INSERT_VECTOR_ELTs.
2175   // Note that this includes vectors of 2 elements by association. The
2176   // upper-most element is the "dominant" one, allowing us to use a splat to
2177   // "insert" the upper element, and an insert of the lower element at position
2178   // 0, which improves codegen.
2179   SDValue DominantValue;
2180   unsigned MostCommonCount = 0;
2181   DenseMap<SDValue, unsigned> ValueCounts;
2182   unsigned NumUndefElts =
2183       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2184 
2185   // Track the number of scalar loads we know we'd be inserting, estimated as
2186   // any non-zero floating-point constant. Other kinds of element are either
2187   // already in registers or are materialized on demand. The threshold at which
2188   // a vector load is more desirable than several scalar materializion and
2189   // vector-insertion instructions is not known.
2190   unsigned NumScalarLoads = 0;
2191 
2192   for (SDValue V : Op->op_values()) {
2193     if (V.isUndef())
2194       continue;
2195 
2196     ValueCounts.insert(std::make_pair(V, 0));
2197     unsigned &Count = ValueCounts[V];
2198 
2199     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2200       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2201 
2202     // Is this value dominant? In case of a tie, prefer the highest element as
2203     // it's cheaper to insert near the beginning of a vector than it is at the
2204     // end.
2205     if (++Count >= MostCommonCount) {
2206       DominantValue = V;
2207       MostCommonCount = Count;
2208     }
2209   }
2210 
2211   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2212   unsigned NumDefElts = NumElts - NumUndefElts;
2213   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2214 
2215   // Don't perform this optimization when optimizing for size, since
2216   // materializing elements and inserting them tends to cause code bloat.
2217   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2218       ((MostCommonCount > DominantValueCountThreshold) ||
2219        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2220     // Start by splatting the most common element.
2221     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2222 
2223     DenseSet<SDValue> Processed{DominantValue};
2224     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2225     for (const auto &OpIdx : enumerate(Op->ops())) {
2226       const SDValue &V = OpIdx.value();
2227       if (V.isUndef() || !Processed.insert(V).second)
2228         continue;
2229       if (ValueCounts[V] == 1) {
2230         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2231                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2232       } else {
2233         // Blend in all instances of this value using a VSELECT, using a
2234         // mask where each bit signals whether that element is the one
2235         // we're after.
2236         SmallVector<SDValue> Ops;
2237         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2238           return DAG.getConstant(V == V1, DL, XLenVT);
2239         });
2240         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2241                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2242                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2243       }
2244     }
2245 
2246     return Vec;
2247   }
2248 
2249   return SDValue();
2250 }
2251 
2252 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2253                                    SDValue Lo, SDValue Hi, SDValue VL,
2254                                    SelectionDAG &DAG) {
2255   if (!Passthru)
2256     Passthru = DAG.getUNDEF(VT);
2257   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2258     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2259     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2260     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2261     // node in order to try and match RVV vector/scalar instructions.
2262     if ((LoC >> 31) == HiC)
2263       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2264 
2265     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2266     // vmv.v.x whose EEW = 32 to lower it.
2267     auto *Const = dyn_cast<ConstantSDNode>(VL);
2268     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2269       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2270       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2271       // access the subtarget here now.
2272       auto InterVec = DAG.getNode(
2273           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2274                                   DAG.getRegister(RISCV::X0, MVT::i32));
2275       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2276     }
2277   }
2278 
2279   // Fall back to a stack store and stride x0 vector load.
2280   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2281                      Hi, VL);
2282 }
2283 
2284 // Called by type legalization to handle splat of i64 on RV32.
2285 // FIXME: We can optimize this when the type has sign or zero bits in one
2286 // of the halves.
2287 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2288                                    SDValue Scalar, SDValue VL,
2289                                    SelectionDAG &DAG) {
2290   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2291   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2292                            DAG.getConstant(0, DL, MVT::i32));
2293   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2294                            DAG.getConstant(1, DL, MVT::i32));
2295   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2296 }
2297 
2298 // This function lowers a splat of a scalar operand Splat with the vector
2299 // length VL. It ensures the final sequence is type legal, which is useful when
2300 // lowering a splat after type legalization.
2301 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2302                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2303                                 const RISCVSubtarget &Subtarget) {
2304   bool HasPassthru = Passthru && !Passthru.isUndef();
2305   if (!HasPassthru && !Passthru)
2306     Passthru = DAG.getUNDEF(VT);
2307   if (VT.isFloatingPoint()) {
2308     // If VL is 1, we could use vfmv.s.f.
2309     if (isOneConstant(VL))
2310       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2311     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2312   }
2313 
2314   MVT XLenVT = Subtarget.getXLenVT();
2315 
2316   // Simplest case is that the operand needs to be promoted to XLenVT.
2317   if (Scalar.getValueType().bitsLE(XLenVT)) {
2318     // If the operand is a constant, sign extend to increase our chances
2319     // of being able to use a .vi instruction. ANY_EXTEND would become a
2320     // a zero extend and the simm5 check in isel would fail.
2321     // FIXME: Should we ignore the upper bits in isel instead?
2322     unsigned ExtOpc =
2323         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2324     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2325     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2326     // If VL is 1 and the scalar value won't benefit from immediate, we could
2327     // use vmv.s.x.
2328     if (isOneConstant(VL) &&
2329         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2330       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2331     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2332   }
2333 
2334   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2335          "Unexpected scalar for splat lowering!");
2336 
2337   if (isOneConstant(VL) && isNullConstant(Scalar))
2338     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2339                        DAG.getConstant(0, DL, XLenVT), VL);
2340 
2341   // Otherwise use the more complicated splatting algorithm.
2342   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2343 }
2344 
2345 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2346                                 const RISCVSubtarget &Subtarget) {
2347   // We need to be able to widen elements to the next larger integer type.
2348   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2349     return false;
2350 
2351   int Size = Mask.size();
2352   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2353 
2354   int Srcs[] = {-1, -1};
2355   for (int i = 0; i != Size; ++i) {
2356     // Ignore undef elements.
2357     if (Mask[i] < 0)
2358       continue;
2359 
2360     // Is this an even or odd element.
2361     int Pol = i % 2;
2362 
2363     // Ensure we consistently use the same source for this element polarity.
2364     int Src = Mask[i] / Size;
2365     if (Srcs[Pol] < 0)
2366       Srcs[Pol] = Src;
2367     if (Srcs[Pol] != Src)
2368       return false;
2369 
2370     // Make sure the element within the source is appropriate for this element
2371     // in the destination.
2372     int Elt = Mask[i] % Size;
2373     if (Elt != i / 2)
2374       return false;
2375   }
2376 
2377   // We need to find a source for each polarity and they can't be the same.
2378   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2379     return false;
2380 
2381   // Swap the sources if the second source was in the even polarity.
2382   SwapSources = Srcs[0] > Srcs[1];
2383 
2384   return true;
2385 }
2386 
2387 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2388 /// and then extract the original number of elements from the rotated result.
2389 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2390 /// returned rotation amount is for a rotate right, where elements move from
2391 /// higher elements to lower elements. \p LoSrc indicates the first source
2392 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2393 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2394 /// 0 or 1 if a rotation is found.
2395 ///
2396 /// NOTE: We talk about rotate to the right which matches how bit shift and
2397 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2398 /// and the table below write vectors with the lowest elements on the left.
2399 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2400   int Size = Mask.size();
2401 
2402   // We need to detect various ways of spelling a rotation:
2403   //   [11, 12, 13, 14, 15,  0,  1,  2]
2404   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2405   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2406   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2407   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2408   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2409   int Rotation = 0;
2410   LoSrc = -1;
2411   HiSrc = -1;
2412   for (int i = 0; i != Size; ++i) {
2413     int M = Mask[i];
2414     if (M < 0)
2415       continue;
2416 
2417     // Determine where a rotate vector would have started.
2418     int StartIdx = i - (M % Size);
2419     // The identity rotation isn't interesting, stop.
2420     if (StartIdx == 0)
2421       return -1;
2422 
2423     // If we found the tail of a vector the rotation must be the missing
2424     // front. If we found the head of a vector, it must be how much of the
2425     // head.
2426     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2427 
2428     if (Rotation == 0)
2429       Rotation = CandidateRotation;
2430     else if (Rotation != CandidateRotation)
2431       // The rotations don't match, so we can't match this mask.
2432       return -1;
2433 
2434     // Compute which value this mask is pointing at.
2435     int MaskSrc = M < Size ? 0 : 1;
2436 
2437     // Compute which of the two target values this index should be assigned to.
2438     // This reflects whether the high elements are remaining or the low elemnts
2439     // are remaining.
2440     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2441 
2442     // Either set up this value if we've not encountered it before, or check
2443     // that it remains consistent.
2444     if (TargetSrc < 0)
2445       TargetSrc = MaskSrc;
2446     else if (TargetSrc != MaskSrc)
2447       // This may be a rotation, but it pulls from the inputs in some
2448       // unsupported interleaving.
2449       return -1;
2450   }
2451 
2452   // Check that we successfully analyzed the mask, and normalize the results.
2453   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2454   assert((LoSrc >= 0 || HiSrc >= 0) &&
2455          "Failed to find a rotated input vector!");
2456 
2457   return Rotation;
2458 }
2459 
2460 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2461                                    const RISCVSubtarget &Subtarget) {
2462   SDValue V1 = Op.getOperand(0);
2463   SDValue V2 = Op.getOperand(1);
2464   SDLoc DL(Op);
2465   MVT XLenVT = Subtarget.getXLenVT();
2466   MVT VT = Op.getSimpleValueType();
2467   unsigned NumElts = VT.getVectorNumElements();
2468   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2469 
2470   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2471 
2472   SDValue TrueMask, VL;
2473   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2474 
2475   if (SVN->isSplat()) {
2476     const int Lane = SVN->getSplatIndex();
2477     if (Lane >= 0) {
2478       MVT SVT = VT.getVectorElementType();
2479 
2480       // Turn splatted vector load into a strided load with an X0 stride.
2481       SDValue V = V1;
2482       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2483       // with undef.
2484       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2485       int Offset = Lane;
2486       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2487         int OpElements =
2488             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2489         V = V.getOperand(Offset / OpElements);
2490         Offset %= OpElements;
2491       }
2492 
2493       // We need to ensure the load isn't atomic or volatile.
2494       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2495         auto *Ld = cast<LoadSDNode>(V);
2496         Offset *= SVT.getStoreSize();
2497         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2498                                                    TypeSize::Fixed(Offset), DL);
2499 
2500         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2501         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2502           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2503           SDValue IntID =
2504               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2505           SDValue Ops[] = {Ld->getChain(),
2506                            IntID,
2507                            DAG.getUNDEF(ContainerVT),
2508                            NewAddr,
2509                            DAG.getRegister(RISCV::X0, XLenVT),
2510                            VL};
2511           SDValue NewLoad = DAG.getMemIntrinsicNode(
2512               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2513               DAG.getMachineFunction().getMachineMemOperand(
2514                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2515           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2516           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2517         }
2518 
2519         // Otherwise use a scalar load and splat. This will give the best
2520         // opportunity to fold a splat into the operation. ISel can turn it into
2521         // the x0 strided load if we aren't able to fold away the select.
2522         if (SVT.isFloatingPoint())
2523           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2524                           Ld->getPointerInfo().getWithOffset(Offset),
2525                           Ld->getOriginalAlign(),
2526                           Ld->getMemOperand()->getFlags());
2527         else
2528           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2529                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2530                              Ld->getOriginalAlign(),
2531                              Ld->getMemOperand()->getFlags());
2532         DAG.makeEquivalentMemoryOrdering(Ld, V);
2533 
2534         unsigned Opc =
2535             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2536         SDValue Splat =
2537             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2538         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2539       }
2540 
2541       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2542       assert(Lane < (int)NumElts && "Unexpected lane!");
2543       SDValue Gather =
2544           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2545                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2546       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2547     }
2548   }
2549 
2550   ArrayRef<int> Mask = SVN->getMask();
2551 
2552   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2553   // be undef which can be handled with a single SLIDEDOWN/UP.
2554   int LoSrc, HiSrc;
2555   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2556   if (Rotation > 0) {
2557     SDValue LoV, HiV;
2558     if (LoSrc >= 0) {
2559       LoV = LoSrc == 0 ? V1 : V2;
2560       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2561     }
2562     if (HiSrc >= 0) {
2563       HiV = HiSrc == 0 ? V1 : V2;
2564       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2565     }
2566 
2567     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2568     // to slide LoV up by (NumElts - Rotation).
2569     unsigned InvRotate = NumElts - Rotation;
2570 
2571     SDValue Res = DAG.getUNDEF(ContainerVT);
2572     if (HiV) {
2573       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2574       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2575       // causes multiple vsetvlis in some test cases such as lowering
2576       // reduce.mul
2577       SDValue DownVL = VL;
2578       if (LoV)
2579         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2580       Res =
2581           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2582                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2583     }
2584     if (LoV)
2585       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2586                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2587 
2588     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2589   }
2590 
2591   // Detect an interleave shuffle and lower to
2592   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2593   bool SwapSources;
2594   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2595     // Swap sources if needed.
2596     if (SwapSources)
2597       std::swap(V1, V2);
2598 
2599     // Extract the lower half of the vectors.
2600     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2601     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2602                      DAG.getConstant(0, DL, XLenVT));
2603     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2604                      DAG.getConstant(0, DL, XLenVT));
2605 
2606     // Double the element width and halve the number of elements in an int type.
2607     unsigned EltBits = VT.getScalarSizeInBits();
2608     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2609     MVT WideIntVT =
2610         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2611     // Convert this to a scalable vector. We need to base this on the
2612     // destination size to ensure there's always a type with a smaller LMUL.
2613     MVT WideIntContainerVT =
2614         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2615 
2616     // Convert sources to scalable vectors with the same element count as the
2617     // larger type.
2618     MVT HalfContainerVT = MVT::getVectorVT(
2619         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2620     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2621     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2622 
2623     // Cast sources to integer.
2624     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2625     MVT IntHalfVT =
2626         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2627     V1 = DAG.getBitcast(IntHalfVT, V1);
2628     V2 = DAG.getBitcast(IntHalfVT, V2);
2629 
2630     // Freeze V2 since we use it twice and we need to be sure that the add and
2631     // multiply see the same value.
2632     V2 = DAG.getFreeze(V2);
2633 
2634     // Recreate TrueMask using the widened type's element count.
2635     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2636 
2637     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2638     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2639                               V2, TrueMask, VL);
2640     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2641     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2642                                      DAG.getUNDEF(IntHalfVT),
2643                                      DAG.getAllOnesConstant(DL, XLenVT));
2644     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2645                                    V2, Multiplier, TrueMask, VL);
2646     // Add the new copies to our previous addition giving us 2^eltbits copies of
2647     // V2. This is equivalent to shifting V2 left by eltbits. This should
2648     // combine with the vwmulu.vv above to form vwmaccu.vv.
2649     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2650                       TrueMask, VL);
2651     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2652     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2653     // vector VT.
2654     ContainerVT =
2655         MVT::getVectorVT(VT.getVectorElementType(),
2656                          WideIntContainerVT.getVectorElementCount() * 2);
2657     Add = DAG.getBitcast(ContainerVT, Add);
2658     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2659   }
2660 
2661   // Detect shuffles which can be re-expressed as vector selects; these are
2662   // shuffles in which each element in the destination is taken from an element
2663   // at the corresponding index in either source vectors.
2664   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2665     int MaskIndex = MaskIdx.value();
2666     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2667   });
2668 
2669   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2670 
2671   SmallVector<SDValue> MaskVals;
2672   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2673   // merged with a second vrgather.
2674   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2675 
2676   // By default we preserve the original operand order, and use a mask to
2677   // select LHS as true and RHS as false. However, since RVV vector selects may
2678   // feature splats but only on the LHS, we may choose to invert our mask and
2679   // instead select between RHS and LHS.
2680   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2681   bool InvertMask = IsSelect == SwapOps;
2682 
2683   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2684   // half.
2685   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2686 
2687   // Now construct the mask that will be used by the vselect or blended
2688   // vrgather operation. For vrgathers, construct the appropriate indices into
2689   // each vector.
2690   for (int MaskIndex : Mask) {
2691     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2692     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2693     if (!IsSelect) {
2694       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2695       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2696                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2697                                      : DAG.getUNDEF(XLenVT));
2698       GatherIndicesRHS.push_back(
2699           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2700                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2701       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2702         ++LHSIndexCounts[MaskIndex];
2703       if (!IsLHSOrUndefIndex)
2704         ++RHSIndexCounts[MaskIndex - NumElts];
2705     }
2706   }
2707 
2708   if (SwapOps) {
2709     std::swap(V1, V2);
2710     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2711   }
2712 
2713   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2714   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2715   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2716 
2717   if (IsSelect)
2718     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2719 
2720   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2721     // On such a large vector we're unable to use i8 as the index type.
2722     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2723     // may involve vector splitting if we're already at LMUL=8, or our
2724     // user-supplied maximum fixed-length LMUL.
2725     return SDValue();
2726   }
2727 
2728   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2729   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2730   MVT IndexVT = VT.changeTypeToInteger();
2731   // Since we can't introduce illegal index types at this stage, use i16 and
2732   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2733   // than XLenVT.
2734   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2735     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2736     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2737   }
2738 
2739   MVT IndexContainerVT =
2740       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2741 
2742   SDValue Gather;
2743   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2744   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2745   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2746     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2747                               Subtarget);
2748   } else {
2749     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2750     // If only one index is used, we can use a "splat" vrgather.
2751     // TODO: We can splat the most-common index and fix-up any stragglers, if
2752     // that's beneficial.
2753     if (LHSIndexCounts.size() == 1) {
2754       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2755       Gather =
2756           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2757                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2758     } else {
2759       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2760       LHSIndices =
2761           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2762 
2763       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2764                            TrueMask, VL);
2765     }
2766   }
2767 
2768   // If a second vector operand is used by this shuffle, blend it in with an
2769   // additional vrgather.
2770   if (!V2.isUndef()) {
2771     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2772     // If only one index is used, we can use a "splat" vrgather.
2773     // TODO: We can splat the most-common index and fix-up any stragglers, if
2774     // that's beneficial.
2775     if (RHSIndexCounts.size() == 1) {
2776       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2777       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2778                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2779     } else {
2780       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2781       RHSIndices =
2782           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2783       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2784                        VL);
2785     }
2786 
2787     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2788     SelectMask =
2789         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2790 
2791     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2792                          Gather, VL);
2793   }
2794 
2795   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2796 }
2797 
2798 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2799   // Support splats for any type. These should type legalize well.
2800   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2801     return true;
2802 
2803   // Only support legal VTs for other shuffles for now.
2804   if (!isTypeLegal(VT))
2805     return false;
2806 
2807   MVT SVT = VT.getSimpleVT();
2808 
2809   bool SwapSources;
2810   int LoSrc, HiSrc;
2811   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2812          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2813 }
2814 
2815 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2816 // the exponent.
2817 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2818   MVT VT = Op.getSimpleValueType();
2819   unsigned EltSize = VT.getScalarSizeInBits();
2820   SDValue Src = Op.getOperand(0);
2821   SDLoc DL(Op);
2822 
2823   // We need a FP type that can represent the value.
2824   // TODO: Use f16 for i8 when possible?
2825   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2826   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2827 
2828   // Legal types should have been checked in the RISCVTargetLowering
2829   // constructor.
2830   // TODO: Splitting may make sense in some cases.
2831   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2832          "Expected legal float type!");
2833 
2834   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2835   // The trailing zero count is equal to log2 of this single bit value.
2836   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2837     SDValue Neg =
2838         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2839     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2840   }
2841 
2842   // We have a legal FP type, convert to it.
2843   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2844   // Bitcast to integer and shift the exponent to the LSB.
2845   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2846   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2847   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2848   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2849                               DAG.getConstant(ShiftAmt, DL, IntVT));
2850   // Truncate back to original type to allow vnsrl.
2851   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2852   // The exponent contains log2 of the value in biased form.
2853   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2854 
2855   // For trailing zeros, we just need to subtract the bias.
2856   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2857     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2858                        DAG.getConstant(ExponentBias, DL, VT));
2859 
2860   // For leading zeros, we need to remove the bias and convert from log2 to
2861   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2862   unsigned Adjust = ExponentBias + (EltSize - 1);
2863   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2864 }
2865 
2866 // While RVV has alignment restrictions, we should always be able to load as a
2867 // legal equivalently-sized byte-typed vector instead. This method is
2868 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2869 // the load is already correctly-aligned, it returns SDValue().
2870 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2871                                                     SelectionDAG &DAG) const {
2872   auto *Load = cast<LoadSDNode>(Op);
2873   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2874 
2875   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2876                                      Load->getMemoryVT(),
2877                                      *Load->getMemOperand()))
2878     return SDValue();
2879 
2880   SDLoc DL(Op);
2881   MVT VT = Op.getSimpleValueType();
2882   unsigned EltSizeBits = VT.getScalarSizeInBits();
2883   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2884          "Unexpected unaligned RVV load type");
2885   MVT NewVT =
2886       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2887   assert(NewVT.isValid() &&
2888          "Expecting equally-sized RVV vector types to be legal");
2889   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2890                           Load->getPointerInfo(), Load->getOriginalAlign(),
2891                           Load->getMemOperand()->getFlags());
2892   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2893 }
2894 
2895 // While RVV has alignment restrictions, we should always be able to store as a
2896 // legal equivalently-sized byte-typed vector instead. This method is
2897 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2898 // returns SDValue() if the store is already correctly aligned.
2899 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2900                                                      SelectionDAG &DAG) const {
2901   auto *Store = cast<StoreSDNode>(Op);
2902   assert(Store && Store->getValue().getValueType().isVector() &&
2903          "Expected vector store");
2904 
2905   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2906                                      Store->getMemoryVT(),
2907                                      *Store->getMemOperand()))
2908     return SDValue();
2909 
2910   SDLoc DL(Op);
2911   SDValue StoredVal = Store->getValue();
2912   MVT VT = StoredVal.getSimpleValueType();
2913   unsigned EltSizeBits = VT.getScalarSizeInBits();
2914   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2915          "Unexpected unaligned RVV store type");
2916   MVT NewVT =
2917       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2918   assert(NewVT.isValid() &&
2919          "Expecting equally-sized RVV vector types to be legal");
2920   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2921   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2922                       Store->getPointerInfo(), Store->getOriginalAlign(),
2923                       Store->getMemOperand()->getFlags());
2924 }
2925 
2926 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2927                                             SelectionDAG &DAG) const {
2928   switch (Op.getOpcode()) {
2929   default:
2930     report_fatal_error("unimplemented operand");
2931   case ISD::GlobalAddress:
2932     return lowerGlobalAddress(Op, DAG);
2933   case ISD::BlockAddress:
2934     return lowerBlockAddress(Op, DAG);
2935   case ISD::ConstantPool:
2936     return lowerConstantPool(Op, DAG);
2937   case ISD::JumpTable:
2938     return lowerJumpTable(Op, DAG);
2939   case ISD::GlobalTLSAddress:
2940     return lowerGlobalTLSAddress(Op, DAG);
2941   case ISD::SELECT:
2942     return lowerSELECT(Op, DAG);
2943   case ISD::BRCOND:
2944     return lowerBRCOND(Op, DAG);
2945   case ISD::VASTART:
2946     return lowerVASTART(Op, DAG);
2947   case ISD::FRAMEADDR:
2948     return lowerFRAMEADDR(Op, DAG);
2949   case ISD::RETURNADDR:
2950     return lowerRETURNADDR(Op, DAG);
2951   case ISD::SHL_PARTS:
2952     return lowerShiftLeftParts(Op, DAG);
2953   case ISD::SRA_PARTS:
2954     return lowerShiftRightParts(Op, DAG, true);
2955   case ISD::SRL_PARTS:
2956     return lowerShiftRightParts(Op, DAG, false);
2957   case ISD::BITCAST: {
2958     SDLoc DL(Op);
2959     EVT VT = Op.getValueType();
2960     SDValue Op0 = Op.getOperand(0);
2961     EVT Op0VT = Op0.getValueType();
2962     MVT XLenVT = Subtarget.getXLenVT();
2963     if (VT.isFixedLengthVector()) {
2964       // We can handle fixed length vector bitcasts with a simple replacement
2965       // in isel.
2966       if (Op0VT.isFixedLengthVector())
2967         return Op;
2968       // When bitcasting from scalar to fixed-length vector, insert the scalar
2969       // into a one-element vector of the result type, and perform a vector
2970       // bitcast.
2971       if (!Op0VT.isVector()) {
2972         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2973         if (!isTypeLegal(BVT))
2974           return SDValue();
2975         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2976                                               DAG.getUNDEF(BVT), Op0,
2977                                               DAG.getConstant(0, DL, XLenVT)));
2978       }
2979       return SDValue();
2980     }
2981     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2982     // thus: bitcast the vector to a one-element vector type whose element type
2983     // is the same as the result type, and extract the first element.
2984     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2985       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2986       if (!isTypeLegal(BVT))
2987         return SDValue();
2988       SDValue BVec = DAG.getBitcast(BVT, Op0);
2989       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2990                          DAG.getConstant(0, DL, XLenVT));
2991     }
2992     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2993       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2994       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2995       return FPConv;
2996     }
2997     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2998         Subtarget.hasStdExtF()) {
2999       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3000       SDValue FPConv =
3001           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3002       return FPConv;
3003     }
3004     return SDValue();
3005   }
3006   case ISD::INTRINSIC_WO_CHAIN:
3007     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3008   case ISD::INTRINSIC_W_CHAIN:
3009     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3010   case ISD::INTRINSIC_VOID:
3011     return LowerINTRINSIC_VOID(Op, DAG);
3012   case ISD::BSWAP:
3013   case ISD::BITREVERSE: {
3014     MVT VT = Op.getSimpleValueType();
3015     SDLoc DL(Op);
3016     if (Subtarget.hasStdExtZbp()) {
3017       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3018       // Start with the maximum immediate value which is the bitwidth - 1.
3019       unsigned Imm = VT.getSizeInBits() - 1;
3020       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3021       if (Op.getOpcode() == ISD::BSWAP)
3022         Imm &= ~0x7U;
3023       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3024                          DAG.getConstant(Imm, DL, VT));
3025     }
3026     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3027     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3028     // Expand bitreverse to a bswap(rev8) followed by brev8.
3029     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3030     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3031     // as brev8 by an isel pattern.
3032     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3033                        DAG.getConstant(7, DL, VT));
3034   }
3035   case ISD::FSHL:
3036   case ISD::FSHR: {
3037     MVT VT = Op.getSimpleValueType();
3038     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3039     SDLoc DL(Op);
3040     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3041     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3042     // accidentally setting the extra bit.
3043     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3044     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3045                                 DAG.getConstant(ShAmtWidth, DL, VT));
3046     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3047     // instruction use different orders. fshl will return its first operand for
3048     // shift of zero, fshr will return its second operand. fsl and fsr both
3049     // return rs1 so the ISD nodes need to have different operand orders.
3050     // Shift amount is in rs2.
3051     SDValue Op0 = Op.getOperand(0);
3052     SDValue Op1 = Op.getOperand(1);
3053     unsigned Opc = RISCVISD::FSL;
3054     if (Op.getOpcode() == ISD::FSHR) {
3055       std::swap(Op0, Op1);
3056       Opc = RISCVISD::FSR;
3057     }
3058     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3059   }
3060   case ISD::TRUNCATE:
3061     // Only custom-lower vector truncates
3062     if (!Op.getSimpleValueType().isVector())
3063       return Op;
3064     return lowerVectorTruncLike(Op, DAG);
3065   case ISD::ANY_EXTEND:
3066   case ISD::ZERO_EXTEND:
3067     if (Op.getOperand(0).getValueType().isVector() &&
3068         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3069       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3070     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3071   case ISD::SIGN_EXTEND:
3072     if (Op.getOperand(0).getValueType().isVector() &&
3073         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3074       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3075     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3076   case ISD::SPLAT_VECTOR_PARTS:
3077     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3078   case ISD::INSERT_VECTOR_ELT:
3079     return lowerINSERT_VECTOR_ELT(Op, DAG);
3080   case ISD::EXTRACT_VECTOR_ELT:
3081     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3082   case ISD::VSCALE: {
3083     MVT VT = Op.getSimpleValueType();
3084     SDLoc DL(Op);
3085     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3086     // We define our scalable vector types for lmul=1 to use a 64 bit known
3087     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3088     // vscale as VLENB / 8.
3089     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3090     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3091       report_fatal_error("Support for VLEN==32 is incomplete.");
3092     // We assume VLENB is a multiple of 8. We manually choose the best shift
3093     // here because SimplifyDemandedBits isn't always able to simplify it.
3094     uint64_t Val = Op.getConstantOperandVal(0);
3095     if (isPowerOf2_64(Val)) {
3096       uint64_t Log2 = Log2_64(Val);
3097       if (Log2 < 3)
3098         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3099                            DAG.getConstant(3 - Log2, DL, VT));
3100       if (Log2 > 3)
3101         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3102                            DAG.getConstant(Log2 - 3, DL, VT));
3103       return VLENB;
3104     }
3105     // If the multiplier is a multiple of 8, scale it down to avoid needing
3106     // to shift the VLENB value.
3107     if ((Val % 8) == 0)
3108       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3109                          DAG.getConstant(Val / 8, DL, VT));
3110 
3111     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3112                                  DAG.getConstant(3, DL, VT));
3113     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3114   }
3115   case ISD::FPOWI: {
3116     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3117     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3118     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3119         Op.getOperand(1).getValueType() == MVT::i32) {
3120       SDLoc DL(Op);
3121       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3122       SDValue Powi =
3123           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3124       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3125                          DAG.getIntPtrConstant(0, DL));
3126     }
3127     return SDValue();
3128   }
3129   case ISD::FP_EXTEND:
3130   case ISD::FP_ROUND:
3131     if (!Op.getValueType().isVector())
3132       return Op;
3133     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3134   case ISD::FP_TO_SINT:
3135   case ISD::FP_TO_UINT:
3136   case ISD::SINT_TO_FP:
3137   case ISD::UINT_TO_FP: {
3138     // RVV can only do fp<->int conversions to types half/double the size as
3139     // the source. We custom-lower any conversions that do two hops into
3140     // sequences.
3141     MVT VT = Op.getSimpleValueType();
3142     if (!VT.isVector())
3143       return Op;
3144     SDLoc DL(Op);
3145     SDValue Src = Op.getOperand(0);
3146     MVT EltVT = VT.getVectorElementType();
3147     MVT SrcVT = Src.getSimpleValueType();
3148     MVT SrcEltVT = SrcVT.getVectorElementType();
3149     unsigned EltSize = EltVT.getSizeInBits();
3150     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3151     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3152            "Unexpected vector element types");
3153 
3154     bool IsInt2FP = SrcEltVT.isInteger();
3155     // Widening conversions
3156     if (EltSize > (2 * SrcEltSize)) {
3157       if (IsInt2FP) {
3158         // Do a regular integer sign/zero extension then convert to float.
3159         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3160                                       VT.getVectorElementCount());
3161         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3162                                  ? ISD::ZERO_EXTEND
3163                                  : ISD::SIGN_EXTEND;
3164         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3165         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3166       }
3167       // FP2Int
3168       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3169       // Do one doubling fp_extend then complete the operation by converting
3170       // to int.
3171       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3172       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3173       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3174     }
3175 
3176     // Narrowing conversions
3177     if (SrcEltSize > (2 * EltSize)) {
3178       if (IsInt2FP) {
3179         // One narrowing int_to_fp, then an fp_round.
3180         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3181         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3182         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3183         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3184       }
3185       // FP2Int
3186       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3187       // representable by the integer, the result is poison.
3188       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3189                                     VT.getVectorElementCount());
3190       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3191       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3192     }
3193 
3194     // Scalable vectors can exit here. Patterns will handle equally-sized
3195     // conversions halving/doubling ones.
3196     if (!VT.isFixedLengthVector())
3197       return Op;
3198 
3199     // For fixed-length vectors we lower to a custom "VL" node.
3200     unsigned RVVOpc = 0;
3201     switch (Op.getOpcode()) {
3202     default:
3203       llvm_unreachable("Impossible opcode");
3204     case ISD::FP_TO_SINT:
3205       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3206       break;
3207     case ISD::FP_TO_UINT:
3208       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3209       break;
3210     case ISD::SINT_TO_FP:
3211       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3212       break;
3213     case ISD::UINT_TO_FP:
3214       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3215       break;
3216     }
3217 
3218     MVT ContainerVT, SrcContainerVT;
3219     // Derive the reference container type from the larger vector type.
3220     if (SrcEltSize > EltSize) {
3221       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3222       ContainerVT =
3223           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3224     } else {
3225       ContainerVT = getContainerForFixedLengthVector(VT);
3226       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3227     }
3228 
3229     SDValue Mask, VL;
3230     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3231 
3232     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3233     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3234     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3235   }
3236   case ISD::FP_TO_SINT_SAT:
3237   case ISD::FP_TO_UINT_SAT:
3238     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3239   case ISD::FTRUNC:
3240   case ISD::FCEIL:
3241   case ISD::FFLOOR:
3242     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3243   case ISD::FROUND:
3244     return lowerFROUND(Op, DAG);
3245   case ISD::VECREDUCE_ADD:
3246   case ISD::VECREDUCE_UMAX:
3247   case ISD::VECREDUCE_SMAX:
3248   case ISD::VECREDUCE_UMIN:
3249   case ISD::VECREDUCE_SMIN:
3250     return lowerVECREDUCE(Op, DAG);
3251   case ISD::VECREDUCE_AND:
3252   case ISD::VECREDUCE_OR:
3253   case ISD::VECREDUCE_XOR:
3254     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3255       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3256     return lowerVECREDUCE(Op, DAG);
3257   case ISD::VECREDUCE_FADD:
3258   case ISD::VECREDUCE_SEQ_FADD:
3259   case ISD::VECREDUCE_FMIN:
3260   case ISD::VECREDUCE_FMAX:
3261     return lowerFPVECREDUCE(Op, DAG);
3262   case ISD::VP_REDUCE_ADD:
3263   case ISD::VP_REDUCE_UMAX:
3264   case ISD::VP_REDUCE_SMAX:
3265   case ISD::VP_REDUCE_UMIN:
3266   case ISD::VP_REDUCE_SMIN:
3267   case ISD::VP_REDUCE_FADD:
3268   case ISD::VP_REDUCE_SEQ_FADD:
3269   case ISD::VP_REDUCE_FMIN:
3270   case ISD::VP_REDUCE_FMAX:
3271     return lowerVPREDUCE(Op, DAG);
3272   case ISD::VP_REDUCE_AND:
3273   case ISD::VP_REDUCE_OR:
3274   case ISD::VP_REDUCE_XOR:
3275     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3276       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3277     return lowerVPREDUCE(Op, DAG);
3278   case ISD::INSERT_SUBVECTOR:
3279     return lowerINSERT_SUBVECTOR(Op, DAG);
3280   case ISD::EXTRACT_SUBVECTOR:
3281     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3282   case ISD::STEP_VECTOR:
3283     return lowerSTEP_VECTOR(Op, DAG);
3284   case ISD::VECTOR_REVERSE:
3285     return lowerVECTOR_REVERSE(Op, DAG);
3286   case ISD::VECTOR_SPLICE:
3287     return lowerVECTOR_SPLICE(Op, DAG);
3288   case ISD::BUILD_VECTOR:
3289     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3290   case ISD::SPLAT_VECTOR:
3291     if (Op.getValueType().getVectorElementType() == MVT::i1)
3292       return lowerVectorMaskSplat(Op, DAG);
3293     return SDValue();
3294   case ISD::VECTOR_SHUFFLE:
3295     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3296   case ISD::CONCAT_VECTORS: {
3297     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3298     // better than going through the stack, as the default expansion does.
3299     SDLoc DL(Op);
3300     MVT VT = Op.getSimpleValueType();
3301     unsigned NumOpElts =
3302         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3303     SDValue Vec = DAG.getUNDEF(VT);
3304     for (const auto &OpIdx : enumerate(Op->ops())) {
3305       SDValue SubVec = OpIdx.value();
3306       // Don't insert undef subvectors.
3307       if (SubVec.isUndef())
3308         continue;
3309       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3310                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3311     }
3312     return Vec;
3313   }
3314   case ISD::LOAD:
3315     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3316       return V;
3317     if (Op.getValueType().isFixedLengthVector())
3318       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3319     return Op;
3320   case ISD::STORE:
3321     if (auto V = expandUnalignedRVVStore(Op, DAG))
3322       return V;
3323     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3324       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3325     return Op;
3326   case ISD::MLOAD:
3327   case ISD::VP_LOAD:
3328     return lowerMaskedLoad(Op, DAG);
3329   case ISD::MSTORE:
3330   case ISD::VP_STORE:
3331     return lowerMaskedStore(Op, DAG);
3332   case ISD::SETCC:
3333     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3334   case ISD::ADD:
3335     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3336   case ISD::SUB:
3337     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3338   case ISD::MUL:
3339     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3340   case ISD::MULHS:
3341     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3342   case ISD::MULHU:
3343     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3344   case ISD::AND:
3345     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3346                                               RISCVISD::AND_VL);
3347   case ISD::OR:
3348     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3349                                               RISCVISD::OR_VL);
3350   case ISD::XOR:
3351     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3352                                               RISCVISD::XOR_VL);
3353   case ISD::SDIV:
3354     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3355   case ISD::SREM:
3356     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3357   case ISD::UDIV:
3358     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3359   case ISD::UREM:
3360     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3361   case ISD::SHL:
3362   case ISD::SRA:
3363   case ISD::SRL:
3364     if (Op.getSimpleValueType().isFixedLengthVector())
3365       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3366     // This can be called for an i32 shift amount that needs to be promoted.
3367     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3368            "Unexpected custom legalisation");
3369     return SDValue();
3370   case ISD::SADDSAT:
3371     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3372   case ISD::UADDSAT:
3373     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3374   case ISD::SSUBSAT:
3375     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3376   case ISD::USUBSAT:
3377     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3378   case ISD::FADD:
3379     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3380   case ISD::FSUB:
3381     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3382   case ISD::FMUL:
3383     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3384   case ISD::FDIV:
3385     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3386   case ISD::FNEG:
3387     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3388   case ISD::FABS:
3389     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3390   case ISD::FSQRT:
3391     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3392   case ISD::FMA:
3393     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3394   case ISD::SMIN:
3395     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3396   case ISD::SMAX:
3397     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3398   case ISD::UMIN:
3399     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3400   case ISD::UMAX:
3401     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3402   case ISD::FMINNUM:
3403     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3404   case ISD::FMAXNUM:
3405     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3406   case ISD::ABS:
3407     return lowerABS(Op, DAG);
3408   case ISD::CTLZ_ZERO_UNDEF:
3409   case ISD::CTTZ_ZERO_UNDEF:
3410     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3411   case ISD::VSELECT:
3412     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3413   case ISD::FCOPYSIGN:
3414     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3415   case ISD::MGATHER:
3416   case ISD::VP_GATHER:
3417     return lowerMaskedGather(Op, DAG);
3418   case ISD::MSCATTER:
3419   case ISD::VP_SCATTER:
3420     return lowerMaskedScatter(Op, DAG);
3421   case ISD::FLT_ROUNDS_:
3422     return lowerGET_ROUNDING(Op, DAG);
3423   case ISD::SET_ROUNDING:
3424     return lowerSET_ROUNDING(Op, DAG);
3425   case ISD::VP_SELECT:
3426     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3427   case ISD::VP_MERGE:
3428     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3429   case ISD::VP_ADD:
3430     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3431   case ISD::VP_SUB:
3432     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3433   case ISD::VP_MUL:
3434     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3435   case ISD::VP_SDIV:
3436     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3437   case ISD::VP_UDIV:
3438     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3439   case ISD::VP_SREM:
3440     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3441   case ISD::VP_UREM:
3442     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3443   case ISD::VP_AND:
3444     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3445   case ISD::VP_OR:
3446     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3447   case ISD::VP_XOR:
3448     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3449   case ISD::VP_ASHR:
3450     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3451   case ISD::VP_LSHR:
3452     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3453   case ISD::VP_SHL:
3454     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3455   case ISD::VP_FADD:
3456     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3457   case ISD::VP_FSUB:
3458     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3459   case ISD::VP_FMUL:
3460     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3461   case ISD::VP_FDIV:
3462     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3463   case ISD::VP_FNEG:
3464     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3465   case ISD::VP_FMA:
3466     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3467   case ISD::VP_SIGN_EXTEND:
3468   case ISD::VP_ZERO_EXTEND:
3469     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3470       return lowerVPExtMaskOp(Op, DAG);
3471     return lowerVPOp(Op, DAG,
3472                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3473                          ? RISCVISD::VSEXT_VL
3474                          : RISCVISD::VZEXT_VL);
3475   case ISD::VP_TRUNCATE:
3476     return lowerVectorTruncLike(Op, DAG);
3477   case ISD::VP_FP_EXTEND:
3478   case ISD::VP_FP_ROUND:
3479     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3480   case ISD::VP_FPTOSI:
3481     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3482   case ISD::VP_FPTOUI:
3483     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3484   case ISD::VP_SITOFP:
3485     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3486   case ISD::VP_UITOFP:
3487     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3488   case ISD::VP_SETCC:
3489     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3490       return lowerVPSetCCMaskOp(Op, DAG);
3491     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3492   }
3493 }
3494 
3495 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3496                              SelectionDAG &DAG, unsigned Flags) {
3497   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3498 }
3499 
3500 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3501                              SelectionDAG &DAG, unsigned Flags) {
3502   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3503                                    Flags);
3504 }
3505 
3506 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3507                              SelectionDAG &DAG, unsigned Flags) {
3508   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3509                                    N->getOffset(), Flags);
3510 }
3511 
3512 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3513                              SelectionDAG &DAG, unsigned Flags) {
3514   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3515 }
3516 
3517 template <class NodeTy>
3518 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3519                                      bool IsLocal) const {
3520   SDLoc DL(N);
3521   EVT Ty = getPointerTy(DAG.getDataLayout());
3522 
3523   if (isPositionIndependent()) {
3524     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3525     if (IsLocal)
3526       // Use PC-relative addressing to access the symbol. This generates the
3527       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3528       // %pcrel_lo(auipc)).
3529       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3530 
3531     // Use PC-relative addressing to access the GOT for this symbol, then load
3532     // the address from the GOT. This generates the pattern (PseudoLA sym),
3533     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3534     SDValue Load =
3535         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3536     MachineFunction &MF = DAG.getMachineFunction();
3537     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3538         MachinePointerInfo::getGOT(MF),
3539         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3540             MachineMemOperand::MOInvariant,
3541         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3542     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3543     return Load;
3544   }
3545 
3546   switch (getTargetMachine().getCodeModel()) {
3547   default:
3548     report_fatal_error("Unsupported code model for lowering");
3549   case CodeModel::Small: {
3550     // Generate a sequence for accessing addresses within the first 2 GiB of
3551     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3552     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3553     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3554     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3555     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3556   }
3557   case CodeModel::Medium: {
3558     // Generate a sequence for accessing addresses within any 2GiB range within
3559     // the address space. This generates the pattern (PseudoLLA sym), which
3560     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3561     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3562     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3563   }
3564   }
3565 }
3566 
3567 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3568     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3569 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3570     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3571 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3572     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3573 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3574     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3575 
3576 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3577                                                 SelectionDAG &DAG) const {
3578   SDLoc DL(Op);
3579   EVT Ty = Op.getValueType();
3580   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3581   int64_t Offset = N->getOffset();
3582   MVT XLenVT = Subtarget.getXLenVT();
3583 
3584   const GlobalValue *GV = N->getGlobal();
3585   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3586   SDValue Addr = getAddr(N, DAG, IsLocal);
3587 
3588   // In order to maximise the opportunity for common subexpression elimination,
3589   // emit a separate ADD node for the global address offset instead of folding
3590   // it in the global address node. Later peephole optimisations may choose to
3591   // fold it back in when profitable.
3592   if (Offset != 0)
3593     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3594                        DAG.getConstant(Offset, DL, XLenVT));
3595   return Addr;
3596 }
3597 
3598 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3599                                                SelectionDAG &DAG) const {
3600   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3601 
3602   return getAddr(N, DAG);
3603 }
3604 
3605 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3606                                                SelectionDAG &DAG) const {
3607   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3608 
3609   return getAddr(N, DAG);
3610 }
3611 
3612 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3613                                             SelectionDAG &DAG) const {
3614   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3615 
3616   return getAddr(N, DAG);
3617 }
3618 
3619 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3620                                               SelectionDAG &DAG,
3621                                               bool UseGOT) const {
3622   SDLoc DL(N);
3623   EVT Ty = getPointerTy(DAG.getDataLayout());
3624   const GlobalValue *GV = N->getGlobal();
3625   MVT XLenVT = Subtarget.getXLenVT();
3626 
3627   if (UseGOT) {
3628     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3629     // load the address from the GOT and add the thread pointer. This generates
3630     // the pattern (PseudoLA_TLS_IE sym), which expands to
3631     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3632     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3633     SDValue Load =
3634         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3635     MachineFunction &MF = DAG.getMachineFunction();
3636     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3637         MachinePointerInfo::getGOT(MF),
3638         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3639             MachineMemOperand::MOInvariant,
3640         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3641     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3642 
3643     // Add the thread pointer.
3644     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3645     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3646   }
3647 
3648   // Generate a sequence for accessing the address relative to the thread
3649   // pointer, with the appropriate adjustment for the thread pointer offset.
3650   // This generates the pattern
3651   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3652   SDValue AddrHi =
3653       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3654   SDValue AddrAdd =
3655       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3656   SDValue AddrLo =
3657       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3658 
3659   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3660   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3661   SDValue MNAdd = SDValue(
3662       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3663       0);
3664   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3665 }
3666 
3667 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3668                                                SelectionDAG &DAG) const {
3669   SDLoc DL(N);
3670   EVT Ty = getPointerTy(DAG.getDataLayout());
3671   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3672   const GlobalValue *GV = N->getGlobal();
3673 
3674   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3675   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3676   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3677   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3678   SDValue Load =
3679       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3680 
3681   // Prepare argument list to generate call.
3682   ArgListTy Args;
3683   ArgListEntry Entry;
3684   Entry.Node = Load;
3685   Entry.Ty = CallTy;
3686   Args.push_back(Entry);
3687 
3688   // Setup call to __tls_get_addr.
3689   TargetLowering::CallLoweringInfo CLI(DAG);
3690   CLI.setDebugLoc(DL)
3691       .setChain(DAG.getEntryNode())
3692       .setLibCallee(CallingConv::C, CallTy,
3693                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3694                     std::move(Args));
3695 
3696   return LowerCallTo(CLI).first;
3697 }
3698 
3699 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3700                                                    SelectionDAG &DAG) const {
3701   SDLoc DL(Op);
3702   EVT Ty = Op.getValueType();
3703   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3704   int64_t Offset = N->getOffset();
3705   MVT XLenVT = Subtarget.getXLenVT();
3706 
3707   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3708 
3709   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3710       CallingConv::GHC)
3711     report_fatal_error("In GHC calling convention TLS is not supported");
3712 
3713   SDValue Addr;
3714   switch (Model) {
3715   case TLSModel::LocalExec:
3716     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3717     break;
3718   case TLSModel::InitialExec:
3719     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3720     break;
3721   case TLSModel::LocalDynamic:
3722   case TLSModel::GeneralDynamic:
3723     Addr = getDynamicTLSAddr(N, DAG);
3724     break;
3725   }
3726 
3727   // In order to maximise the opportunity for common subexpression elimination,
3728   // emit a separate ADD node for the global address offset instead of folding
3729   // it in the global address node. Later peephole optimisations may choose to
3730   // fold it back in when profitable.
3731   if (Offset != 0)
3732     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3733                        DAG.getConstant(Offset, DL, XLenVT));
3734   return Addr;
3735 }
3736 
3737 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3738   SDValue CondV = Op.getOperand(0);
3739   SDValue TrueV = Op.getOperand(1);
3740   SDValue FalseV = Op.getOperand(2);
3741   SDLoc DL(Op);
3742   MVT VT = Op.getSimpleValueType();
3743   MVT XLenVT = Subtarget.getXLenVT();
3744 
3745   // Lower vector SELECTs to VSELECTs by splatting the condition.
3746   if (VT.isVector()) {
3747     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3748     SDValue CondSplat = VT.isScalableVector()
3749                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3750                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3751     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3752   }
3753 
3754   // If the result type is XLenVT and CondV is the output of a SETCC node
3755   // which also operated on XLenVT inputs, then merge the SETCC node into the
3756   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3757   // compare+branch instructions. i.e.:
3758   // (select (setcc lhs, rhs, cc), truev, falsev)
3759   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3760   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3761       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3762     SDValue LHS = CondV.getOperand(0);
3763     SDValue RHS = CondV.getOperand(1);
3764     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3765     ISD::CondCode CCVal = CC->get();
3766 
3767     // Special case for a select of 2 constants that have a diffence of 1.
3768     // Normally this is done by DAGCombine, but if the select is introduced by
3769     // type legalization or op legalization, we miss it. Restricting to SETLT
3770     // case for now because that is what signed saturating add/sub need.
3771     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3772     // but we would probably want to swap the true/false values if the condition
3773     // is SETGE/SETLE to avoid an XORI.
3774     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3775         CCVal == ISD::SETLT) {
3776       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3777       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3778       if (TrueVal - 1 == FalseVal)
3779         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3780       if (TrueVal + 1 == FalseVal)
3781         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3782     }
3783 
3784     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3785 
3786     SDValue TargetCC = DAG.getCondCode(CCVal);
3787     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3788     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3789   }
3790 
3791   // Otherwise:
3792   // (select condv, truev, falsev)
3793   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3794   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3795   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3796 
3797   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3798 
3799   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3800 }
3801 
3802 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3803   SDValue CondV = Op.getOperand(1);
3804   SDLoc DL(Op);
3805   MVT XLenVT = Subtarget.getXLenVT();
3806 
3807   if (CondV.getOpcode() == ISD::SETCC &&
3808       CondV.getOperand(0).getValueType() == XLenVT) {
3809     SDValue LHS = CondV.getOperand(0);
3810     SDValue RHS = CondV.getOperand(1);
3811     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3812 
3813     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3814 
3815     SDValue TargetCC = DAG.getCondCode(CCVal);
3816     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3817                        LHS, RHS, TargetCC, Op.getOperand(2));
3818   }
3819 
3820   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3821                      CondV, DAG.getConstant(0, DL, XLenVT),
3822                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3823 }
3824 
3825 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3826   MachineFunction &MF = DAG.getMachineFunction();
3827   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3828 
3829   SDLoc DL(Op);
3830   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3831                                  getPointerTy(MF.getDataLayout()));
3832 
3833   // vastart just stores the address of the VarArgsFrameIndex slot into the
3834   // memory location argument.
3835   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3836   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3837                       MachinePointerInfo(SV));
3838 }
3839 
3840 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3841                                             SelectionDAG &DAG) const {
3842   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3843   MachineFunction &MF = DAG.getMachineFunction();
3844   MachineFrameInfo &MFI = MF.getFrameInfo();
3845   MFI.setFrameAddressIsTaken(true);
3846   Register FrameReg = RI.getFrameRegister(MF);
3847   int XLenInBytes = Subtarget.getXLen() / 8;
3848 
3849   EVT VT = Op.getValueType();
3850   SDLoc DL(Op);
3851   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3852   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3853   while (Depth--) {
3854     int Offset = -(XLenInBytes * 2);
3855     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3856                               DAG.getIntPtrConstant(Offset, DL));
3857     FrameAddr =
3858         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3859   }
3860   return FrameAddr;
3861 }
3862 
3863 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3864                                              SelectionDAG &DAG) const {
3865   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3866   MachineFunction &MF = DAG.getMachineFunction();
3867   MachineFrameInfo &MFI = MF.getFrameInfo();
3868   MFI.setReturnAddressIsTaken(true);
3869   MVT XLenVT = Subtarget.getXLenVT();
3870   int XLenInBytes = Subtarget.getXLen() / 8;
3871 
3872   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3873     return SDValue();
3874 
3875   EVT VT = Op.getValueType();
3876   SDLoc DL(Op);
3877   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3878   if (Depth) {
3879     int Off = -XLenInBytes;
3880     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3881     SDValue Offset = DAG.getConstant(Off, DL, VT);
3882     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3883                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3884                        MachinePointerInfo());
3885   }
3886 
3887   // Return the value of the return address register, marking it an implicit
3888   // live-in.
3889   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3890   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3891 }
3892 
3893 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3894                                                  SelectionDAG &DAG) const {
3895   SDLoc DL(Op);
3896   SDValue Lo = Op.getOperand(0);
3897   SDValue Hi = Op.getOperand(1);
3898   SDValue Shamt = Op.getOperand(2);
3899   EVT VT = Lo.getValueType();
3900 
3901   // if Shamt-XLEN < 0: // Shamt < XLEN
3902   //   Lo = Lo << Shamt
3903   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3904   // else:
3905   //   Lo = 0
3906   //   Hi = Lo << (Shamt-XLEN)
3907 
3908   SDValue Zero = DAG.getConstant(0, DL, VT);
3909   SDValue One = DAG.getConstant(1, DL, VT);
3910   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3911   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3912   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3913   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3914 
3915   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3916   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3917   SDValue ShiftRightLo =
3918       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3919   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3920   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3921   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3922 
3923   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3924 
3925   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3926   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3927 
3928   SDValue Parts[2] = {Lo, Hi};
3929   return DAG.getMergeValues(Parts, DL);
3930 }
3931 
3932 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3933                                                   bool IsSRA) const {
3934   SDLoc DL(Op);
3935   SDValue Lo = Op.getOperand(0);
3936   SDValue Hi = Op.getOperand(1);
3937   SDValue Shamt = Op.getOperand(2);
3938   EVT VT = Lo.getValueType();
3939 
3940   // SRA expansion:
3941   //   if Shamt-XLEN < 0: // Shamt < XLEN
3942   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3943   //     Hi = Hi >>s Shamt
3944   //   else:
3945   //     Lo = Hi >>s (Shamt-XLEN);
3946   //     Hi = Hi >>s (XLEN-1)
3947   //
3948   // SRL expansion:
3949   //   if Shamt-XLEN < 0: // Shamt < XLEN
3950   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3951   //     Hi = Hi >>u Shamt
3952   //   else:
3953   //     Lo = Hi >>u (Shamt-XLEN);
3954   //     Hi = 0;
3955 
3956   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3957 
3958   SDValue Zero = DAG.getConstant(0, DL, VT);
3959   SDValue One = DAG.getConstant(1, DL, VT);
3960   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3961   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3962   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3963   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3964 
3965   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3966   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3967   SDValue ShiftLeftHi =
3968       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3969   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3970   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3971   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3972   SDValue HiFalse =
3973       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3974 
3975   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3976 
3977   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3978   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3979 
3980   SDValue Parts[2] = {Lo, Hi};
3981   return DAG.getMergeValues(Parts, DL);
3982 }
3983 
3984 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3985 // legal equivalently-sized i8 type, so we can use that as a go-between.
3986 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3987                                                   SelectionDAG &DAG) const {
3988   SDLoc DL(Op);
3989   MVT VT = Op.getSimpleValueType();
3990   SDValue SplatVal = Op.getOperand(0);
3991   // All-zeros or all-ones splats are handled specially.
3992   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3993     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3994     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3995   }
3996   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3997     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3998     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3999   }
4000   MVT XLenVT = Subtarget.getXLenVT();
4001   assert(SplatVal.getValueType() == XLenVT &&
4002          "Unexpected type for i1 splat value");
4003   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4004   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4005                          DAG.getConstant(1, DL, XLenVT));
4006   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4007   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4008   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4009 }
4010 
4011 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4012 // illegal (currently only vXi64 RV32).
4013 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4014 // them to VMV_V_X_VL.
4015 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4016                                                      SelectionDAG &DAG) const {
4017   SDLoc DL(Op);
4018   MVT VecVT = Op.getSimpleValueType();
4019   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4020          "Unexpected SPLAT_VECTOR_PARTS lowering");
4021 
4022   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4023   SDValue Lo = Op.getOperand(0);
4024   SDValue Hi = Op.getOperand(1);
4025 
4026   if (VecVT.isFixedLengthVector()) {
4027     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4028     SDLoc DL(Op);
4029     SDValue Mask, VL;
4030     std::tie(Mask, VL) =
4031         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4032 
4033     SDValue Res =
4034         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4035     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4036   }
4037 
4038   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4039     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4040     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4041     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4042     // node in order to try and match RVV vector/scalar instructions.
4043     if ((LoC >> 31) == HiC)
4044       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4045                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4046   }
4047 
4048   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4049   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4050       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4051       Hi.getConstantOperandVal(1) == 31)
4052     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4053                        DAG.getRegister(RISCV::X0, MVT::i32));
4054 
4055   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4056   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4057                      DAG.getUNDEF(VecVT), Lo, Hi,
4058                      DAG.getRegister(RISCV::X0, MVT::i32));
4059 }
4060 
4061 // Custom-lower extensions from mask vectors by using a vselect either with 1
4062 // for zero/any-extension or -1 for sign-extension:
4063 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4064 // Note that any-extension is lowered identically to zero-extension.
4065 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4066                                                 int64_t ExtTrueVal) const {
4067   SDLoc DL(Op);
4068   MVT VecVT = Op.getSimpleValueType();
4069   SDValue Src = Op.getOperand(0);
4070   // Only custom-lower extensions from mask types
4071   assert(Src.getValueType().isVector() &&
4072          Src.getValueType().getVectorElementType() == MVT::i1);
4073 
4074   if (VecVT.isScalableVector()) {
4075     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4076     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4077     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4078   }
4079 
4080   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4081   MVT I1ContainerVT =
4082       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4083 
4084   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4085 
4086   SDValue Mask, VL;
4087   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4088 
4089   MVT XLenVT = Subtarget.getXLenVT();
4090   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4091   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4092 
4093   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4094                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4095   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4096                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4097   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4098                                SplatTrueVal, SplatZero, VL);
4099 
4100   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4101 }
4102 
4103 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4104     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4105   MVT ExtVT = Op.getSimpleValueType();
4106   // Only custom-lower extensions from fixed-length vector types.
4107   if (!ExtVT.isFixedLengthVector())
4108     return Op;
4109   MVT VT = Op.getOperand(0).getSimpleValueType();
4110   // Grab the canonical container type for the extended type. Infer the smaller
4111   // type from that to ensure the same number of vector elements, as we know
4112   // the LMUL will be sufficient to hold the smaller type.
4113   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4114   // Get the extended container type manually to ensure the same number of
4115   // vector elements between source and dest.
4116   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4117                                      ContainerExtVT.getVectorElementCount());
4118 
4119   SDValue Op1 =
4120       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4121 
4122   SDLoc DL(Op);
4123   SDValue Mask, VL;
4124   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4125 
4126   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4127 
4128   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4129 }
4130 
4131 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4132 // setcc operation:
4133 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4134 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4135                                                       SelectionDAG &DAG) const {
4136   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4137   SDLoc DL(Op);
4138   EVT MaskVT = Op.getValueType();
4139   // Only expect to custom-lower truncations to mask types
4140   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4141          "Unexpected type for vector mask lowering");
4142   SDValue Src = Op.getOperand(0);
4143   MVT VecVT = Src.getSimpleValueType();
4144   SDValue Mask, VL;
4145   if (IsVPTrunc) {
4146     Mask = Op.getOperand(1);
4147     VL = Op.getOperand(2);
4148   }
4149   // If this is a fixed vector, we need to convert it to a scalable vector.
4150   MVT ContainerVT = VecVT;
4151 
4152   if (VecVT.isFixedLengthVector()) {
4153     ContainerVT = getContainerForFixedLengthVector(VecVT);
4154     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4155     if (IsVPTrunc) {
4156       MVT MaskContainerVT =
4157           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4158       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4159     }
4160   }
4161 
4162   if (!IsVPTrunc) {
4163     std::tie(Mask, VL) =
4164         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4165   }
4166 
4167   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4168   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4169 
4170   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4171                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4172   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4173                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4174 
4175   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4176   SDValue Trunc =
4177       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4178   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4179                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4180   if (MaskVT.isFixedLengthVector())
4181     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4182   return Trunc;
4183 }
4184 
4185 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4186                                                   SelectionDAG &DAG) const {
4187   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4188   SDLoc DL(Op);
4189 
4190   MVT VT = Op.getSimpleValueType();
4191   // Only custom-lower vector truncates
4192   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4193 
4194   // Truncates to mask types are handled differently
4195   if (VT.getVectorElementType() == MVT::i1)
4196     return lowerVectorMaskTruncLike(Op, DAG);
4197 
4198   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4199   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4200   // truncate by one power of two at a time.
4201   MVT DstEltVT = VT.getVectorElementType();
4202 
4203   SDValue Src = Op.getOperand(0);
4204   MVT SrcVT = Src.getSimpleValueType();
4205   MVT SrcEltVT = SrcVT.getVectorElementType();
4206 
4207   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4208          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4209          "Unexpected vector truncate lowering");
4210 
4211   MVT ContainerVT = SrcVT;
4212   SDValue Mask, VL;
4213   if (IsVPTrunc) {
4214     Mask = Op.getOperand(1);
4215     VL = Op.getOperand(2);
4216   }
4217   if (SrcVT.isFixedLengthVector()) {
4218     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4219     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4220     if (IsVPTrunc) {
4221       MVT MaskVT = getMaskTypeFor(ContainerVT);
4222       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4223     }
4224   }
4225 
4226   SDValue Result = Src;
4227   if (!IsVPTrunc) {
4228     std::tie(Mask, VL) =
4229         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4230   }
4231 
4232   LLVMContext &Context = *DAG.getContext();
4233   const ElementCount Count = ContainerVT.getVectorElementCount();
4234   do {
4235     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4236     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4237     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4238                          Mask, VL);
4239   } while (SrcEltVT != DstEltVT);
4240 
4241   if (SrcVT.isFixedLengthVector())
4242     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4243 
4244   return Result;
4245 }
4246 
4247 SDValue
4248 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4249                                                     SelectionDAG &DAG) const {
4250   bool IsVP =
4251       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4252   bool IsExtend =
4253       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4254   // RVV can only do truncate fp to types half the size as the source. We
4255   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4256   // conversion instruction.
4257   SDLoc DL(Op);
4258   MVT VT = Op.getSimpleValueType();
4259 
4260   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4261 
4262   SDValue Src = Op.getOperand(0);
4263   MVT SrcVT = Src.getSimpleValueType();
4264 
4265   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4266                                      SrcVT.getVectorElementType() != MVT::f16);
4267   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4268                                      SrcVT.getVectorElementType() != MVT::f64);
4269 
4270   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4271 
4272   // Prepare any fixed-length vector operands.
4273   MVT ContainerVT = VT;
4274   SDValue Mask, VL;
4275   if (IsVP) {
4276     Mask = Op.getOperand(1);
4277     VL = Op.getOperand(2);
4278   }
4279   if (VT.isFixedLengthVector()) {
4280     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4281     ContainerVT =
4282         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4283     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4284     if (IsVP) {
4285       MVT MaskVT = getMaskTypeFor(ContainerVT);
4286       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4287     }
4288   }
4289 
4290   if (!IsVP)
4291     std::tie(Mask, VL) =
4292         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4293 
4294   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4295 
4296   if (IsDirectConv) {
4297     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4298     if (VT.isFixedLengthVector())
4299       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4300     return Src;
4301   }
4302 
4303   unsigned InterConvOpc =
4304       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4305 
4306   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4307   SDValue IntermediateConv =
4308       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4309   SDValue Result =
4310       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4311   if (VT.isFixedLengthVector())
4312     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4313   return Result;
4314 }
4315 
4316 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4317 // first position of a vector, and that vector is slid up to the insert index.
4318 // By limiting the active vector length to index+1 and merging with the
4319 // original vector (with an undisturbed tail policy for elements >= VL), we
4320 // achieve the desired result of leaving all elements untouched except the one
4321 // at VL-1, which is replaced with the desired value.
4322 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4323                                                     SelectionDAG &DAG) const {
4324   SDLoc DL(Op);
4325   MVT VecVT = Op.getSimpleValueType();
4326   SDValue Vec = Op.getOperand(0);
4327   SDValue Val = Op.getOperand(1);
4328   SDValue Idx = Op.getOperand(2);
4329 
4330   if (VecVT.getVectorElementType() == MVT::i1) {
4331     // FIXME: For now we just promote to an i8 vector and insert into that,
4332     // but this is probably not optimal.
4333     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4334     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4335     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4336     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4337   }
4338 
4339   MVT ContainerVT = VecVT;
4340   // If the operand is a fixed-length vector, convert to a scalable one.
4341   if (VecVT.isFixedLengthVector()) {
4342     ContainerVT = getContainerForFixedLengthVector(VecVT);
4343     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4344   }
4345 
4346   MVT XLenVT = Subtarget.getXLenVT();
4347 
4348   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4349   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4350   // Even i64-element vectors on RV32 can be lowered without scalar
4351   // legalization if the most-significant 32 bits of the value are not affected
4352   // by the sign-extension of the lower 32 bits.
4353   // TODO: We could also catch sign extensions of a 32-bit value.
4354   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4355     const auto *CVal = cast<ConstantSDNode>(Val);
4356     if (isInt<32>(CVal->getSExtValue())) {
4357       IsLegalInsert = true;
4358       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4359     }
4360   }
4361 
4362   SDValue Mask, VL;
4363   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4364 
4365   SDValue ValInVec;
4366 
4367   if (IsLegalInsert) {
4368     unsigned Opc =
4369         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4370     if (isNullConstant(Idx)) {
4371       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4372       if (!VecVT.isFixedLengthVector())
4373         return Vec;
4374       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4375     }
4376     ValInVec =
4377         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4378   } else {
4379     // On RV32, i64-element vectors must be specially handled to place the
4380     // value at element 0, by using two vslide1up instructions in sequence on
4381     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4382     // this.
4383     SDValue One = DAG.getConstant(1, DL, XLenVT);
4384     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4385     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4386     MVT I32ContainerVT =
4387         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4388     SDValue I32Mask =
4389         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4390     // Limit the active VL to two.
4391     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4392     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4393     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4394     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4395                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4396     // First slide in the hi value, then the lo in underneath it.
4397     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4398                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4399                            I32Mask, InsertI64VL);
4400     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4401                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4402                            I32Mask, InsertI64VL);
4403     // Bitcast back to the right container type.
4404     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4405   }
4406 
4407   // Now that the value is in a vector, slide it into position.
4408   SDValue InsertVL =
4409       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4410   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4411                                 ValInVec, Idx, Mask, InsertVL);
4412   if (!VecVT.isFixedLengthVector())
4413     return Slideup;
4414   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4415 }
4416 
4417 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4418 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4419 // types this is done using VMV_X_S to allow us to glean information about the
4420 // sign bits of the result.
4421 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4422                                                      SelectionDAG &DAG) const {
4423   SDLoc DL(Op);
4424   SDValue Idx = Op.getOperand(1);
4425   SDValue Vec = Op.getOperand(0);
4426   EVT EltVT = Op.getValueType();
4427   MVT VecVT = Vec.getSimpleValueType();
4428   MVT XLenVT = Subtarget.getXLenVT();
4429 
4430   if (VecVT.getVectorElementType() == MVT::i1) {
4431     if (VecVT.isFixedLengthVector()) {
4432       unsigned NumElts = VecVT.getVectorNumElements();
4433       if (NumElts >= 8) {
4434         MVT WideEltVT;
4435         unsigned WidenVecLen;
4436         SDValue ExtractElementIdx;
4437         SDValue ExtractBitIdx;
4438         unsigned MaxEEW = Subtarget.getELEN();
4439         MVT LargestEltVT = MVT::getIntegerVT(
4440             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4441         if (NumElts <= LargestEltVT.getSizeInBits()) {
4442           assert(isPowerOf2_32(NumElts) &&
4443                  "the number of elements should be power of 2");
4444           WideEltVT = MVT::getIntegerVT(NumElts);
4445           WidenVecLen = 1;
4446           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4447           ExtractBitIdx = Idx;
4448         } else {
4449           WideEltVT = LargestEltVT;
4450           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4451           // extract element index = index / element width
4452           ExtractElementIdx = DAG.getNode(
4453               ISD::SRL, DL, XLenVT, Idx,
4454               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4455           // mask bit index = index % element width
4456           ExtractBitIdx = DAG.getNode(
4457               ISD::AND, DL, XLenVT, Idx,
4458               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4459         }
4460         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4461         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4462         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4463                                          Vec, ExtractElementIdx);
4464         // Extract the bit from GPR.
4465         SDValue ShiftRight =
4466             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4467         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4468                            DAG.getConstant(1, DL, XLenVT));
4469       }
4470     }
4471     // Otherwise, promote to an i8 vector and extract from that.
4472     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4473     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4474     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4475   }
4476 
4477   // If this is a fixed vector, we need to convert it to a scalable vector.
4478   MVT ContainerVT = VecVT;
4479   if (VecVT.isFixedLengthVector()) {
4480     ContainerVT = getContainerForFixedLengthVector(VecVT);
4481     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4482   }
4483 
4484   // If the index is 0, the vector is already in the right position.
4485   if (!isNullConstant(Idx)) {
4486     // Use a VL of 1 to avoid processing more elements than we need.
4487     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4488     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4489     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4490                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4491   }
4492 
4493   if (!EltVT.isInteger()) {
4494     // Floating-point extracts are handled in TableGen.
4495     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4496                        DAG.getConstant(0, DL, XLenVT));
4497   }
4498 
4499   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4500   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4501 }
4502 
4503 // Some RVV intrinsics may claim that they want an integer operand to be
4504 // promoted or expanded.
4505 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4506                                            const RISCVSubtarget &Subtarget) {
4507   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4508           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4509          "Unexpected opcode");
4510 
4511   if (!Subtarget.hasVInstructions())
4512     return SDValue();
4513 
4514   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4515   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4516   SDLoc DL(Op);
4517 
4518   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4519       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4520   if (!II || !II->hasScalarOperand())
4521     return SDValue();
4522 
4523   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4524   assert(SplatOp < Op.getNumOperands());
4525 
4526   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4527   SDValue &ScalarOp = Operands[SplatOp];
4528   MVT OpVT = ScalarOp.getSimpleValueType();
4529   MVT XLenVT = Subtarget.getXLenVT();
4530 
4531   // If this isn't a scalar, or its type is XLenVT we're done.
4532   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4533     return SDValue();
4534 
4535   // Simplest case is that the operand needs to be promoted to XLenVT.
4536   if (OpVT.bitsLT(XLenVT)) {
4537     // If the operand is a constant, sign extend to increase our chances
4538     // of being able to use a .vi instruction. ANY_EXTEND would become a
4539     // a zero extend and the simm5 check in isel would fail.
4540     // FIXME: Should we ignore the upper bits in isel instead?
4541     unsigned ExtOpc =
4542         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4543     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4544     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4545   }
4546 
4547   // Use the previous operand to get the vXi64 VT. The result might be a mask
4548   // VT for compares. Using the previous operand assumes that the previous
4549   // operand will never have a smaller element size than a scalar operand and
4550   // that a widening operation never uses SEW=64.
4551   // NOTE: If this fails the below assert, we can probably just find the
4552   // element count from any operand or result and use it to construct the VT.
4553   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4554   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4555 
4556   // The more complex case is when the scalar is larger than XLenVT.
4557   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4558          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4559 
4560   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4561   // instruction to sign-extend since SEW>XLEN.
4562   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4563     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4564     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4565   }
4566 
4567   switch (IntNo) {
4568   case Intrinsic::riscv_vslide1up:
4569   case Intrinsic::riscv_vslide1down:
4570   case Intrinsic::riscv_vslide1up_mask:
4571   case Intrinsic::riscv_vslide1down_mask: {
4572     // We need to special case these when the scalar is larger than XLen.
4573     unsigned NumOps = Op.getNumOperands();
4574     bool IsMasked = NumOps == 7;
4575 
4576     // Convert the vector source to the equivalent nxvXi32 vector.
4577     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4578     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4579 
4580     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4581                                    DAG.getConstant(0, DL, XLenVT));
4582     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4583                                    DAG.getConstant(1, DL, XLenVT));
4584 
4585     // Double the VL since we halved SEW.
4586     SDValue AVL = getVLOperand(Op);
4587     SDValue I32VL;
4588 
4589     // Optimize for constant AVL
4590     if (isa<ConstantSDNode>(AVL)) {
4591       unsigned EltSize = VT.getScalarSizeInBits();
4592       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4593 
4594       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4595       unsigned MaxVLMAX =
4596           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4597 
4598       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4599       unsigned MinVLMAX =
4600           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4601 
4602       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4603       if (AVLInt <= MinVLMAX) {
4604         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4605       } else if (AVLInt >= 2 * MaxVLMAX) {
4606         // Just set vl to VLMAX in this situation
4607         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4608         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4609         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4610         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4611         SDValue SETVLMAX = DAG.getTargetConstant(
4612             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4613         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4614                             LMUL);
4615       } else {
4616         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4617         // is related to the hardware implementation.
4618         // So let the following code handle
4619       }
4620     }
4621     if (!I32VL) {
4622       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4623       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4624       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4625       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4626       SDValue SETVL =
4627           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4628       // Using vsetvli instruction to get actually used length which related to
4629       // the hardware implementation
4630       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4631                                SEW, LMUL);
4632       I32VL =
4633           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4634     }
4635 
4636     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4637 
4638     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4639     // instructions.
4640     SDValue Passthru;
4641     if (IsMasked)
4642       Passthru = DAG.getUNDEF(I32VT);
4643     else
4644       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4645 
4646     if (IntNo == Intrinsic::riscv_vslide1up ||
4647         IntNo == Intrinsic::riscv_vslide1up_mask) {
4648       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4649                         ScalarHi, I32Mask, I32VL);
4650       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4651                         ScalarLo, I32Mask, I32VL);
4652     } else {
4653       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4654                         ScalarLo, I32Mask, I32VL);
4655       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4656                         ScalarHi, I32Mask, I32VL);
4657     }
4658 
4659     // Convert back to nxvXi64.
4660     Vec = DAG.getBitcast(VT, Vec);
4661 
4662     if (!IsMasked)
4663       return Vec;
4664     // Apply mask after the operation.
4665     SDValue Mask = Operands[NumOps - 3];
4666     SDValue MaskedOff = Operands[1];
4667     // Assume Policy operand is the last operand.
4668     uint64_t Policy =
4669         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4670     // We don't need to select maskedoff if it's undef.
4671     if (MaskedOff.isUndef())
4672       return Vec;
4673     // TAMU
4674     if (Policy == RISCVII::TAIL_AGNOSTIC)
4675       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4676                          AVL);
4677     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4678     // It's fine because vmerge does not care mask policy.
4679     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4680                        AVL);
4681   }
4682   }
4683 
4684   // We need to convert the scalar to a splat vector.
4685   SDValue VL = getVLOperand(Op);
4686   assert(VL.getValueType() == XLenVT);
4687   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4688   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4689 }
4690 
4691 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4692                                                      SelectionDAG &DAG) const {
4693   unsigned IntNo = Op.getConstantOperandVal(0);
4694   SDLoc DL(Op);
4695   MVT XLenVT = Subtarget.getXLenVT();
4696 
4697   switch (IntNo) {
4698   default:
4699     break; // Don't custom lower most intrinsics.
4700   case Intrinsic::thread_pointer: {
4701     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4702     return DAG.getRegister(RISCV::X4, PtrVT);
4703   }
4704   case Intrinsic::riscv_orc_b:
4705   case Intrinsic::riscv_brev8: {
4706     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4707     unsigned Opc =
4708         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4709     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4710                        DAG.getConstant(7, DL, XLenVT));
4711   }
4712   case Intrinsic::riscv_grev:
4713   case Intrinsic::riscv_gorc: {
4714     unsigned Opc =
4715         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4716     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4717   }
4718   case Intrinsic::riscv_zip:
4719   case Intrinsic::riscv_unzip: {
4720     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4721     // For i32 the immediate is 15. For i64 the immediate is 31.
4722     unsigned Opc =
4723         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4724     unsigned BitWidth = Op.getValueSizeInBits();
4725     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4726     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4727                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4728   }
4729   case Intrinsic::riscv_shfl:
4730   case Intrinsic::riscv_unshfl: {
4731     unsigned Opc =
4732         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4733     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4734   }
4735   case Intrinsic::riscv_bcompress:
4736   case Intrinsic::riscv_bdecompress: {
4737     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4738                                                        : RISCVISD::BDECOMPRESS;
4739     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4740   }
4741   case Intrinsic::riscv_bfp:
4742     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4743                        Op.getOperand(2));
4744   case Intrinsic::riscv_fsl:
4745     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4746                        Op.getOperand(2), Op.getOperand(3));
4747   case Intrinsic::riscv_fsr:
4748     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4749                        Op.getOperand(2), Op.getOperand(3));
4750   case Intrinsic::riscv_vmv_x_s:
4751     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4752     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4753                        Op.getOperand(1));
4754   case Intrinsic::riscv_vmv_v_x:
4755     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4756                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4757                             Subtarget);
4758   case Intrinsic::riscv_vfmv_v_f:
4759     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4760                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4761   case Intrinsic::riscv_vmv_s_x: {
4762     SDValue Scalar = Op.getOperand(2);
4763 
4764     if (Scalar.getValueType().bitsLE(XLenVT)) {
4765       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4766       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4767                          Op.getOperand(1), Scalar, Op.getOperand(3));
4768     }
4769 
4770     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4771 
4772     // This is an i64 value that lives in two scalar registers. We have to
4773     // insert this in a convoluted way. First we build vXi64 splat containing
4774     // the two values that we assemble using some bit math. Next we'll use
4775     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4776     // to merge element 0 from our splat into the source vector.
4777     // FIXME: This is probably not the best way to do this, but it is
4778     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4779     // point.
4780     //   sw lo, (a0)
4781     //   sw hi, 4(a0)
4782     //   vlse vX, (a0)
4783     //
4784     //   vid.v      vVid
4785     //   vmseq.vx   mMask, vVid, 0
4786     //   vmerge.vvm vDest, vSrc, vVal, mMask
4787     MVT VT = Op.getSimpleValueType();
4788     SDValue Vec = Op.getOperand(1);
4789     SDValue VL = getVLOperand(Op);
4790 
4791     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4792     if (Op.getOperand(1).isUndef())
4793       return SplattedVal;
4794     SDValue SplattedIdx =
4795         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4796                     DAG.getConstant(0, DL, MVT::i32), VL);
4797 
4798     MVT MaskVT = getMaskTypeFor(VT);
4799     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4800     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4801     SDValue SelectCond =
4802         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4803                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4804     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4805                        Vec, VL);
4806   }
4807   }
4808 
4809   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4810 }
4811 
4812 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4813                                                     SelectionDAG &DAG) const {
4814   unsigned IntNo = Op.getConstantOperandVal(1);
4815   switch (IntNo) {
4816   default:
4817     break;
4818   case Intrinsic::riscv_masked_strided_load: {
4819     SDLoc DL(Op);
4820     MVT XLenVT = Subtarget.getXLenVT();
4821 
4822     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4823     // the selection of the masked intrinsics doesn't do this for us.
4824     SDValue Mask = Op.getOperand(5);
4825     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4826 
4827     MVT VT = Op->getSimpleValueType(0);
4828     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4829 
4830     SDValue PassThru = Op.getOperand(2);
4831     if (!IsUnmasked) {
4832       MVT MaskVT = getMaskTypeFor(ContainerVT);
4833       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4834       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4835     }
4836 
4837     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4838 
4839     SDValue IntID = DAG.getTargetConstant(
4840         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4841         XLenVT);
4842 
4843     auto *Load = cast<MemIntrinsicSDNode>(Op);
4844     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4845     if (IsUnmasked)
4846       Ops.push_back(DAG.getUNDEF(ContainerVT));
4847     else
4848       Ops.push_back(PassThru);
4849     Ops.push_back(Op.getOperand(3)); // Ptr
4850     Ops.push_back(Op.getOperand(4)); // Stride
4851     if (!IsUnmasked)
4852       Ops.push_back(Mask);
4853     Ops.push_back(VL);
4854     if (!IsUnmasked) {
4855       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4856       Ops.push_back(Policy);
4857     }
4858 
4859     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4860     SDValue Result =
4861         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4862                                 Load->getMemoryVT(), Load->getMemOperand());
4863     SDValue Chain = Result.getValue(1);
4864     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4865     return DAG.getMergeValues({Result, Chain}, DL);
4866   }
4867   case Intrinsic::riscv_seg2_load:
4868   case Intrinsic::riscv_seg3_load:
4869   case Intrinsic::riscv_seg4_load:
4870   case Intrinsic::riscv_seg5_load:
4871   case Intrinsic::riscv_seg6_load:
4872   case Intrinsic::riscv_seg7_load:
4873   case Intrinsic::riscv_seg8_load: {
4874     SDLoc DL(Op);
4875     static const Intrinsic::ID VlsegInts[7] = {
4876         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4877         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4878         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4879         Intrinsic::riscv_vlseg8};
4880     unsigned NF = Op->getNumValues() - 1;
4881     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4882     MVT XLenVT = Subtarget.getXLenVT();
4883     MVT VT = Op->getSimpleValueType(0);
4884     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4885 
4886     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4887     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4888     auto *Load = cast<MemIntrinsicSDNode>(Op);
4889     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4890     ContainerVTs.push_back(MVT::Other);
4891     SDVTList VTs = DAG.getVTList(ContainerVTs);
4892     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
4893     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
4894     Ops.push_back(Op.getOperand(2));
4895     Ops.push_back(VL);
4896     SDValue Result =
4897         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4898                                 Load->getMemoryVT(), Load->getMemOperand());
4899     SmallVector<SDValue, 9> Results;
4900     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4901       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4902                                                   DAG, Subtarget));
4903     Results.push_back(Result.getValue(NF));
4904     return DAG.getMergeValues(Results, DL);
4905   }
4906   }
4907 
4908   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4909 }
4910 
4911 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4912                                                  SelectionDAG &DAG) const {
4913   unsigned IntNo = Op.getConstantOperandVal(1);
4914   switch (IntNo) {
4915   default:
4916     break;
4917   case Intrinsic::riscv_masked_strided_store: {
4918     SDLoc DL(Op);
4919     MVT XLenVT = Subtarget.getXLenVT();
4920 
4921     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4922     // the selection of the masked intrinsics doesn't do this for us.
4923     SDValue Mask = Op.getOperand(5);
4924     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4925 
4926     SDValue Val = Op.getOperand(2);
4927     MVT VT = Val.getSimpleValueType();
4928     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4929 
4930     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4931     if (!IsUnmasked) {
4932       MVT MaskVT = getMaskTypeFor(ContainerVT);
4933       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4934     }
4935 
4936     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4937 
4938     SDValue IntID = DAG.getTargetConstant(
4939         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4940         XLenVT);
4941 
4942     auto *Store = cast<MemIntrinsicSDNode>(Op);
4943     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4944     Ops.push_back(Val);
4945     Ops.push_back(Op.getOperand(3)); // Ptr
4946     Ops.push_back(Op.getOperand(4)); // Stride
4947     if (!IsUnmasked)
4948       Ops.push_back(Mask);
4949     Ops.push_back(VL);
4950 
4951     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4952                                    Ops, Store->getMemoryVT(),
4953                                    Store->getMemOperand());
4954   }
4955   }
4956 
4957   return SDValue();
4958 }
4959 
4960 static MVT getLMUL1VT(MVT VT) {
4961   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4962          "Unexpected vector MVT");
4963   return MVT::getScalableVectorVT(
4964       VT.getVectorElementType(),
4965       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4966 }
4967 
4968 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4969   switch (ISDOpcode) {
4970   default:
4971     llvm_unreachable("Unhandled reduction");
4972   case ISD::VECREDUCE_ADD:
4973     return RISCVISD::VECREDUCE_ADD_VL;
4974   case ISD::VECREDUCE_UMAX:
4975     return RISCVISD::VECREDUCE_UMAX_VL;
4976   case ISD::VECREDUCE_SMAX:
4977     return RISCVISD::VECREDUCE_SMAX_VL;
4978   case ISD::VECREDUCE_UMIN:
4979     return RISCVISD::VECREDUCE_UMIN_VL;
4980   case ISD::VECREDUCE_SMIN:
4981     return RISCVISD::VECREDUCE_SMIN_VL;
4982   case ISD::VECREDUCE_AND:
4983     return RISCVISD::VECREDUCE_AND_VL;
4984   case ISD::VECREDUCE_OR:
4985     return RISCVISD::VECREDUCE_OR_VL;
4986   case ISD::VECREDUCE_XOR:
4987     return RISCVISD::VECREDUCE_XOR_VL;
4988   }
4989 }
4990 
4991 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4992                                                          SelectionDAG &DAG,
4993                                                          bool IsVP) const {
4994   SDLoc DL(Op);
4995   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4996   MVT VecVT = Vec.getSimpleValueType();
4997   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4998           Op.getOpcode() == ISD::VECREDUCE_OR ||
4999           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5000           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5001           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5002           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5003          "Unexpected reduction lowering");
5004 
5005   MVT XLenVT = Subtarget.getXLenVT();
5006   assert(Op.getValueType() == XLenVT &&
5007          "Expected reduction output to be legalized to XLenVT");
5008 
5009   MVT ContainerVT = VecVT;
5010   if (VecVT.isFixedLengthVector()) {
5011     ContainerVT = getContainerForFixedLengthVector(VecVT);
5012     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5013   }
5014 
5015   SDValue Mask, VL;
5016   if (IsVP) {
5017     Mask = Op.getOperand(2);
5018     VL = Op.getOperand(3);
5019   } else {
5020     std::tie(Mask, VL) =
5021         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5022   }
5023 
5024   unsigned BaseOpc;
5025   ISD::CondCode CC;
5026   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5027 
5028   switch (Op.getOpcode()) {
5029   default:
5030     llvm_unreachable("Unhandled reduction");
5031   case ISD::VECREDUCE_AND:
5032   case ISD::VP_REDUCE_AND: {
5033     // vcpop ~x == 0
5034     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5035     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5036     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5037     CC = ISD::SETEQ;
5038     BaseOpc = ISD::AND;
5039     break;
5040   }
5041   case ISD::VECREDUCE_OR:
5042   case ISD::VP_REDUCE_OR:
5043     // vcpop x != 0
5044     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5045     CC = ISD::SETNE;
5046     BaseOpc = ISD::OR;
5047     break;
5048   case ISD::VECREDUCE_XOR:
5049   case ISD::VP_REDUCE_XOR: {
5050     // ((vcpop x) & 1) != 0
5051     SDValue One = DAG.getConstant(1, DL, XLenVT);
5052     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5053     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5054     CC = ISD::SETNE;
5055     BaseOpc = ISD::XOR;
5056     break;
5057   }
5058   }
5059 
5060   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5061 
5062   if (!IsVP)
5063     return SetCC;
5064 
5065   // Now include the start value in the operation.
5066   // Note that we must return the start value when no elements are operated
5067   // upon. The vcpop instructions we've emitted in each case above will return
5068   // 0 for an inactive vector, and so we've already received the neutral value:
5069   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5070   // can simply include the start value.
5071   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5072 }
5073 
5074 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5075                                             SelectionDAG &DAG) const {
5076   SDLoc DL(Op);
5077   SDValue Vec = Op.getOperand(0);
5078   EVT VecEVT = Vec.getValueType();
5079 
5080   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5081 
5082   // Due to ordering in legalize types we may have a vector type that needs to
5083   // be split. Do that manually so we can get down to a legal type.
5084   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5085          TargetLowering::TypeSplitVector) {
5086     SDValue Lo, Hi;
5087     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5088     VecEVT = Lo.getValueType();
5089     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5090   }
5091 
5092   // TODO: The type may need to be widened rather than split. Or widened before
5093   // it can be split.
5094   if (!isTypeLegal(VecEVT))
5095     return SDValue();
5096 
5097   MVT VecVT = VecEVT.getSimpleVT();
5098   MVT VecEltVT = VecVT.getVectorElementType();
5099   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5100 
5101   MVT ContainerVT = VecVT;
5102   if (VecVT.isFixedLengthVector()) {
5103     ContainerVT = getContainerForFixedLengthVector(VecVT);
5104     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5105   }
5106 
5107   MVT M1VT = getLMUL1VT(ContainerVT);
5108   MVT XLenVT = Subtarget.getXLenVT();
5109 
5110   SDValue Mask, VL;
5111   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5112 
5113   SDValue NeutralElem =
5114       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5115   SDValue IdentitySplat =
5116       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5117                        M1VT, DL, DAG, Subtarget);
5118   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5119                                   IdentitySplat, Mask, VL);
5120   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5121                              DAG.getConstant(0, DL, XLenVT));
5122   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5123 }
5124 
5125 // Given a reduction op, this function returns the matching reduction opcode,
5126 // the vector SDValue and the scalar SDValue required to lower this to a
5127 // RISCVISD node.
5128 static std::tuple<unsigned, SDValue, SDValue>
5129 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5130   SDLoc DL(Op);
5131   auto Flags = Op->getFlags();
5132   unsigned Opcode = Op.getOpcode();
5133   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5134   switch (Opcode) {
5135   default:
5136     llvm_unreachable("Unhandled reduction");
5137   case ISD::VECREDUCE_FADD: {
5138     // Use positive zero if we can. It is cheaper to materialize.
5139     SDValue Zero =
5140         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5141     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5142   }
5143   case ISD::VECREDUCE_SEQ_FADD:
5144     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5145                            Op.getOperand(0));
5146   case ISD::VECREDUCE_FMIN:
5147     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5148                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5149   case ISD::VECREDUCE_FMAX:
5150     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5151                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5152   }
5153 }
5154 
5155 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5156                                               SelectionDAG &DAG) const {
5157   SDLoc DL(Op);
5158   MVT VecEltVT = Op.getSimpleValueType();
5159 
5160   unsigned RVVOpcode;
5161   SDValue VectorVal, ScalarVal;
5162   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5163       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5164   MVT VecVT = VectorVal.getSimpleValueType();
5165 
5166   MVT ContainerVT = VecVT;
5167   if (VecVT.isFixedLengthVector()) {
5168     ContainerVT = getContainerForFixedLengthVector(VecVT);
5169     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5170   }
5171 
5172   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5173   MVT XLenVT = Subtarget.getXLenVT();
5174 
5175   SDValue Mask, VL;
5176   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5177 
5178   SDValue ScalarSplat =
5179       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5180                        M1VT, DL, DAG, Subtarget);
5181   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5182                                   VectorVal, ScalarSplat, Mask, VL);
5183   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5184                      DAG.getConstant(0, DL, XLenVT));
5185 }
5186 
5187 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5188   switch (ISDOpcode) {
5189   default:
5190     llvm_unreachable("Unhandled reduction");
5191   case ISD::VP_REDUCE_ADD:
5192     return RISCVISD::VECREDUCE_ADD_VL;
5193   case ISD::VP_REDUCE_UMAX:
5194     return RISCVISD::VECREDUCE_UMAX_VL;
5195   case ISD::VP_REDUCE_SMAX:
5196     return RISCVISD::VECREDUCE_SMAX_VL;
5197   case ISD::VP_REDUCE_UMIN:
5198     return RISCVISD::VECREDUCE_UMIN_VL;
5199   case ISD::VP_REDUCE_SMIN:
5200     return RISCVISD::VECREDUCE_SMIN_VL;
5201   case ISD::VP_REDUCE_AND:
5202     return RISCVISD::VECREDUCE_AND_VL;
5203   case ISD::VP_REDUCE_OR:
5204     return RISCVISD::VECREDUCE_OR_VL;
5205   case ISD::VP_REDUCE_XOR:
5206     return RISCVISD::VECREDUCE_XOR_VL;
5207   case ISD::VP_REDUCE_FADD:
5208     return RISCVISD::VECREDUCE_FADD_VL;
5209   case ISD::VP_REDUCE_SEQ_FADD:
5210     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5211   case ISD::VP_REDUCE_FMAX:
5212     return RISCVISD::VECREDUCE_FMAX_VL;
5213   case ISD::VP_REDUCE_FMIN:
5214     return RISCVISD::VECREDUCE_FMIN_VL;
5215   }
5216 }
5217 
5218 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5219                                            SelectionDAG &DAG) const {
5220   SDLoc DL(Op);
5221   SDValue Vec = Op.getOperand(1);
5222   EVT VecEVT = Vec.getValueType();
5223 
5224   // TODO: The type may need to be widened rather than split. Or widened before
5225   // it can be split.
5226   if (!isTypeLegal(VecEVT))
5227     return SDValue();
5228 
5229   MVT VecVT = VecEVT.getSimpleVT();
5230   MVT VecEltVT = VecVT.getVectorElementType();
5231   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5232 
5233   MVT ContainerVT = VecVT;
5234   if (VecVT.isFixedLengthVector()) {
5235     ContainerVT = getContainerForFixedLengthVector(VecVT);
5236     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5237   }
5238 
5239   SDValue VL = Op.getOperand(3);
5240   SDValue Mask = Op.getOperand(2);
5241 
5242   MVT M1VT = getLMUL1VT(ContainerVT);
5243   MVT XLenVT = Subtarget.getXLenVT();
5244   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5245 
5246   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5247                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5248                                         DL, DAG, Subtarget);
5249   SDValue Reduction =
5250       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5251   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5252                              DAG.getConstant(0, DL, XLenVT));
5253   if (!VecVT.isInteger())
5254     return Elt0;
5255   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5256 }
5257 
5258 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5259                                                    SelectionDAG &DAG) const {
5260   SDValue Vec = Op.getOperand(0);
5261   SDValue SubVec = Op.getOperand(1);
5262   MVT VecVT = Vec.getSimpleValueType();
5263   MVT SubVecVT = SubVec.getSimpleValueType();
5264 
5265   SDLoc DL(Op);
5266   MVT XLenVT = Subtarget.getXLenVT();
5267   unsigned OrigIdx = Op.getConstantOperandVal(2);
5268   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5269 
5270   // We don't have the ability to slide mask vectors up indexed by their i1
5271   // elements; the smallest we can do is i8. Often we are able to bitcast to
5272   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5273   // into a scalable one, we might not necessarily have enough scalable
5274   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5275   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5276       (OrigIdx != 0 || !Vec.isUndef())) {
5277     if (VecVT.getVectorMinNumElements() >= 8 &&
5278         SubVecVT.getVectorMinNumElements() >= 8) {
5279       assert(OrigIdx % 8 == 0 && "Invalid index");
5280       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5281              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5282              "Unexpected mask vector lowering");
5283       OrigIdx /= 8;
5284       SubVecVT =
5285           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5286                            SubVecVT.isScalableVector());
5287       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5288                                VecVT.isScalableVector());
5289       Vec = DAG.getBitcast(VecVT, Vec);
5290       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5291     } else {
5292       // We can't slide this mask vector up indexed by its i1 elements.
5293       // This poses a problem when we wish to insert a scalable vector which
5294       // can't be re-expressed as a larger type. Just choose the slow path and
5295       // extend to a larger type, then truncate back down.
5296       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5297       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5298       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5299       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5300       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5301                         Op.getOperand(2));
5302       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5303       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5304     }
5305   }
5306 
5307   // If the subvector vector is a fixed-length type, we cannot use subregister
5308   // manipulation to simplify the codegen; we don't know which register of a
5309   // LMUL group contains the specific subvector as we only know the minimum
5310   // register size. Therefore we must slide the vector group up the full
5311   // amount.
5312   if (SubVecVT.isFixedLengthVector()) {
5313     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5314       return Op;
5315     MVT ContainerVT = VecVT;
5316     if (VecVT.isFixedLengthVector()) {
5317       ContainerVT = getContainerForFixedLengthVector(VecVT);
5318       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5319     }
5320     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5321                          DAG.getUNDEF(ContainerVT), SubVec,
5322                          DAG.getConstant(0, DL, XLenVT));
5323     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5324       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5325       return DAG.getBitcast(Op.getValueType(), SubVec);
5326     }
5327     SDValue Mask =
5328         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5329     // Set the vector length to only the number of elements we care about. Note
5330     // that for slideup this includes the offset.
5331     SDValue VL =
5332         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5333     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5334     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5335                                   SubVec, SlideupAmt, Mask, VL);
5336     if (VecVT.isFixedLengthVector())
5337       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5338     return DAG.getBitcast(Op.getValueType(), Slideup);
5339   }
5340 
5341   unsigned SubRegIdx, RemIdx;
5342   std::tie(SubRegIdx, RemIdx) =
5343       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5344           VecVT, SubVecVT, OrigIdx, TRI);
5345 
5346   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5347   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5348                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5349                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5350 
5351   // 1. If the Idx has been completely eliminated and this subvector's size is
5352   // a vector register or a multiple thereof, or the surrounding elements are
5353   // undef, then this is a subvector insert which naturally aligns to a vector
5354   // register. These can easily be handled using subregister manipulation.
5355   // 2. If the subvector is smaller than a vector register, then the insertion
5356   // must preserve the undisturbed elements of the register. We do this by
5357   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5358   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5359   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5360   // LMUL=1 type back into the larger vector (resolving to another subregister
5361   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5362   // to avoid allocating a large register group to hold our subvector.
5363   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5364     return Op;
5365 
5366   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5367   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5368   // (in our case undisturbed). This means we can set up a subvector insertion
5369   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5370   // size of the subvector.
5371   MVT InterSubVT = VecVT;
5372   SDValue AlignedExtract = Vec;
5373   unsigned AlignedIdx = OrigIdx - RemIdx;
5374   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5375     InterSubVT = getLMUL1VT(VecVT);
5376     // Extract a subvector equal to the nearest full vector register type. This
5377     // should resolve to a EXTRACT_SUBREG instruction.
5378     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5379                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5380   }
5381 
5382   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5383   // For scalable vectors this must be further multiplied by vscale.
5384   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5385 
5386   SDValue Mask, VL;
5387   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5388 
5389   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5390   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5391   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5392   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5393 
5394   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5395                        DAG.getUNDEF(InterSubVT), SubVec,
5396                        DAG.getConstant(0, DL, XLenVT));
5397 
5398   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5399                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5400 
5401   // If required, insert this subvector back into the correct vector register.
5402   // This should resolve to an INSERT_SUBREG instruction.
5403   if (VecVT.bitsGT(InterSubVT))
5404     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5405                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5406 
5407   // We might have bitcast from a mask type: cast back to the original type if
5408   // required.
5409   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5410 }
5411 
5412 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5413                                                     SelectionDAG &DAG) const {
5414   SDValue Vec = Op.getOperand(0);
5415   MVT SubVecVT = Op.getSimpleValueType();
5416   MVT VecVT = Vec.getSimpleValueType();
5417 
5418   SDLoc DL(Op);
5419   MVT XLenVT = Subtarget.getXLenVT();
5420   unsigned OrigIdx = Op.getConstantOperandVal(1);
5421   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5422 
5423   // We don't have the ability to slide mask vectors down indexed by their i1
5424   // elements; the smallest we can do is i8. Often we are able to bitcast to
5425   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5426   // from a scalable one, we might not necessarily have enough scalable
5427   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5428   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5429     if (VecVT.getVectorMinNumElements() >= 8 &&
5430         SubVecVT.getVectorMinNumElements() >= 8) {
5431       assert(OrigIdx % 8 == 0 && "Invalid index");
5432       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5433              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5434              "Unexpected mask vector lowering");
5435       OrigIdx /= 8;
5436       SubVecVT =
5437           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5438                            SubVecVT.isScalableVector());
5439       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5440                                VecVT.isScalableVector());
5441       Vec = DAG.getBitcast(VecVT, Vec);
5442     } else {
5443       // We can't slide this mask vector down, indexed by its i1 elements.
5444       // This poses a problem when we wish to extract a scalable vector which
5445       // can't be re-expressed as a larger type. Just choose the slow path and
5446       // extend to a larger type, then truncate back down.
5447       // TODO: We could probably improve this when extracting certain fixed
5448       // from fixed, where we can extract as i8 and shift the correct element
5449       // right to reach the desired subvector?
5450       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5451       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5452       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5453       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5454                         Op.getOperand(1));
5455       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5456       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5457     }
5458   }
5459 
5460   // If the subvector vector is a fixed-length type, we cannot use subregister
5461   // manipulation to simplify the codegen; we don't know which register of a
5462   // LMUL group contains the specific subvector as we only know the minimum
5463   // register size. Therefore we must slide the vector group down the full
5464   // amount.
5465   if (SubVecVT.isFixedLengthVector()) {
5466     // With an index of 0 this is a cast-like subvector, which can be performed
5467     // with subregister operations.
5468     if (OrigIdx == 0)
5469       return Op;
5470     MVT ContainerVT = VecVT;
5471     if (VecVT.isFixedLengthVector()) {
5472       ContainerVT = getContainerForFixedLengthVector(VecVT);
5473       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5474     }
5475     SDValue Mask =
5476         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5477     // Set the vector length to only the number of elements we care about. This
5478     // avoids sliding down elements we're going to discard straight away.
5479     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5480     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5481     SDValue Slidedown =
5482         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5483                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5484     // Now we can use a cast-like subvector extract to get the result.
5485     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5486                             DAG.getConstant(0, DL, XLenVT));
5487     return DAG.getBitcast(Op.getValueType(), Slidedown);
5488   }
5489 
5490   unsigned SubRegIdx, RemIdx;
5491   std::tie(SubRegIdx, RemIdx) =
5492       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5493           VecVT, SubVecVT, OrigIdx, TRI);
5494 
5495   // If the Idx has been completely eliminated then this is a subvector extract
5496   // which naturally aligns to a vector register. These can easily be handled
5497   // using subregister manipulation.
5498   if (RemIdx == 0)
5499     return Op;
5500 
5501   // Else we must shift our vector register directly to extract the subvector.
5502   // Do this using VSLIDEDOWN.
5503 
5504   // If the vector type is an LMUL-group type, extract a subvector equal to the
5505   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5506   // instruction.
5507   MVT InterSubVT = VecVT;
5508   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5509     InterSubVT = getLMUL1VT(VecVT);
5510     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5511                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5512   }
5513 
5514   // Slide this vector register down by the desired number of elements in order
5515   // to place the desired subvector starting at element 0.
5516   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5517   // For scalable vectors this must be further multiplied by vscale.
5518   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5519 
5520   SDValue Mask, VL;
5521   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5522   SDValue Slidedown =
5523       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5524                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5525 
5526   // Now the vector is in the right position, extract our final subvector. This
5527   // should resolve to a COPY.
5528   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5529                           DAG.getConstant(0, DL, XLenVT));
5530 
5531   // We might have bitcast from a mask type: cast back to the original type if
5532   // required.
5533   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5534 }
5535 
5536 // Lower step_vector to the vid instruction. Any non-identity step value must
5537 // be accounted for my manual expansion.
5538 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5539                                               SelectionDAG &DAG) const {
5540   SDLoc DL(Op);
5541   MVT VT = Op.getSimpleValueType();
5542   MVT XLenVT = Subtarget.getXLenVT();
5543   SDValue Mask, VL;
5544   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5545   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5546   uint64_t StepValImm = Op.getConstantOperandVal(0);
5547   if (StepValImm != 1) {
5548     if (isPowerOf2_64(StepValImm)) {
5549       SDValue StepVal =
5550           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5551                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5552       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5553     } else {
5554       SDValue StepVal = lowerScalarSplat(
5555           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5556           VL, VT, DL, DAG, Subtarget);
5557       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5558     }
5559   }
5560   return StepVec;
5561 }
5562 
5563 // Implement vector_reverse using vrgather.vv with indices determined by
5564 // subtracting the id of each element from (VLMAX-1). This will convert
5565 // the indices like so:
5566 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5567 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5568 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5569                                                  SelectionDAG &DAG) const {
5570   SDLoc DL(Op);
5571   MVT VecVT = Op.getSimpleValueType();
5572   unsigned EltSize = VecVT.getScalarSizeInBits();
5573   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5574 
5575   unsigned MaxVLMAX = 0;
5576   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5577   if (VectorBitsMax != 0)
5578     MaxVLMAX =
5579         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5580 
5581   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5582   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5583 
5584   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5585   // to use vrgatherei16.vv.
5586   // TODO: It's also possible to use vrgatherei16.vv for other types to
5587   // decrease register width for the index calculation.
5588   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5589     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5590     // Reverse each half, then reassemble them in reverse order.
5591     // NOTE: It's also possible that after splitting that VLMAX no longer
5592     // requires vrgatherei16.vv.
5593     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5594       SDValue Lo, Hi;
5595       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5596       EVT LoVT, HiVT;
5597       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5598       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5599       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5600       // Reassemble the low and high pieces reversed.
5601       // FIXME: This is a CONCAT_VECTORS.
5602       SDValue Res =
5603           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5604                       DAG.getIntPtrConstant(0, DL));
5605       return DAG.getNode(
5606           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5607           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5608     }
5609 
5610     // Just promote the int type to i16 which will double the LMUL.
5611     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5612     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5613   }
5614 
5615   MVT XLenVT = Subtarget.getXLenVT();
5616   SDValue Mask, VL;
5617   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5618 
5619   // Calculate VLMAX-1 for the desired SEW.
5620   unsigned MinElts = VecVT.getVectorMinNumElements();
5621   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5622                               DAG.getConstant(MinElts, DL, XLenVT));
5623   SDValue VLMinus1 =
5624       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5625 
5626   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5627   bool IsRV32E64 =
5628       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5629   SDValue SplatVL;
5630   if (!IsRV32E64)
5631     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5632   else
5633     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5634                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5635 
5636   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5637   SDValue Indices =
5638       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5639 
5640   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5641 }
5642 
5643 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5644                                                 SelectionDAG &DAG) const {
5645   SDLoc DL(Op);
5646   SDValue V1 = Op.getOperand(0);
5647   SDValue V2 = Op.getOperand(1);
5648   MVT XLenVT = Subtarget.getXLenVT();
5649   MVT VecVT = Op.getSimpleValueType();
5650 
5651   unsigned MinElts = VecVT.getVectorMinNumElements();
5652   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5653                               DAG.getConstant(MinElts, DL, XLenVT));
5654 
5655   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5656   SDValue DownOffset, UpOffset;
5657   if (ImmValue >= 0) {
5658     // The operand is a TargetConstant, we need to rebuild it as a regular
5659     // constant.
5660     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5661     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5662   } else {
5663     // The operand is a TargetConstant, we need to rebuild it as a regular
5664     // constant rather than negating the original operand.
5665     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5666     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5667   }
5668 
5669   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5670 
5671   SDValue SlideDown =
5672       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5673                   DownOffset, TrueMask, UpOffset);
5674   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5675                      TrueMask,
5676                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5677 }
5678 
5679 SDValue
5680 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5681                                                      SelectionDAG &DAG) const {
5682   SDLoc DL(Op);
5683   auto *Load = cast<LoadSDNode>(Op);
5684 
5685   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5686                                         Load->getMemoryVT(),
5687                                         *Load->getMemOperand()) &&
5688          "Expecting a correctly-aligned load");
5689 
5690   MVT VT = Op.getSimpleValueType();
5691   MVT XLenVT = Subtarget.getXLenVT();
5692   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5693 
5694   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5695 
5696   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5697   SDValue IntID = DAG.getTargetConstant(
5698       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5699   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5700   if (!IsMaskOp)
5701     Ops.push_back(DAG.getUNDEF(ContainerVT));
5702   Ops.push_back(Load->getBasePtr());
5703   Ops.push_back(VL);
5704   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5705   SDValue NewLoad =
5706       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5707                               Load->getMemoryVT(), Load->getMemOperand());
5708 
5709   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5710   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5711 }
5712 
5713 SDValue
5714 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5715                                                       SelectionDAG &DAG) const {
5716   SDLoc DL(Op);
5717   auto *Store = cast<StoreSDNode>(Op);
5718 
5719   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5720                                         Store->getMemoryVT(),
5721                                         *Store->getMemOperand()) &&
5722          "Expecting a correctly-aligned store");
5723 
5724   SDValue StoreVal = Store->getValue();
5725   MVT VT = StoreVal.getSimpleValueType();
5726   MVT XLenVT = Subtarget.getXLenVT();
5727 
5728   // If the size less than a byte, we need to pad with zeros to make a byte.
5729   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5730     VT = MVT::v8i1;
5731     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5732                            DAG.getConstant(0, DL, VT), StoreVal,
5733                            DAG.getIntPtrConstant(0, DL));
5734   }
5735 
5736   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5737 
5738   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5739 
5740   SDValue NewValue =
5741       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5742 
5743   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5744   SDValue IntID = DAG.getTargetConstant(
5745       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5746   return DAG.getMemIntrinsicNode(
5747       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5748       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5749       Store->getMemoryVT(), Store->getMemOperand());
5750 }
5751 
5752 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5753                                              SelectionDAG &DAG) const {
5754   SDLoc DL(Op);
5755   MVT VT = Op.getSimpleValueType();
5756 
5757   const auto *MemSD = cast<MemSDNode>(Op);
5758   EVT MemVT = MemSD->getMemoryVT();
5759   MachineMemOperand *MMO = MemSD->getMemOperand();
5760   SDValue Chain = MemSD->getChain();
5761   SDValue BasePtr = MemSD->getBasePtr();
5762 
5763   SDValue Mask, PassThru, VL;
5764   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5765     Mask = VPLoad->getMask();
5766     PassThru = DAG.getUNDEF(VT);
5767     VL = VPLoad->getVectorLength();
5768   } else {
5769     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5770     Mask = MLoad->getMask();
5771     PassThru = MLoad->getPassThru();
5772   }
5773 
5774   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5775 
5776   MVT XLenVT = Subtarget.getXLenVT();
5777 
5778   MVT ContainerVT = VT;
5779   if (VT.isFixedLengthVector()) {
5780     ContainerVT = getContainerForFixedLengthVector(VT);
5781     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5782     if (!IsUnmasked) {
5783       MVT MaskVT = getMaskTypeFor(ContainerVT);
5784       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5785     }
5786   }
5787 
5788   if (!VL)
5789     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5790 
5791   unsigned IntID =
5792       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5793   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5794   if (IsUnmasked)
5795     Ops.push_back(DAG.getUNDEF(ContainerVT));
5796   else
5797     Ops.push_back(PassThru);
5798   Ops.push_back(BasePtr);
5799   if (!IsUnmasked)
5800     Ops.push_back(Mask);
5801   Ops.push_back(VL);
5802   if (!IsUnmasked)
5803     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5804 
5805   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5806 
5807   SDValue Result =
5808       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5809   Chain = Result.getValue(1);
5810 
5811   if (VT.isFixedLengthVector())
5812     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5813 
5814   return DAG.getMergeValues({Result, Chain}, DL);
5815 }
5816 
5817 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5818                                               SelectionDAG &DAG) const {
5819   SDLoc DL(Op);
5820 
5821   const auto *MemSD = cast<MemSDNode>(Op);
5822   EVT MemVT = MemSD->getMemoryVT();
5823   MachineMemOperand *MMO = MemSD->getMemOperand();
5824   SDValue Chain = MemSD->getChain();
5825   SDValue BasePtr = MemSD->getBasePtr();
5826   SDValue Val, Mask, VL;
5827 
5828   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5829     Val = VPStore->getValue();
5830     Mask = VPStore->getMask();
5831     VL = VPStore->getVectorLength();
5832   } else {
5833     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5834     Val = MStore->getValue();
5835     Mask = MStore->getMask();
5836   }
5837 
5838   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5839 
5840   MVT VT = Val.getSimpleValueType();
5841   MVT XLenVT = Subtarget.getXLenVT();
5842 
5843   MVT ContainerVT = VT;
5844   if (VT.isFixedLengthVector()) {
5845     ContainerVT = getContainerForFixedLengthVector(VT);
5846 
5847     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5848     if (!IsUnmasked) {
5849       MVT MaskVT = getMaskTypeFor(ContainerVT);
5850       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5851     }
5852   }
5853 
5854   if (!VL)
5855     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5856 
5857   unsigned IntID =
5858       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5859   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5860   Ops.push_back(Val);
5861   Ops.push_back(BasePtr);
5862   if (!IsUnmasked)
5863     Ops.push_back(Mask);
5864   Ops.push_back(VL);
5865 
5866   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5867                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5868 }
5869 
5870 SDValue
5871 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5872                                                       SelectionDAG &DAG) const {
5873   MVT InVT = Op.getOperand(0).getSimpleValueType();
5874   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5875 
5876   MVT VT = Op.getSimpleValueType();
5877 
5878   SDValue Op1 =
5879       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5880   SDValue Op2 =
5881       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5882 
5883   SDLoc DL(Op);
5884   SDValue VL =
5885       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5886 
5887   MVT MaskVT = getMaskTypeFor(ContainerVT);
5888   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
5889 
5890   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5891                             Op.getOperand(2), Mask, VL);
5892 
5893   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5894 }
5895 
5896 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5897     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5898   MVT VT = Op.getSimpleValueType();
5899 
5900   if (VT.getVectorElementType() == MVT::i1)
5901     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5902 
5903   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5904 }
5905 
5906 SDValue
5907 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5908                                                       SelectionDAG &DAG) const {
5909   unsigned Opc;
5910   switch (Op.getOpcode()) {
5911   default: llvm_unreachable("Unexpected opcode!");
5912   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5913   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5914   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5915   }
5916 
5917   return lowerToScalableOp(Op, DAG, Opc);
5918 }
5919 
5920 // Lower vector ABS to smax(X, sub(0, X)).
5921 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5922   SDLoc DL(Op);
5923   MVT VT = Op.getSimpleValueType();
5924   SDValue X = Op.getOperand(0);
5925 
5926   assert(VT.isFixedLengthVector() && "Unexpected type");
5927 
5928   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5929   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5930 
5931   SDValue Mask, VL;
5932   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5933 
5934   SDValue SplatZero = DAG.getNode(
5935       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5936       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5937   SDValue NegX =
5938       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5939   SDValue Max =
5940       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5941 
5942   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5943 }
5944 
5945 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5946     SDValue Op, SelectionDAG &DAG) const {
5947   SDLoc DL(Op);
5948   MVT VT = Op.getSimpleValueType();
5949   SDValue Mag = Op.getOperand(0);
5950   SDValue Sign = Op.getOperand(1);
5951   assert(Mag.getValueType() == Sign.getValueType() &&
5952          "Can only handle COPYSIGN with matching types.");
5953 
5954   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5955   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5956   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5957 
5958   SDValue Mask, VL;
5959   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5960 
5961   SDValue CopySign =
5962       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5963 
5964   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5965 }
5966 
5967 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5968     SDValue Op, SelectionDAG &DAG) const {
5969   MVT VT = Op.getSimpleValueType();
5970   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5971 
5972   MVT I1ContainerVT =
5973       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5974 
5975   SDValue CC =
5976       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5977   SDValue Op1 =
5978       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5979   SDValue Op2 =
5980       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5981 
5982   SDLoc DL(Op);
5983   SDValue Mask, VL;
5984   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5985 
5986   SDValue Select =
5987       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5988 
5989   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5990 }
5991 
5992 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5993                                                unsigned NewOpc,
5994                                                bool HasMask) const {
5995   MVT VT = Op.getSimpleValueType();
5996   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5997 
5998   // Create list of operands by converting existing ones to scalable types.
5999   SmallVector<SDValue, 6> Ops;
6000   for (const SDValue &V : Op->op_values()) {
6001     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6002 
6003     // Pass through non-vector operands.
6004     if (!V.getValueType().isVector()) {
6005       Ops.push_back(V);
6006       continue;
6007     }
6008 
6009     // "cast" fixed length vector to a scalable vector.
6010     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6011            "Only fixed length vectors are supported!");
6012     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6013   }
6014 
6015   SDLoc DL(Op);
6016   SDValue Mask, VL;
6017   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6018   if (HasMask)
6019     Ops.push_back(Mask);
6020   Ops.push_back(VL);
6021 
6022   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6023   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6024 }
6025 
6026 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6027 // * Operands of each node are assumed to be in the same order.
6028 // * The EVL operand is promoted from i32 to i64 on RV64.
6029 // * Fixed-length vectors are converted to their scalable-vector container
6030 //   types.
6031 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6032                                        unsigned RISCVISDOpc) const {
6033   SDLoc DL(Op);
6034   MVT VT = Op.getSimpleValueType();
6035   SmallVector<SDValue, 4> Ops;
6036 
6037   for (const auto &OpIdx : enumerate(Op->ops())) {
6038     SDValue V = OpIdx.value();
6039     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6040     // Pass through operands which aren't fixed-length vectors.
6041     if (!V.getValueType().isFixedLengthVector()) {
6042       Ops.push_back(V);
6043       continue;
6044     }
6045     // "cast" fixed length vector to a scalable vector.
6046     MVT OpVT = V.getSimpleValueType();
6047     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6048     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6049            "Only fixed length vectors are supported!");
6050     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6051   }
6052 
6053   if (!VT.isFixedLengthVector())
6054     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6055 
6056   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6057 
6058   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6059 
6060   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6061 }
6062 
6063 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6064                                               SelectionDAG &DAG) const {
6065   SDLoc DL(Op);
6066   MVT VT = Op.getSimpleValueType();
6067 
6068   SDValue Src = Op.getOperand(0);
6069   // NOTE: Mask is dropped.
6070   SDValue VL = Op.getOperand(2);
6071 
6072   MVT ContainerVT = VT;
6073   if (VT.isFixedLengthVector()) {
6074     ContainerVT = getContainerForFixedLengthVector(VT);
6075     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6076     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6077   }
6078 
6079   MVT XLenVT = Subtarget.getXLenVT();
6080   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6081   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6082                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6083 
6084   SDValue SplatValue = DAG.getConstant(
6085       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6086   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6087                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6088 
6089   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6090                                Splat, ZeroSplat, VL);
6091   if (!VT.isFixedLengthVector())
6092     return Result;
6093   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6094 }
6095 
6096 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6097                                                 SelectionDAG &DAG) const {
6098   SDLoc DL(Op);
6099   MVT VT = Op.getSimpleValueType();
6100 
6101   SDValue Op1 = Op.getOperand(0);
6102   SDValue Op2 = Op.getOperand(1);
6103   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6104   // NOTE: Mask is dropped.
6105   SDValue VL = Op.getOperand(4);
6106 
6107   MVT ContainerVT = VT;
6108   if (VT.isFixedLengthVector()) {
6109     ContainerVT = getContainerForFixedLengthVector(VT);
6110     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6111     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6112   }
6113 
6114   SDValue Result;
6115   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6116 
6117   switch (Condition) {
6118   default:
6119     break;
6120   // X != Y  --> (X^Y)
6121   case ISD::SETNE:
6122     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6123     break;
6124   // X == Y  --> ~(X^Y)
6125   case ISD::SETEQ: {
6126     SDValue Temp =
6127         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6128     Result =
6129         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6130     break;
6131   }
6132   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6133   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6134   case ISD::SETGT:
6135   case ISD::SETULT: {
6136     SDValue Temp =
6137         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6138     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6139     break;
6140   }
6141   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6142   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6143   case ISD::SETLT:
6144   case ISD::SETUGT: {
6145     SDValue Temp =
6146         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6147     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6148     break;
6149   }
6150   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6151   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6152   case ISD::SETGE:
6153   case ISD::SETULE: {
6154     SDValue Temp =
6155         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6156     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6157     break;
6158   }
6159   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6160   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6161   case ISD::SETLE:
6162   case ISD::SETUGE: {
6163     SDValue Temp =
6164         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6165     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6166     break;
6167   }
6168   }
6169 
6170   if (!VT.isFixedLengthVector())
6171     return Result;
6172   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6173 }
6174 
6175 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6176 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6177                                                 unsigned RISCVISDOpc) const {
6178   SDLoc DL(Op);
6179 
6180   SDValue Src = Op.getOperand(0);
6181   SDValue Mask = Op.getOperand(1);
6182   SDValue VL = Op.getOperand(2);
6183 
6184   MVT DstVT = Op.getSimpleValueType();
6185   MVT SrcVT = Src.getSimpleValueType();
6186   if (DstVT.isFixedLengthVector()) {
6187     DstVT = getContainerForFixedLengthVector(DstVT);
6188     SrcVT = getContainerForFixedLengthVector(SrcVT);
6189     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6190     MVT MaskVT = getMaskTypeFor(DstVT);
6191     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6192   }
6193 
6194   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6195                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6196                                 ? RISCVISD::VSEXT_VL
6197                                 : RISCVISD::VZEXT_VL;
6198 
6199   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6200   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6201 
6202   SDValue Result;
6203   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6204     if (SrcVT.isInteger()) {
6205       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6206 
6207       // Do we need to do any pre-widening before converting?
6208       if (SrcEltSize == 1) {
6209         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6210         MVT XLenVT = Subtarget.getXLenVT();
6211         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6212         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6213                                         DAG.getUNDEF(IntVT), Zero, VL);
6214         SDValue One = DAG.getConstant(
6215             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6216         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6217                                        DAG.getUNDEF(IntVT), One, VL);
6218         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6219                           ZeroSplat, VL);
6220       } else if (DstEltSize > (2 * SrcEltSize)) {
6221         // Widen before converting.
6222         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6223                                      DstVT.getVectorElementCount());
6224         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6225       }
6226 
6227       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6228     } else {
6229       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6230              "Wrong input/output vector types");
6231 
6232       // Convert f16 to f32 then convert f32 to i64.
6233       if (DstEltSize > (2 * SrcEltSize)) {
6234         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6235         MVT InterimFVT =
6236             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6237         Src =
6238             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6239       }
6240 
6241       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6242     }
6243   } else { // Narrowing + Conversion
6244     if (SrcVT.isInteger()) {
6245       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6246       // First do a narrowing convert to an FP type half the size, then round
6247       // the FP type to a small FP type if needed.
6248 
6249       MVT InterimFVT = DstVT;
6250       if (SrcEltSize > (2 * DstEltSize)) {
6251         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6252         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6253         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6254       }
6255 
6256       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6257 
6258       if (InterimFVT != DstVT) {
6259         Src = Result;
6260         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6261       }
6262     } else {
6263       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6264              "Wrong input/output vector types");
6265       // First do a narrowing conversion to an integer half the size, then
6266       // truncate if needed.
6267 
6268       if (DstEltSize == 1) {
6269         // First convert to the same size integer, then convert to mask using
6270         // setcc.
6271         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6272         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6273                                           DstVT.getVectorElementCount());
6274         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6275 
6276         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6277         // otherwise the conversion was undefined.
6278         MVT XLenVT = Subtarget.getXLenVT();
6279         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6280         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6281                                 DAG.getUNDEF(InterimIVT), SplatZero);
6282         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6283                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6284       } else {
6285         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6286                                           DstVT.getVectorElementCount());
6287 
6288         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6289 
6290         while (InterimIVT != DstVT) {
6291           SrcEltSize /= 2;
6292           Src = Result;
6293           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6294                                         DstVT.getVectorElementCount());
6295           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6296                                Src, Mask, VL);
6297         }
6298       }
6299     }
6300   }
6301 
6302   MVT VT = Op.getSimpleValueType();
6303   if (!VT.isFixedLengthVector())
6304     return Result;
6305   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6306 }
6307 
6308 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6309                                             unsigned MaskOpc,
6310                                             unsigned VecOpc) const {
6311   MVT VT = Op.getSimpleValueType();
6312   if (VT.getVectorElementType() != MVT::i1)
6313     return lowerVPOp(Op, DAG, VecOpc);
6314 
6315   // It is safe to drop mask parameter as masked-off elements are undef.
6316   SDValue Op1 = Op->getOperand(0);
6317   SDValue Op2 = Op->getOperand(1);
6318   SDValue VL = Op->getOperand(3);
6319 
6320   MVT ContainerVT = VT;
6321   const bool IsFixed = VT.isFixedLengthVector();
6322   if (IsFixed) {
6323     ContainerVT = getContainerForFixedLengthVector(VT);
6324     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6325     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6326   }
6327 
6328   SDLoc DL(Op);
6329   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6330   if (!IsFixed)
6331     return Val;
6332   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6333 }
6334 
6335 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6336 // matched to a RVV indexed load. The RVV indexed load instructions only
6337 // support the "unsigned unscaled" addressing mode; indices are implicitly
6338 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6339 // signed or scaled indexing is extended to the XLEN value type and scaled
6340 // accordingly.
6341 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6342                                                SelectionDAG &DAG) const {
6343   SDLoc DL(Op);
6344   MVT VT = Op.getSimpleValueType();
6345 
6346   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6347   EVT MemVT = MemSD->getMemoryVT();
6348   MachineMemOperand *MMO = MemSD->getMemOperand();
6349   SDValue Chain = MemSD->getChain();
6350   SDValue BasePtr = MemSD->getBasePtr();
6351 
6352   ISD::LoadExtType LoadExtType;
6353   SDValue Index, Mask, PassThru, VL;
6354 
6355   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6356     Index = VPGN->getIndex();
6357     Mask = VPGN->getMask();
6358     PassThru = DAG.getUNDEF(VT);
6359     VL = VPGN->getVectorLength();
6360     // VP doesn't support extending loads.
6361     LoadExtType = ISD::NON_EXTLOAD;
6362   } else {
6363     // Else it must be a MGATHER.
6364     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6365     Index = MGN->getIndex();
6366     Mask = MGN->getMask();
6367     PassThru = MGN->getPassThru();
6368     LoadExtType = MGN->getExtensionType();
6369   }
6370 
6371   MVT IndexVT = Index.getSimpleValueType();
6372   MVT XLenVT = Subtarget.getXLenVT();
6373 
6374   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6375          "Unexpected VTs!");
6376   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6377   // Targets have to explicitly opt-in for extending vector loads.
6378   assert(LoadExtType == ISD::NON_EXTLOAD &&
6379          "Unexpected extending MGATHER/VP_GATHER");
6380   (void)LoadExtType;
6381 
6382   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6383   // the selection of the masked intrinsics doesn't do this for us.
6384   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6385 
6386   MVT ContainerVT = VT;
6387   if (VT.isFixedLengthVector()) {
6388     ContainerVT = getContainerForFixedLengthVector(VT);
6389     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6390                                ContainerVT.getVectorElementCount());
6391 
6392     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6393 
6394     if (!IsUnmasked) {
6395       MVT MaskVT = getMaskTypeFor(ContainerVT);
6396       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6397       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6398     }
6399   }
6400 
6401   if (!VL)
6402     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6403 
6404   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6405     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6406     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6407                                    VL);
6408     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6409                         TrueMask, VL);
6410   }
6411 
6412   unsigned IntID =
6413       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6414   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6415   if (IsUnmasked)
6416     Ops.push_back(DAG.getUNDEF(ContainerVT));
6417   else
6418     Ops.push_back(PassThru);
6419   Ops.push_back(BasePtr);
6420   Ops.push_back(Index);
6421   if (!IsUnmasked)
6422     Ops.push_back(Mask);
6423   Ops.push_back(VL);
6424   if (!IsUnmasked)
6425     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6426 
6427   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6428   SDValue Result =
6429       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6430   Chain = Result.getValue(1);
6431 
6432   if (VT.isFixedLengthVector())
6433     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6434 
6435   return DAG.getMergeValues({Result, Chain}, DL);
6436 }
6437 
6438 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6439 // matched to a RVV indexed store. The RVV indexed store instructions only
6440 // support the "unsigned unscaled" addressing mode; indices are implicitly
6441 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6442 // signed or scaled indexing is extended to the XLEN value type and scaled
6443 // accordingly.
6444 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6445                                                 SelectionDAG &DAG) const {
6446   SDLoc DL(Op);
6447   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6448   EVT MemVT = MemSD->getMemoryVT();
6449   MachineMemOperand *MMO = MemSD->getMemOperand();
6450   SDValue Chain = MemSD->getChain();
6451   SDValue BasePtr = MemSD->getBasePtr();
6452 
6453   bool IsTruncatingStore = false;
6454   SDValue Index, Mask, Val, VL;
6455 
6456   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6457     Index = VPSN->getIndex();
6458     Mask = VPSN->getMask();
6459     Val = VPSN->getValue();
6460     VL = VPSN->getVectorLength();
6461     // VP doesn't support truncating stores.
6462     IsTruncatingStore = false;
6463   } else {
6464     // Else it must be a MSCATTER.
6465     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6466     Index = MSN->getIndex();
6467     Mask = MSN->getMask();
6468     Val = MSN->getValue();
6469     IsTruncatingStore = MSN->isTruncatingStore();
6470   }
6471 
6472   MVT VT = Val.getSimpleValueType();
6473   MVT IndexVT = Index.getSimpleValueType();
6474   MVT XLenVT = Subtarget.getXLenVT();
6475 
6476   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6477          "Unexpected VTs!");
6478   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6479   // Targets have to explicitly opt-in for extending vector loads and
6480   // truncating vector stores.
6481   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6482   (void)IsTruncatingStore;
6483 
6484   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6485   // the selection of the masked intrinsics doesn't do this for us.
6486   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6487 
6488   MVT ContainerVT = VT;
6489   if (VT.isFixedLengthVector()) {
6490     ContainerVT = getContainerForFixedLengthVector(VT);
6491     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6492                                ContainerVT.getVectorElementCount());
6493 
6494     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6495     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6496 
6497     if (!IsUnmasked) {
6498       MVT MaskVT = getMaskTypeFor(ContainerVT);
6499       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6500     }
6501   }
6502 
6503   if (!VL)
6504     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6505 
6506   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6507     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6508     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6509                                    VL);
6510     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6511                         TrueMask, VL);
6512   }
6513 
6514   unsigned IntID =
6515       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6516   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6517   Ops.push_back(Val);
6518   Ops.push_back(BasePtr);
6519   Ops.push_back(Index);
6520   if (!IsUnmasked)
6521     Ops.push_back(Mask);
6522   Ops.push_back(VL);
6523 
6524   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6525                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6526 }
6527 
6528 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6529                                                SelectionDAG &DAG) const {
6530   const MVT XLenVT = Subtarget.getXLenVT();
6531   SDLoc DL(Op);
6532   SDValue Chain = Op->getOperand(0);
6533   SDValue SysRegNo = DAG.getTargetConstant(
6534       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6535   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6536   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6537 
6538   // Encoding used for rounding mode in RISCV differs from that used in
6539   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6540   // table, which consists of a sequence of 4-bit fields, each representing
6541   // corresponding FLT_ROUNDS mode.
6542   static const int Table =
6543       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6544       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6545       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6546       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6547       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6548 
6549   SDValue Shift =
6550       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6551   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6552                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6553   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6554                                DAG.getConstant(7, DL, XLenVT));
6555 
6556   return DAG.getMergeValues({Masked, Chain}, DL);
6557 }
6558 
6559 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6560                                                SelectionDAG &DAG) const {
6561   const MVT XLenVT = Subtarget.getXLenVT();
6562   SDLoc DL(Op);
6563   SDValue Chain = Op->getOperand(0);
6564   SDValue RMValue = Op->getOperand(1);
6565   SDValue SysRegNo = DAG.getTargetConstant(
6566       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6567 
6568   // Encoding used for rounding mode in RISCV differs from that used in
6569   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6570   // a table, which consists of a sequence of 4-bit fields, each representing
6571   // corresponding RISCV mode.
6572   static const unsigned Table =
6573       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6574       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6575       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6576       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6577       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6578 
6579   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6580                               DAG.getConstant(2, DL, XLenVT));
6581   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6582                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6583   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6584                         DAG.getConstant(0x7, DL, XLenVT));
6585   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6586                      RMValue);
6587 }
6588 
6589 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6590   switch (IntNo) {
6591   default:
6592     llvm_unreachable("Unexpected Intrinsic");
6593   case Intrinsic::riscv_bcompress:
6594     return RISCVISD::BCOMPRESSW;
6595   case Intrinsic::riscv_bdecompress:
6596     return RISCVISD::BDECOMPRESSW;
6597   case Intrinsic::riscv_bfp:
6598     return RISCVISD::BFPW;
6599   case Intrinsic::riscv_fsl:
6600     return RISCVISD::FSLW;
6601   case Intrinsic::riscv_fsr:
6602     return RISCVISD::FSRW;
6603   }
6604 }
6605 
6606 // Converts the given intrinsic to a i64 operation with any extension.
6607 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6608                                          unsigned IntNo) {
6609   SDLoc DL(N);
6610   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6611   // Deal with the Instruction Operands
6612   SmallVector<SDValue, 3> NewOps;
6613   for (SDValue Op : drop_begin(N->ops()))
6614     // Promote the operand to i64 type
6615     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6616   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6617   // ReplaceNodeResults requires we maintain the same type for the return value.
6618   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6619 }
6620 
6621 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6622 // form of the given Opcode.
6623 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6624   switch (Opcode) {
6625   default:
6626     llvm_unreachable("Unexpected opcode");
6627   case ISD::SHL:
6628     return RISCVISD::SLLW;
6629   case ISD::SRA:
6630     return RISCVISD::SRAW;
6631   case ISD::SRL:
6632     return RISCVISD::SRLW;
6633   case ISD::SDIV:
6634     return RISCVISD::DIVW;
6635   case ISD::UDIV:
6636     return RISCVISD::DIVUW;
6637   case ISD::UREM:
6638     return RISCVISD::REMUW;
6639   case ISD::ROTL:
6640     return RISCVISD::ROLW;
6641   case ISD::ROTR:
6642     return RISCVISD::RORW;
6643   }
6644 }
6645 
6646 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6647 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6648 // otherwise be promoted to i64, making it difficult to select the
6649 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6650 // type i8/i16/i32 is lost.
6651 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6652                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6653   SDLoc DL(N);
6654   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6655   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6656   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6657   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6658   // ReplaceNodeResults requires we maintain the same type for the return value.
6659   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6660 }
6661 
6662 // Converts the given 32-bit operation to a i64 operation with signed extension
6663 // semantic to reduce the signed extension instructions.
6664 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6665   SDLoc DL(N);
6666   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6667   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6668   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6669   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6670                                DAG.getValueType(MVT::i32));
6671   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6672 }
6673 
6674 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6675                                              SmallVectorImpl<SDValue> &Results,
6676                                              SelectionDAG &DAG) const {
6677   SDLoc DL(N);
6678   switch (N->getOpcode()) {
6679   default:
6680     llvm_unreachable("Don't know how to custom type legalize this operation!");
6681   case ISD::STRICT_FP_TO_SINT:
6682   case ISD::STRICT_FP_TO_UINT:
6683   case ISD::FP_TO_SINT:
6684   case ISD::FP_TO_UINT: {
6685     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6686            "Unexpected custom legalisation");
6687     bool IsStrict = N->isStrictFPOpcode();
6688     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6689                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6690     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6691     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6692         TargetLowering::TypeSoftenFloat) {
6693       if (!isTypeLegal(Op0.getValueType()))
6694         return;
6695       if (IsStrict) {
6696         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6697                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6698         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6699         SDValue Res = DAG.getNode(
6700             Opc, DL, VTs, N->getOperand(0), Op0,
6701             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6702         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6703         Results.push_back(Res.getValue(1));
6704         return;
6705       }
6706       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6707       SDValue Res =
6708           DAG.getNode(Opc, DL, MVT::i64, Op0,
6709                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6710       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6711       return;
6712     }
6713     // If the FP type needs to be softened, emit a library call using the 'si'
6714     // version. If we left it to default legalization we'd end up with 'di'. If
6715     // the FP type doesn't need to be softened just let generic type
6716     // legalization promote the result type.
6717     RTLIB::Libcall LC;
6718     if (IsSigned)
6719       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6720     else
6721       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6722     MakeLibCallOptions CallOptions;
6723     EVT OpVT = Op0.getValueType();
6724     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6725     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6726     SDValue Result;
6727     std::tie(Result, Chain) =
6728         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6729     Results.push_back(Result);
6730     if (IsStrict)
6731       Results.push_back(Chain);
6732     break;
6733   }
6734   case ISD::READCYCLECOUNTER: {
6735     assert(!Subtarget.is64Bit() &&
6736            "READCYCLECOUNTER only has custom type legalization on riscv32");
6737 
6738     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6739     SDValue RCW =
6740         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6741 
6742     Results.push_back(
6743         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6744     Results.push_back(RCW.getValue(2));
6745     break;
6746   }
6747   case ISD::MUL: {
6748     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6749     unsigned XLen = Subtarget.getXLen();
6750     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6751     if (Size > XLen) {
6752       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6753       SDValue LHS = N->getOperand(0);
6754       SDValue RHS = N->getOperand(1);
6755       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6756 
6757       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6758       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6759       // We need exactly one side to be unsigned.
6760       if (LHSIsU == RHSIsU)
6761         return;
6762 
6763       auto MakeMULPair = [&](SDValue S, SDValue U) {
6764         MVT XLenVT = Subtarget.getXLenVT();
6765         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6766         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6767         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6768         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6769         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6770       };
6771 
6772       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6773       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6774 
6775       // The other operand should be signed, but still prefer MULH when
6776       // possible.
6777       if (RHSIsU && LHSIsS && !RHSIsS)
6778         Results.push_back(MakeMULPair(LHS, RHS));
6779       else if (LHSIsU && RHSIsS && !LHSIsS)
6780         Results.push_back(MakeMULPair(RHS, LHS));
6781 
6782       return;
6783     }
6784     LLVM_FALLTHROUGH;
6785   }
6786   case ISD::ADD:
6787   case ISD::SUB:
6788     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6789            "Unexpected custom legalisation");
6790     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6791     break;
6792   case ISD::SHL:
6793   case ISD::SRA:
6794   case ISD::SRL:
6795     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6796            "Unexpected custom legalisation");
6797     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6798       // If we can use a BSET instruction, allow default promotion to apply.
6799       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6800           isOneConstant(N->getOperand(0)))
6801         break;
6802       Results.push_back(customLegalizeToWOp(N, DAG));
6803       break;
6804     }
6805 
6806     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6807     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6808     // shift amount.
6809     if (N->getOpcode() == ISD::SHL) {
6810       SDLoc DL(N);
6811       SDValue NewOp0 =
6812           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6813       SDValue NewOp1 =
6814           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6815       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6816       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6817                                    DAG.getValueType(MVT::i32));
6818       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6819     }
6820 
6821     break;
6822   case ISD::ROTL:
6823   case ISD::ROTR:
6824     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6825            "Unexpected custom legalisation");
6826     Results.push_back(customLegalizeToWOp(N, DAG));
6827     break;
6828   case ISD::CTTZ:
6829   case ISD::CTTZ_ZERO_UNDEF:
6830   case ISD::CTLZ:
6831   case ISD::CTLZ_ZERO_UNDEF: {
6832     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6833            "Unexpected custom legalisation");
6834 
6835     SDValue NewOp0 =
6836         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6837     bool IsCTZ =
6838         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6839     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6840     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6841     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6842     return;
6843   }
6844   case ISD::SDIV:
6845   case ISD::UDIV:
6846   case ISD::UREM: {
6847     MVT VT = N->getSimpleValueType(0);
6848     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6849            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6850            "Unexpected custom legalisation");
6851     // Don't promote division/remainder by constant since we should expand those
6852     // to multiply by magic constant.
6853     // FIXME: What if the expansion is disabled for minsize.
6854     if (N->getOperand(1).getOpcode() == ISD::Constant)
6855       return;
6856 
6857     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6858     // the upper 32 bits. For other types we need to sign or zero extend
6859     // based on the opcode.
6860     unsigned ExtOpc = ISD::ANY_EXTEND;
6861     if (VT != MVT::i32)
6862       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6863                                            : ISD::ZERO_EXTEND;
6864 
6865     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6866     break;
6867   }
6868   case ISD::UADDO:
6869   case ISD::USUBO: {
6870     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6871            "Unexpected custom legalisation");
6872     bool IsAdd = N->getOpcode() == ISD::UADDO;
6873     // Create an ADDW or SUBW.
6874     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6875     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6876     SDValue Res =
6877         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6878     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6879                       DAG.getValueType(MVT::i32));
6880 
6881     SDValue Overflow;
6882     if (IsAdd && isOneConstant(RHS)) {
6883       // Special case uaddo X, 1 overflowed if the addition result is 0.
6884       // The general case (X + C) < C is not necessarily beneficial. Although we
6885       // reduce the live range of X, we may introduce the materialization of
6886       // constant C, especially when the setcc result is used by branch. We have
6887       // no compare with constant and branch instructions.
6888       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6889                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6890     } else {
6891       // Sign extend the LHS and perform an unsigned compare with the ADDW
6892       // result. Since the inputs are sign extended from i32, this is equivalent
6893       // to comparing the lower 32 bits.
6894       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6895       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6896                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6897     }
6898 
6899     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6900     Results.push_back(Overflow);
6901     return;
6902   }
6903   case ISD::UADDSAT:
6904   case ISD::USUBSAT: {
6905     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6906            "Unexpected custom legalisation");
6907     if (Subtarget.hasStdExtZbb()) {
6908       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6909       // sign extend allows overflow of the lower 32 bits to be detected on
6910       // the promoted size.
6911       SDValue LHS =
6912           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6913       SDValue RHS =
6914           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6915       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6916       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6917       return;
6918     }
6919 
6920     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6921     // promotion for UADDO/USUBO.
6922     Results.push_back(expandAddSubSat(N, DAG));
6923     return;
6924   }
6925   case ISD::ABS: {
6926     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6927            "Unexpected custom legalisation");
6928           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6929 
6930     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6931 
6932     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6933 
6934     // Freeze the source so we can increase it's use count.
6935     Src = DAG.getFreeze(Src);
6936 
6937     // Copy sign bit to all bits using the sraiw pattern.
6938     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6939                                    DAG.getValueType(MVT::i32));
6940     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6941                            DAG.getConstant(31, DL, MVT::i64));
6942 
6943     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6944     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6945 
6946     // NOTE: The result is only required to be anyextended, but sext is
6947     // consistent with type legalization of sub.
6948     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6949                          DAG.getValueType(MVT::i32));
6950     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6951     return;
6952   }
6953   case ISD::BITCAST: {
6954     EVT VT = N->getValueType(0);
6955     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6956     SDValue Op0 = N->getOperand(0);
6957     EVT Op0VT = Op0.getValueType();
6958     MVT XLenVT = Subtarget.getXLenVT();
6959     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6960       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6961       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6962     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6963                Subtarget.hasStdExtF()) {
6964       SDValue FPConv =
6965           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6966       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6967     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6968                isTypeLegal(Op0VT)) {
6969       // Custom-legalize bitcasts from fixed-length vector types to illegal
6970       // scalar types in order to improve codegen. Bitcast the vector to a
6971       // one-element vector type whose element type is the same as the result
6972       // type, and extract the first element.
6973       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6974       if (isTypeLegal(BVT)) {
6975         SDValue BVec = DAG.getBitcast(BVT, Op0);
6976         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6977                                       DAG.getConstant(0, DL, XLenVT)));
6978       }
6979     }
6980     break;
6981   }
6982   case RISCVISD::GREV:
6983   case RISCVISD::GORC:
6984   case RISCVISD::SHFL: {
6985     MVT VT = N->getSimpleValueType(0);
6986     MVT XLenVT = Subtarget.getXLenVT();
6987     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
6988            "Unexpected custom legalisation");
6989     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6990     assert((Subtarget.hasStdExtZbp() ||
6991             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
6992              N->getConstantOperandVal(1) == 7)) &&
6993            "Unexpected extension");
6994     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6995     SDValue NewOp1 =
6996         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
6997     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
6998     // ReplaceNodeResults requires we maintain the same type for the return
6999     // value.
7000     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7001     break;
7002   }
7003   case ISD::BSWAP:
7004   case ISD::BITREVERSE: {
7005     MVT VT = N->getSimpleValueType(0);
7006     MVT XLenVT = Subtarget.getXLenVT();
7007     assert((VT == MVT::i8 || VT == MVT::i16 ||
7008             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7009            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7010     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7011     unsigned Imm = VT.getSizeInBits() - 1;
7012     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7013     if (N->getOpcode() == ISD::BSWAP)
7014       Imm &= ~0x7U;
7015     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7016                                 DAG.getConstant(Imm, DL, XLenVT));
7017     // ReplaceNodeResults requires we maintain the same type for the return
7018     // value.
7019     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7020     break;
7021   }
7022   case ISD::FSHL:
7023   case ISD::FSHR: {
7024     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7025            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7026     SDValue NewOp0 =
7027         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7028     SDValue NewOp1 =
7029         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7030     SDValue NewShAmt =
7031         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7032     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7033     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7034     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7035                            DAG.getConstant(0x1f, DL, MVT::i64));
7036     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7037     // instruction use different orders. fshl will return its first operand for
7038     // shift of zero, fshr will return its second operand. fsl and fsr both
7039     // return rs1 so the ISD nodes need to have different operand orders.
7040     // Shift amount is in rs2.
7041     unsigned Opc = RISCVISD::FSLW;
7042     if (N->getOpcode() == ISD::FSHR) {
7043       std::swap(NewOp0, NewOp1);
7044       Opc = RISCVISD::FSRW;
7045     }
7046     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7047     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7048     break;
7049   }
7050   case ISD::EXTRACT_VECTOR_ELT: {
7051     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7052     // type is illegal (currently only vXi64 RV32).
7053     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7054     // transferred to the destination register. We issue two of these from the
7055     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7056     // first element.
7057     SDValue Vec = N->getOperand(0);
7058     SDValue Idx = N->getOperand(1);
7059 
7060     // The vector type hasn't been legalized yet so we can't issue target
7061     // specific nodes if it needs legalization.
7062     // FIXME: We would manually legalize if it's important.
7063     if (!isTypeLegal(Vec.getValueType()))
7064       return;
7065 
7066     MVT VecVT = Vec.getSimpleValueType();
7067 
7068     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7069            VecVT.getVectorElementType() == MVT::i64 &&
7070            "Unexpected EXTRACT_VECTOR_ELT legalization");
7071 
7072     // If this is a fixed vector, we need to convert it to a scalable vector.
7073     MVT ContainerVT = VecVT;
7074     if (VecVT.isFixedLengthVector()) {
7075       ContainerVT = getContainerForFixedLengthVector(VecVT);
7076       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7077     }
7078 
7079     MVT XLenVT = Subtarget.getXLenVT();
7080 
7081     // Use a VL of 1 to avoid processing more elements than we need.
7082     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7083     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7084 
7085     // Unless the index is known to be 0, we must slide the vector down to get
7086     // the desired element into index 0.
7087     if (!isNullConstant(Idx)) {
7088       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7089                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7090     }
7091 
7092     // Extract the lower XLEN bits of the correct vector element.
7093     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7094 
7095     // To extract the upper XLEN bits of the vector element, shift the first
7096     // element right by 32 bits and re-extract the lower XLEN bits.
7097     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7098                                      DAG.getUNDEF(ContainerVT),
7099                                      DAG.getConstant(32, DL, XLenVT), VL);
7100     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7101                                  ThirtyTwoV, Mask, VL);
7102 
7103     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7104 
7105     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7106     break;
7107   }
7108   case ISD::INTRINSIC_WO_CHAIN: {
7109     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7110     switch (IntNo) {
7111     default:
7112       llvm_unreachable(
7113           "Don't know how to custom type legalize this intrinsic!");
7114     case Intrinsic::riscv_grev:
7115     case Intrinsic::riscv_gorc: {
7116       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7117              "Unexpected custom legalisation");
7118       SDValue NewOp1 =
7119           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7120       SDValue NewOp2 =
7121           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7122       unsigned Opc =
7123           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7124       // If the control is a constant, promote the node by clearing any extra
7125       // bits bits in the control. isel will form greviw/gorciw if the result is
7126       // sign extended.
7127       if (isa<ConstantSDNode>(NewOp2)) {
7128         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7129                              DAG.getConstant(0x1f, DL, MVT::i64));
7130         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7131       }
7132       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7133       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7134       break;
7135     }
7136     case Intrinsic::riscv_bcompress:
7137     case Intrinsic::riscv_bdecompress:
7138     case Intrinsic::riscv_bfp:
7139     case Intrinsic::riscv_fsl:
7140     case Intrinsic::riscv_fsr: {
7141       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7142              "Unexpected custom legalisation");
7143       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7144       break;
7145     }
7146     case Intrinsic::riscv_orc_b: {
7147       // Lower to the GORCI encoding for orc.b with the operand extended.
7148       SDValue NewOp =
7149           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7150       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7151                                 DAG.getConstant(7, DL, MVT::i64));
7152       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7153       return;
7154     }
7155     case Intrinsic::riscv_shfl:
7156     case Intrinsic::riscv_unshfl: {
7157       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7158              "Unexpected custom legalisation");
7159       SDValue NewOp1 =
7160           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7161       SDValue NewOp2 =
7162           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7163       unsigned Opc =
7164           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7165       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7166       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7167       // will be shuffled the same way as the lower 32 bit half, but the two
7168       // halves won't cross.
7169       if (isa<ConstantSDNode>(NewOp2)) {
7170         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7171                              DAG.getConstant(0xf, DL, MVT::i64));
7172         Opc =
7173             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7174       }
7175       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7176       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7177       break;
7178     }
7179     case Intrinsic::riscv_vmv_x_s: {
7180       EVT VT = N->getValueType(0);
7181       MVT XLenVT = Subtarget.getXLenVT();
7182       if (VT.bitsLT(XLenVT)) {
7183         // Simple case just extract using vmv.x.s and truncate.
7184         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7185                                       Subtarget.getXLenVT(), N->getOperand(1));
7186         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7187         return;
7188       }
7189 
7190       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7191              "Unexpected custom legalization");
7192 
7193       // We need to do the move in two steps.
7194       SDValue Vec = N->getOperand(1);
7195       MVT VecVT = Vec.getSimpleValueType();
7196 
7197       // First extract the lower XLEN bits of the element.
7198       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7199 
7200       // To extract the upper XLEN bits of the vector element, shift the first
7201       // element right by 32 bits and re-extract the lower XLEN bits.
7202       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7203       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7204 
7205       SDValue ThirtyTwoV =
7206           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7207                       DAG.getConstant(32, DL, XLenVT), VL);
7208       SDValue LShr32 =
7209           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7210       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7211 
7212       Results.push_back(
7213           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7214       break;
7215     }
7216     }
7217     break;
7218   }
7219   case ISD::VECREDUCE_ADD:
7220   case ISD::VECREDUCE_AND:
7221   case ISD::VECREDUCE_OR:
7222   case ISD::VECREDUCE_XOR:
7223   case ISD::VECREDUCE_SMAX:
7224   case ISD::VECREDUCE_UMAX:
7225   case ISD::VECREDUCE_SMIN:
7226   case ISD::VECREDUCE_UMIN:
7227     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7228       Results.push_back(V);
7229     break;
7230   case ISD::VP_REDUCE_ADD:
7231   case ISD::VP_REDUCE_AND:
7232   case ISD::VP_REDUCE_OR:
7233   case ISD::VP_REDUCE_XOR:
7234   case ISD::VP_REDUCE_SMAX:
7235   case ISD::VP_REDUCE_UMAX:
7236   case ISD::VP_REDUCE_SMIN:
7237   case ISD::VP_REDUCE_UMIN:
7238     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7239       Results.push_back(V);
7240     break;
7241   case ISD::FLT_ROUNDS_: {
7242     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7243     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7244     Results.push_back(Res.getValue(0));
7245     Results.push_back(Res.getValue(1));
7246     break;
7247   }
7248   }
7249 }
7250 
7251 // A structure to hold one of the bit-manipulation patterns below. Together, a
7252 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7253 //   (or (and (shl x, 1), 0xAAAAAAAA),
7254 //       (and (srl x, 1), 0x55555555))
7255 struct RISCVBitmanipPat {
7256   SDValue Op;
7257   unsigned ShAmt;
7258   bool IsSHL;
7259 
7260   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7261     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7262   }
7263 };
7264 
7265 // Matches patterns of the form
7266 //   (and (shl x, C2), (C1 << C2))
7267 //   (and (srl x, C2), C1)
7268 //   (shl (and x, C1), C2)
7269 //   (srl (and x, (C1 << C2)), C2)
7270 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7271 // The expected masks for each shift amount are specified in BitmanipMasks where
7272 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7273 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7274 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7275 // XLen is 64.
7276 static Optional<RISCVBitmanipPat>
7277 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7278   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7279          "Unexpected number of masks");
7280   Optional<uint64_t> Mask;
7281   // Optionally consume a mask around the shift operation.
7282   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7283     Mask = Op.getConstantOperandVal(1);
7284     Op = Op.getOperand(0);
7285   }
7286   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7287     return None;
7288   bool IsSHL = Op.getOpcode() == ISD::SHL;
7289 
7290   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7291     return None;
7292   uint64_t ShAmt = Op.getConstantOperandVal(1);
7293 
7294   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7295   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7296     return None;
7297   // If we don't have enough masks for 64 bit, then we must be trying to
7298   // match SHFL so we're only allowed to shift 1/4 of the width.
7299   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7300     return None;
7301 
7302   SDValue Src = Op.getOperand(0);
7303 
7304   // The expected mask is shifted left when the AND is found around SHL
7305   // patterns.
7306   //   ((x >> 1) & 0x55555555)
7307   //   ((x << 1) & 0xAAAAAAAA)
7308   bool SHLExpMask = IsSHL;
7309 
7310   if (!Mask) {
7311     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7312     // the mask is all ones: consume that now.
7313     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7314       Mask = Src.getConstantOperandVal(1);
7315       Src = Src.getOperand(0);
7316       // The expected mask is now in fact shifted left for SRL, so reverse the
7317       // decision.
7318       //   ((x & 0xAAAAAAAA) >> 1)
7319       //   ((x & 0x55555555) << 1)
7320       SHLExpMask = !SHLExpMask;
7321     } else {
7322       // Use a default shifted mask of all-ones if there's no AND, truncated
7323       // down to the expected width. This simplifies the logic later on.
7324       Mask = maskTrailingOnes<uint64_t>(Width);
7325       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7326     }
7327   }
7328 
7329   unsigned MaskIdx = Log2_32(ShAmt);
7330   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7331 
7332   if (SHLExpMask)
7333     ExpMask <<= ShAmt;
7334 
7335   if (Mask != ExpMask)
7336     return None;
7337 
7338   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7339 }
7340 
7341 // Matches any of the following bit-manipulation patterns:
7342 //   (and (shl x, 1), (0x55555555 << 1))
7343 //   (and (srl x, 1), 0x55555555)
7344 //   (shl (and x, 0x55555555), 1)
7345 //   (srl (and x, (0x55555555 << 1)), 1)
7346 // where the shift amount and mask may vary thus:
7347 //   [1]  = 0x55555555 / 0xAAAAAAAA
7348 //   [2]  = 0x33333333 / 0xCCCCCCCC
7349 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7350 //   [8]  = 0x00FF00FF / 0xFF00FF00
7351 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7352 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7353 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7354   // These are the unshifted masks which we use to match bit-manipulation
7355   // patterns. They may be shifted left in certain circumstances.
7356   static const uint64_t BitmanipMasks[] = {
7357       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7358       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7359 
7360   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7361 }
7362 
7363 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7364 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7365   auto BinOpToRVVReduce = [](unsigned Opc) {
7366     switch (Opc) {
7367     default:
7368       llvm_unreachable("Unhandled binary to transfrom reduction");
7369     case ISD::ADD:
7370       return RISCVISD::VECREDUCE_ADD_VL;
7371     case ISD::UMAX:
7372       return RISCVISD::VECREDUCE_UMAX_VL;
7373     case ISD::SMAX:
7374       return RISCVISD::VECREDUCE_SMAX_VL;
7375     case ISD::UMIN:
7376       return RISCVISD::VECREDUCE_UMIN_VL;
7377     case ISD::SMIN:
7378       return RISCVISD::VECREDUCE_SMIN_VL;
7379     case ISD::AND:
7380       return RISCVISD::VECREDUCE_AND_VL;
7381     case ISD::OR:
7382       return RISCVISD::VECREDUCE_OR_VL;
7383     case ISD::XOR:
7384       return RISCVISD::VECREDUCE_XOR_VL;
7385     case ISD::FADD:
7386       return RISCVISD::VECREDUCE_FADD_VL;
7387     case ISD::FMAXNUM:
7388       return RISCVISD::VECREDUCE_FMAX_VL;
7389     case ISD::FMINNUM:
7390       return RISCVISD::VECREDUCE_FMIN_VL;
7391     }
7392   };
7393 
7394   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7395     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7396            isNullConstant(V.getOperand(1)) &&
7397            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7398   };
7399 
7400   unsigned Opc = N->getOpcode();
7401   unsigned ReduceIdx;
7402   if (IsReduction(N->getOperand(0), Opc))
7403     ReduceIdx = 0;
7404   else if (IsReduction(N->getOperand(1), Opc))
7405     ReduceIdx = 1;
7406   else
7407     return SDValue();
7408 
7409   // Skip if FADD disallows reassociation but the combiner needs.
7410   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7411     return SDValue();
7412 
7413   SDValue Extract = N->getOperand(ReduceIdx);
7414   SDValue Reduce = Extract.getOperand(0);
7415   if (!Reduce.hasOneUse())
7416     return SDValue();
7417 
7418   SDValue ScalarV = Reduce.getOperand(2);
7419 
7420   // Make sure that ScalarV is a splat with VL=1.
7421   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7422       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7423       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7424     return SDValue();
7425 
7426   if (!isOneConstant(ScalarV.getOperand(2)))
7427     return SDValue();
7428 
7429   // TODO: Deal with value other than neutral element.
7430   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7431     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7432         isNullFPConstant(V))
7433       return true;
7434     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7435                                  N->getFlags()) == V;
7436   };
7437 
7438   // Check the scalar of ScalarV is neutral element
7439   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7440     return SDValue();
7441 
7442   if (!ScalarV.hasOneUse())
7443     return SDValue();
7444 
7445   EVT SplatVT = ScalarV.getValueType();
7446   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7447   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7448   if (SplatVT.isInteger()) {
7449     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7450     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7451       SplatOpc = RISCVISD::VMV_S_X_VL;
7452     else
7453       SplatOpc = RISCVISD::VMV_V_X_VL;
7454   }
7455 
7456   SDValue NewScalarV =
7457       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7458                   ScalarV.getOperand(2));
7459   SDValue NewReduce =
7460       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7461                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7462                   Reduce.getOperand(3), Reduce.getOperand(4));
7463   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7464                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7465 }
7466 
7467 // Match the following pattern as a GREVI(W) operation
7468 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7469 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7470                                const RISCVSubtarget &Subtarget) {
7471   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7472   EVT VT = Op.getValueType();
7473 
7474   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7475     auto LHS = matchGREVIPat(Op.getOperand(0));
7476     auto RHS = matchGREVIPat(Op.getOperand(1));
7477     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7478       SDLoc DL(Op);
7479       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7480                          DAG.getConstant(LHS->ShAmt, DL, VT));
7481     }
7482   }
7483   return SDValue();
7484 }
7485 
7486 // Matches any the following pattern as a GORCI(W) operation
7487 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7488 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7489 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7490 // Note that with the variant of 3.,
7491 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7492 // the inner pattern will first be matched as GREVI and then the outer
7493 // pattern will be matched to GORC via the first rule above.
7494 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7495 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7496                                const RISCVSubtarget &Subtarget) {
7497   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7498   EVT VT = Op.getValueType();
7499 
7500   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7501     SDLoc DL(Op);
7502     SDValue Op0 = Op.getOperand(0);
7503     SDValue Op1 = Op.getOperand(1);
7504 
7505     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7506       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7507           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7508           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7509         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7510       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7511       if ((Reverse.getOpcode() == ISD::ROTL ||
7512            Reverse.getOpcode() == ISD::ROTR) &&
7513           Reverse.getOperand(0) == X &&
7514           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7515         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7516         if (RotAmt == (VT.getSizeInBits() / 2))
7517           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7518                              DAG.getConstant(RotAmt, DL, VT));
7519       }
7520       return SDValue();
7521     };
7522 
7523     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7524     if (SDValue V = MatchOROfReverse(Op0, Op1))
7525       return V;
7526     if (SDValue V = MatchOROfReverse(Op1, Op0))
7527       return V;
7528 
7529     // OR is commutable so canonicalize its OR operand to the left
7530     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7531       std::swap(Op0, Op1);
7532     if (Op0.getOpcode() != ISD::OR)
7533       return SDValue();
7534     SDValue OrOp0 = Op0.getOperand(0);
7535     SDValue OrOp1 = Op0.getOperand(1);
7536     auto LHS = matchGREVIPat(OrOp0);
7537     // OR is commutable so swap the operands and try again: x might have been
7538     // on the left
7539     if (!LHS) {
7540       std::swap(OrOp0, OrOp1);
7541       LHS = matchGREVIPat(OrOp0);
7542     }
7543     auto RHS = matchGREVIPat(Op1);
7544     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7545       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7546                          DAG.getConstant(LHS->ShAmt, DL, VT));
7547     }
7548   }
7549   return SDValue();
7550 }
7551 
7552 // Matches any of the following bit-manipulation patterns:
7553 //   (and (shl x, 1), (0x22222222 << 1))
7554 //   (and (srl x, 1), 0x22222222)
7555 //   (shl (and x, 0x22222222), 1)
7556 //   (srl (and x, (0x22222222 << 1)), 1)
7557 // where the shift amount and mask may vary thus:
7558 //   [1]  = 0x22222222 / 0x44444444
7559 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7560 //   [4]  = 0x00F000F0 / 0x0F000F00
7561 //   [8]  = 0x0000FF00 / 0x00FF0000
7562 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7563 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7564   // These are the unshifted masks which we use to match bit-manipulation
7565   // patterns. They may be shifted left in certain circumstances.
7566   static const uint64_t BitmanipMasks[] = {
7567       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7568       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7569 
7570   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7571 }
7572 
7573 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7574 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7575                                const RISCVSubtarget &Subtarget) {
7576   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7577   EVT VT = Op.getValueType();
7578 
7579   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7580     return SDValue();
7581 
7582   SDValue Op0 = Op.getOperand(0);
7583   SDValue Op1 = Op.getOperand(1);
7584 
7585   // Or is commutable so canonicalize the second OR to the LHS.
7586   if (Op0.getOpcode() != ISD::OR)
7587     std::swap(Op0, Op1);
7588   if (Op0.getOpcode() != ISD::OR)
7589     return SDValue();
7590 
7591   // We found an inner OR, so our operands are the operands of the inner OR
7592   // and the other operand of the outer OR.
7593   SDValue A = Op0.getOperand(0);
7594   SDValue B = Op0.getOperand(1);
7595   SDValue C = Op1;
7596 
7597   auto Match1 = matchSHFLPat(A);
7598   auto Match2 = matchSHFLPat(B);
7599 
7600   // If neither matched, we failed.
7601   if (!Match1 && !Match2)
7602     return SDValue();
7603 
7604   // We had at least one match. if one failed, try the remaining C operand.
7605   if (!Match1) {
7606     std::swap(A, C);
7607     Match1 = matchSHFLPat(A);
7608     if (!Match1)
7609       return SDValue();
7610   } else if (!Match2) {
7611     std::swap(B, C);
7612     Match2 = matchSHFLPat(B);
7613     if (!Match2)
7614       return SDValue();
7615   }
7616   assert(Match1 && Match2);
7617 
7618   // Make sure our matches pair up.
7619   if (!Match1->formsPairWith(*Match2))
7620     return SDValue();
7621 
7622   // All the remains is to make sure C is an AND with the same input, that masks
7623   // out the bits that are being shuffled.
7624   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7625       C.getOperand(0) != Match1->Op)
7626     return SDValue();
7627 
7628   uint64_t Mask = C.getConstantOperandVal(1);
7629 
7630   static const uint64_t BitmanipMasks[] = {
7631       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7632       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7633   };
7634 
7635   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7636   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7637   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7638 
7639   if (Mask != ExpMask)
7640     return SDValue();
7641 
7642   SDLoc DL(Op);
7643   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7644                      DAG.getConstant(Match1->ShAmt, DL, VT));
7645 }
7646 
7647 // Optimize (add (shl x, c0), (shl y, c1)) ->
7648 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7649 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7650                                   const RISCVSubtarget &Subtarget) {
7651   // Perform this optimization only in the zba extension.
7652   if (!Subtarget.hasStdExtZba())
7653     return SDValue();
7654 
7655   // Skip for vector types and larger types.
7656   EVT VT = N->getValueType(0);
7657   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7658     return SDValue();
7659 
7660   // The two operand nodes must be SHL and have no other use.
7661   SDValue N0 = N->getOperand(0);
7662   SDValue N1 = N->getOperand(1);
7663   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7664       !N0->hasOneUse() || !N1->hasOneUse())
7665     return SDValue();
7666 
7667   // Check c0 and c1.
7668   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7669   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7670   if (!N0C || !N1C)
7671     return SDValue();
7672   int64_t C0 = N0C->getSExtValue();
7673   int64_t C1 = N1C->getSExtValue();
7674   if (C0 <= 0 || C1 <= 0)
7675     return SDValue();
7676 
7677   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7678   int64_t Bits = std::min(C0, C1);
7679   int64_t Diff = std::abs(C0 - C1);
7680   if (Diff != 1 && Diff != 2 && Diff != 3)
7681     return SDValue();
7682 
7683   // Build nodes.
7684   SDLoc DL(N);
7685   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7686   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7687   SDValue NA0 =
7688       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7689   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7690   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7691 }
7692 
7693 // Combine
7694 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7695 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7696 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7697 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7698 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7699 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7700 // The grev patterns represents BSWAP.
7701 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7702 // off the grev.
7703 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7704                                           const RISCVSubtarget &Subtarget) {
7705   bool IsWInstruction =
7706       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7707   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7708           IsWInstruction) &&
7709          "Unexpected opcode!");
7710   SDValue Src = N->getOperand(0);
7711   EVT VT = N->getValueType(0);
7712   SDLoc DL(N);
7713 
7714   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7715     return SDValue();
7716 
7717   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7718       !isa<ConstantSDNode>(Src.getOperand(1)))
7719     return SDValue();
7720 
7721   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7722   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7723 
7724   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7725   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7726   unsigned ShAmt1 = N->getConstantOperandVal(1);
7727   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7728   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7729     return SDValue();
7730 
7731   Src = Src.getOperand(0);
7732 
7733   // Toggle bit the MSB of the shift.
7734   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7735   if (CombinedShAmt == 0)
7736     return Src;
7737 
7738   SDValue Res = DAG.getNode(
7739       RISCVISD::GREV, DL, VT, Src,
7740       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7741   if (!IsWInstruction)
7742     return Res;
7743 
7744   // Sign extend the result to match the behavior of the rotate. This will be
7745   // selected to GREVIW in isel.
7746   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7747                      DAG.getValueType(MVT::i32));
7748 }
7749 
7750 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7751 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7752 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7753 // not undo itself, but they are redundant.
7754 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7755   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7756   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7757   SDValue Src = N->getOperand(0);
7758 
7759   if (Src.getOpcode() != N->getOpcode())
7760     return SDValue();
7761 
7762   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7763       !isa<ConstantSDNode>(Src.getOperand(1)))
7764     return SDValue();
7765 
7766   unsigned ShAmt1 = N->getConstantOperandVal(1);
7767   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7768   Src = Src.getOperand(0);
7769 
7770   unsigned CombinedShAmt;
7771   if (IsGORC)
7772     CombinedShAmt = ShAmt1 | ShAmt2;
7773   else
7774     CombinedShAmt = ShAmt1 ^ ShAmt2;
7775 
7776   if (CombinedShAmt == 0)
7777     return Src;
7778 
7779   SDLoc DL(N);
7780   return DAG.getNode(
7781       N->getOpcode(), DL, N->getValueType(0), Src,
7782       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7783 }
7784 
7785 // Combine a constant select operand into its use:
7786 //
7787 // (and (select cond, -1, c), x)
7788 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7789 // (or  (select cond, 0, c), x)
7790 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7791 // (xor (select cond, 0, c), x)
7792 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7793 // (add (select cond, 0, c), x)
7794 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7795 // (sub x, (select cond, 0, c))
7796 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7797 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7798                                    SelectionDAG &DAG, bool AllOnes) {
7799   EVT VT = N->getValueType(0);
7800 
7801   // Skip vectors.
7802   if (VT.isVector())
7803     return SDValue();
7804 
7805   if ((Slct.getOpcode() != ISD::SELECT &&
7806        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7807       !Slct.hasOneUse())
7808     return SDValue();
7809 
7810   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7811     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7812   };
7813 
7814   bool SwapSelectOps;
7815   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7816   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7817   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7818   SDValue NonConstantVal;
7819   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7820     SwapSelectOps = false;
7821     NonConstantVal = FalseVal;
7822   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7823     SwapSelectOps = true;
7824     NonConstantVal = TrueVal;
7825   } else
7826     return SDValue();
7827 
7828   // Slct is now know to be the desired identity constant when CC is true.
7829   TrueVal = OtherOp;
7830   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7831   // Unless SwapSelectOps says the condition should be false.
7832   if (SwapSelectOps)
7833     std::swap(TrueVal, FalseVal);
7834 
7835   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7836     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7837                        {Slct.getOperand(0), Slct.getOperand(1),
7838                         Slct.getOperand(2), TrueVal, FalseVal});
7839 
7840   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7841                      {Slct.getOperand(0), TrueVal, FalseVal});
7842 }
7843 
7844 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7845 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7846                                               bool AllOnes) {
7847   SDValue N0 = N->getOperand(0);
7848   SDValue N1 = N->getOperand(1);
7849   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7850     return Result;
7851   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7852     return Result;
7853   return SDValue();
7854 }
7855 
7856 // Transform (add (mul x, c0), c1) ->
7857 //           (add (mul (add x, c1/c0), c0), c1%c0).
7858 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7859 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7860 // to an infinite loop in DAGCombine if transformed.
7861 // Or transform (add (mul x, c0), c1) ->
7862 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7863 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7864 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7865 // lead to an infinite loop in DAGCombine if transformed.
7866 // Or transform (add (mul x, c0), c1) ->
7867 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7868 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7869 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7870 // lead to an infinite loop in DAGCombine if transformed.
7871 // Or transform (add (mul x, c0), c1) ->
7872 //              (mul (add x, c1/c0), c0).
7873 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7874 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7875                                      const RISCVSubtarget &Subtarget) {
7876   // Skip for vector types and larger types.
7877   EVT VT = N->getValueType(0);
7878   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7879     return SDValue();
7880   // The first operand node must be a MUL and has no other use.
7881   SDValue N0 = N->getOperand(0);
7882   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7883     return SDValue();
7884   // Check if c0 and c1 match above conditions.
7885   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7886   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7887   if (!N0C || !N1C)
7888     return SDValue();
7889   // If N0C has multiple uses it's possible one of the cases in
7890   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7891   // in an infinite loop.
7892   if (!N0C->hasOneUse())
7893     return SDValue();
7894   int64_t C0 = N0C->getSExtValue();
7895   int64_t C1 = N1C->getSExtValue();
7896   int64_t CA, CB;
7897   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7898     return SDValue();
7899   // Search for proper CA (non-zero) and CB that both are simm12.
7900   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7901       !isInt<12>(C0 * (C1 / C0))) {
7902     CA = C1 / C0;
7903     CB = C1 % C0;
7904   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7905              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7906     CA = C1 / C0 + 1;
7907     CB = C1 % C0 - C0;
7908   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7909              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7910     CA = C1 / C0 - 1;
7911     CB = C1 % C0 + C0;
7912   } else
7913     return SDValue();
7914   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7915   SDLoc DL(N);
7916   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7917                              DAG.getConstant(CA, DL, VT));
7918   SDValue New1 =
7919       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7920   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7921 }
7922 
7923 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7924                                  const RISCVSubtarget &Subtarget) {
7925   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7926     return V;
7927   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7928     return V;
7929   if (SDValue V = combineBinOpToReduce(N, DAG))
7930     return V;
7931   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7932   //      (select lhs, rhs, cc, x, (add x, y))
7933   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7934 }
7935 
7936 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7937   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7938   //      (select lhs, rhs, cc, x, (sub x, y))
7939   SDValue N0 = N->getOperand(0);
7940   SDValue N1 = N->getOperand(1);
7941   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7942 }
7943 
7944 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
7945                                  const RISCVSubtarget &Subtarget) {
7946   SDValue N0 = N->getOperand(0);
7947   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
7948   // extending X. This is safe since we only need the LSB after the shift and
7949   // shift amounts larger than 31 would produce poison. If we wait until
7950   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
7951   // to use a BEXT instruction.
7952   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
7953       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
7954       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
7955       N0.hasOneUse()) {
7956     SDLoc DL(N);
7957     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
7958     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
7959     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
7960     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
7961                               DAG.getConstant(1, DL, MVT::i64));
7962     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
7963   }
7964 
7965   if (SDValue V = combineBinOpToReduce(N, DAG))
7966     return V;
7967 
7968   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7969   //      (select lhs, rhs, cc, x, (and x, y))
7970   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7971 }
7972 
7973 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7974                                 const RISCVSubtarget &Subtarget) {
7975   if (Subtarget.hasStdExtZbp()) {
7976     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7977       return GREV;
7978     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7979       return GORC;
7980     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7981       return SHFL;
7982   }
7983 
7984   if (SDValue V = combineBinOpToReduce(N, DAG))
7985     return V;
7986   // fold (or (select cond, 0, y), x) ->
7987   //      (select cond, x, (or x, y))
7988   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7989 }
7990 
7991 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7992   SDValue N0 = N->getOperand(0);
7993   SDValue N1 = N->getOperand(1);
7994 
7995   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
7996   // NOTE: Assumes ROL being legal means ROLW is legal.
7997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7998   if (N0.getOpcode() == RISCVISD::SLLW &&
7999       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8000       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8001     SDLoc DL(N);
8002     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8003                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8004   }
8005 
8006   if (SDValue V = combineBinOpToReduce(N, DAG))
8007     return V;
8008   // fold (xor (select cond, 0, y), x) ->
8009   //      (select cond, x, (xor x, y))
8010   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8011 }
8012 
8013 static SDValue
8014 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8015                                 const RISCVSubtarget &Subtarget) {
8016   SDValue Src = N->getOperand(0);
8017   EVT VT = N->getValueType(0);
8018 
8019   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8020   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8021       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8022     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8023                        Src.getOperand(0));
8024 
8025   // Fold (i64 (sext_inreg (abs X), i32)) ->
8026   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8027   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8028   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8029   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8030   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8031   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8032   // may get combined into an earlier operation so we need to use
8033   // ComputeNumSignBits.
8034   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8035   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8036   // we can't assume that X has 33 sign bits. We must check.
8037   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8038       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8039       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8040       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8041     SDLoc DL(N);
8042     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8043     SDValue Neg =
8044         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8045     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8046                       DAG.getValueType(MVT::i32));
8047     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8048   }
8049 
8050   return SDValue();
8051 }
8052 
8053 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8054 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8055 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8056                                              bool Commute = false) {
8057   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8058           N->getOpcode() == RISCVISD::SUB_VL) &&
8059          "Unexpected opcode");
8060   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8061   SDValue Op0 = N->getOperand(0);
8062   SDValue Op1 = N->getOperand(1);
8063   if (Commute)
8064     std::swap(Op0, Op1);
8065 
8066   MVT VT = N->getSimpleValueType(0);
8067 
8068   // Determine the narrow size for a widening add/sub.
8069   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8070   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8071                                   VT.getVectorElementCount());
8072 
8073   SDValue Mask = N->getOperand(2);
8074   SDValue VL = N->getOperand(3);
8075 
8076   SDLoc DL(N);
8077 
8078   // If the RHS is a sext or zext, we can form a widening op.
8079   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8080        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8081       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8082     unsigned ExtOpc = Op1.getOpcode();
8083     Op1 = Op1.getOperand(0);
8084     // Re-introduce narrower extends if needed.
8085     if (Op1.getValueType() != NarrowVT)
8086       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8087 
8088     unsigned WOpc;
8089     if (ExtOpc == RISCVISD::VSEXT_VL)
8090       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8091     else
8092       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8093 
8094     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8095   }
8096 
8097   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8098   // sext/zext?
8099 
8100   return SDValue();
8101 }
8102 
8103 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8104 // vwsub(u).vv/vx.
8105 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8106   SDValue Op0 = N->getOperand(0);
8107   SDValue Op1 = N->getOperand(1);
8108   SDValue Mask = N->getOperand(2);
8109   SDValue VL = N->getOperand(3);
8110 
8111   MVT VT = N->getSimpleValueType(0);
8112   MVT NarrowVT = Op1.getSimpleValueType();
8113   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8114 
8115   unsigned VOpc;
8116   switch (N->getOpcode()) {
8117   default: llvm_unreachable("Unexpected opcode");
8118   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8119   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8120   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8121   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8122   }
8123 
8124   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8125                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8126 
8127   SDLoc DL(N);
8128 
8129   // If the LHS is a sext or zext, we can narrow this op to the same size as
8130   // the RHS.
8131   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8132        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8133       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8134     unsigned ExtOpc = Op0.getOpcode();
8135     Op0 = Op0.getOperand(0);
8136     // Re-introduce narrower extends if needed.
8137     if (Op0.getValueType() != NarrowVT)
8138       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8139     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8140   }
8141 
8142   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8143                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8144 
8145   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8146   // to commute and use a vwadd(u).vx instead.
8147   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8148       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8149     Op0 = Op0.getOperand(1);
8150 
8151     // See if have enough sign bits or zero bits in the scalar to use a
8152     // widening add/sub by splatting to smaller element size.
8153     unsigned EltBits = VT.getScalarSizeInBits();
8154     unsigned ScalarBits = Op0.getValueSizeInBits();
8155     // Make sure we're getting all element bits from the scalar register.
8156     // FIXME: Support implicit sign extension of vmv.v.x?
8157     if (ScalarBits < EltBits)
8158       return SDValue();
8159 
8160     if (IsSigned) {
8161       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8162         return SDValue();
8163     } else {
8164       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8165       if (!DAG.MaskedValueIsZero(Op0, Mask))
8166         return SDValue();
8167     }
8168 
8169     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8170                       DAG.getUNDEF(NarrowVT), Op0, VL);
8171     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8172   }
8173 
8174   return SDValue();
8175 }
8176 
8177 // Try to form VWMUL, VWMULU or VWMULSU.
8178 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8179 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8180                                        bool Commute) {
8181   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8182   SDValue Op0 = N->getOperand(0);
8183   SDValue Op1 = N->getOperand(1);
8184   if (Commute)
8185     std::swap(Op0, Op1);
8186 
8187   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8188   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8189   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8190   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8191     return SDValue();
8192 
8193   SDValue Mask = N->getOperand(2);
8194   SDValue VL = N->getOperand(3);
8195 
8196   // Make sure the mask and VL match.
8197   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8198     return SDValue();
8199 
8200   MVT VT = N->getSimpleValueType(0);
8201 
8202   // Determine the narrow size for a widening multiply.
8203   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8204   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8205                                   VT.getVectorElementCount());
8206 
8207   SDLoc DL(N);
8208 
8209   // See if the other operand is the same opcode.
8210   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8211     if (!Op1.hasOneUse())
8212       return SDValue();
8213 
8214     // Make sure the mask and VL match.
8215     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8216       return SDValue();
8217 
8218     Op1 = Op1.getOperand(0);
8219   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8220     // The operand is a splat of a scalar.
8221 
8222     // The pasthru must be undef for tail agnostic
8223     if (!Op1.getOperand(0).isUndef())
8224       return SDValue();
8225     // The VL must be the same.
8226     if (Op1.getOperand(2) != VL)
8227       return SDValue();
8228 
8229     // Get the scalar value.
8230     Op1 = Op1.getOperand(1);
8231 
8232     // See if have enough sign bits or zero bits in the scalar to use a
8233     // widening multiply by splatting to smaller element size.
8234     unsigned EltBits = VT.getScalarSizeInBits();
8235     unsigned ScalarBits = Op1.getValueSizeInBits();
8236     // Make sure we're getting all element bits from the scalar register.
8237     // FIXME: Support implicit sign extension of vmv.v.x?
8238     if (ScalarBits < EltBits)
8239       return SDValue();
8240 
8241     // If the LHS is a sign extend, try to use vwmul.
8242     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8243       // Can use vwmul.
8244     } else {
8245       // Otherwise try to use vwmulu or vwmulsu.
8246       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8247       if (DAG.MaskedValueIsZero(Op1, Mask))
8248         IsVWMULSU = IsSignExt;
8249       else
8250         return SDValue();
8251     }
8252 
8253     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8254                       DAG.getUNDEF(NarrowVT), Op1, VL);
8255   } else
8256     return SDValue();
8257 
8258   Op0 = Op0.getOperand(0);
8259 
8260   // Re-introduce narrower extends if needed.
8261   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8262   if (Op0.getValueType() != NarrowVT)
8263     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8264   // vwmulsu requires second operand to be zero extended.
8265   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8266   if (Op1.getValueType() != NarrowVT)
8267     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8268 
8269   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8270   if (!IsVWMULSU)
8271     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8272   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8273 }
8274 
8275 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8276   switch (Op.getOpcode()) {
8277   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8278   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8279   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8280   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8281   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8282   }
8283 
8284   return RISCVFPRndMode::Invalid;
8285 }
8286 
8287 // Fold
8288 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8289 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8290 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8291 //   (fp_to_int (fceil X))      -> fcvt X, rup
8292 //   (fp_to_int (fround X))     -> fcvt X, rmm
8293 static SDValue performFP_TO_INTCombine(SDNode *N,
8294                                        TargetLowering::DAGCombinerInfo &DCI,
8295                                        const RISCVSubtarget &Subtarget) {
8296   SelectionDAG &DAG = DCI.DAG;
8297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8298   MVT XLenVT = Subtarget.getXLenVT();
8299 
8300   // Only handle XLen or i32 types. Other types narrower than XLen will
8301   // eventually be legalized to XLenVT.
8302   EVT VT = N->getValueType(0);
8303   if (VT != MVT::i32 && VT != XLenVT)
8304     return SDValue();
8305 
8306   SDValue Src = N->getOperand(0);
8307 
8308   // Ensure the FP type is also legal.
8309   if (!TLI.isTypeLegal(Src.getValueType()))
8310     return SDValue();
8311 
8312   // Don't do this for f16 with Zfhmin and not Zfh.
8313   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8314     return SDValue();
8315 
8316   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8317   if (FRM == RISCVFPRndMode::Invalid)
8318     return SDValue();
8319 
8320   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8321 
8322   unsigned Opc;
8323   if (VT == XLenVT)
8324     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8325   else
8326     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8327 
8328   SDLoc DL(N);
8329   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8330                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8331   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8332 }
8333 
8334 // Fold
8335 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8336 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8337 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8338 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8339 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8340 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8341                                        TargetLowering::DAGCombinerInfo &DCI,
8342                                        const RISCVSubtarget &Subtarget) {
8343   SelectionDAG &DAG = DCI.DAG;
8344   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8345   MVT XLenVT = Subtarget.getXLenVT();
8346 
8347   // Only handle XLen types. Other types narrower than XLen will eventually be
8348   // legalized to XLenVT.
8349   EVT DstVT = N->getValueType(0);
8350   if (DstVT != XLenVT)
8351     return SDValue();
8352 
8353   SDValue Src = N->getOperand(0);
8354 
8355   // Ensure the FP type is also legal.
8356   if (!TLI.isTypeLegal(Src.getValueType()))
8357     return SDValue();
8358 
8359   // Don't do this for f16 with Zfhmin and not Zfh.
8360   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8361     return SDValue();
8362 
8363   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8364 
8365   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8366   if (FRM == RISCVFPRndMode::Invalid)
8367     return SDValue();
8368 
8369   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8370 
8371   unsigned Opc;
8372   if (SatVT == DstVT)
8373     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8374   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8375     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8376   else
8377     return SDValue();
8378   // FIXME: Support other SatVTs by clamping before or after the conversion.
8379 
8380   Src = Src.getOperand(0);
8381 
8382   SDLoc DL(N);
8383   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8384                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8385 
8386   // RISCV FP-to-int conversions saturate to the destination register size, but
8387   // don't produce 0 for nan.
8388   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8389   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8390 }
8391 
8392 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8393 // smaller than XLenVT.
8394 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8395                                         const RISCVSubtarget &Subtarget) {
8396   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8397 
8398   SDValue Src = N->getOperand(0);
8399   if (Src.getOpcode() != ISD::BSWAP)
8400     return SDValue();
8401 
8402   EVT VT = N->getValueType(0);
8403   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8404       !isPowerOf2_32(VT.getSizeInBits()))
8405     return SDValue();
8406 
8407   SDLoc DL(N);
8408   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8409                      DAG.getConstant(7, DL, VT));
8410 }
8411 
8412 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8413                                                DAGCombinerInfo &DCI) const {
8414   SelectionDAG &DAG = DCI.DAG;
8415 
8416   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8417   // bits are demanded. N will be added to the Worklist if it was not deleted.
8418   // Caller should return SDValue(N, 0) if this returns true.
8419   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8420     SDValue Op = N->getOperand(OpNo);
8421     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8422     if (!SimplifyDemandedBits(Op, Mask, DCI))
8423       return false;
8424 
8425     if (N->getOpcode() != ISD::DELETED_NODE)
8426       DCI.AddToWorklist(N);
8427     return true;
8428   };
8429 
8430   switch (N->getOpcode()) {
8431   default:
8432     break;
8433   case RISCVISD::SplitF64: {
8434     SDValue Op0 = N->getOperand(0);
8435     // If the input to SplitF64 is just BuildPairF64 then the operation is
8436     // redundant. Instead, use BuildPairF64's operands directly.
8437     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8438       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8439 
8440     if (Op0->isUndef()) {
8441       SDValue Lo = DAG.getUNDEF(MVT::i32);
8442       SDValue Hi = DAG.getUNDEF(MVT::i32);
8443       return DCI.CombineTo(N, Lo, Hi);
8444     }
8445 
8446     SDLoc DL(N);
8447 
8448     // It's cheaper to materialise two 32-bit integers than to load a double
8449     // from the constant pool and transfer it to integer registers through the
8450     // stack.
8451     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8452       APInt V = C->getValueAPF().bitcastToAPInt();
8453       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8454       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8455       return DCI.CombineTo(N, Lo, Hi);
8456     }
8457 
8458     // This is a target-specific version of a DAGCombine performed in
8459     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8460     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8461     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8462     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8463         !Op0.getNode()->hasOneUse())
8464       break;
8465     SDValue NewSplitF64 =
8466         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8467                     Op0.getOperand(0));
8468     SDValue Lo = NewSplitF64.getValue(0);
8469     SDValue Hi = NewSplitF64.getValue(1);
8470     APInt SignBit = APInt::getSignMask(32);
8471     if (Op0.getOpcode() == ISD::FNEG) {
8472       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8473                                   DAG.getConstant(SignBit, DL, MVT::i32));
8474       return DCI.CombineTo(N, Lo, NewHi);
8475     }
8476     assert(Op0.getOpcode() == ISD::FABS);
8477     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8478                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8479     return DCI.CombineTo(N, Lo, NewHi);
8480   }
8481   case RISCVISD::SLLW:
8482   case RISCVISD::SRAW:
8483   case RISCVISD::SRLW: {
8484     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8485     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8486         SimplifyDemandedLowBitsHelper(1, 5))
8487       return SDValue(N, 0);
8488 
8489     break;
8490   }
8491   case ISD::ROTR:
8492   case ISD::ROTL:
8493   case RISCVISD::RORW:
8494   case RISCVISD::ROLW: {
8495     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8496       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8497       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8498           SimplifyDemandedLowBitsHelper(1, 5))
8499         return SDValue(N, 0);
8500     }
8501 
8502     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8503   }
8504   case RISCVISD::CLZW:
8505   case RISCVISD::CTZW: {
8506     // Only the lower 32 bits of the first operand are read
8507     if (SimplifyDemandedLowBitsHelper(0, 32))
8508       return SDValue(N, 0);
8509     break;
8510   }
8511   case RISCVISD::GREV:
8512   case RISCVISD::GORC: {
8513     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8514     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8515     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8516     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8517       return SDValue(N, 0);
8518 
8519     return combineGREVI_GORCI(N, DAG);
8520   }
8521   case RISCVISD::GREVW:
8522   case RISCVISD::GORCW: {
8523     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8524     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8525         SimplifyDemandedLowBitsHelper(1, 5))
8526       return SDValue(N, 0);
8527 
8528     break;
8529   }
8530   case RISCVISD::SHFL:
8531   case RISCVISD::UNSHFL: {
8532     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8533     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8534     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8535     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8536       return SDValue(N, 0);
8537 
8538     break;
8539   }
8540   case RISCVISD::SHFLW:
8541   case RISCVISD::UNSHFLW: {
8542     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8543     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8544         SimplifyDemandedLowBitsHelper(1, 4))
8545       return SDValue(N, 0);
8546 
8547     break;
8548   }
8549   case RISCVISD::BCOMPRESSW:
8550   case RISCVISD::BDECOMPRESSW: {
8551     // Only the lower 32 bits of LHS and RHS are read.
8552     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8553         SimplifyDemandedLowBitsHelper(1, 32))
8554       return SDValue(N, 0);
8555 
8556     break;
8557   }
8558   case RISCVISD::FSR:
8559   case RISCVISD::FSL:
8560   case RISCVISD::FSRW:
8561   case RISCVISD::FSLW: {
8562     bool IsWInstruction =
8563         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8564     unsigned BitWidth =
8565         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8566     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8567     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8568     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8569       return SDValue(N, 0);
8570 
8571     break;
8572   }
8573   case RISCVISD::FMV_X_ANYEXTH:
8574   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8575     SDLoc DL(N);
8576     SDValue Op0 = N->getOperand(0);
8577     MVT VT = N->getSimpleValueType(0);
8578     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8579     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8580     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8581     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8582          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8583         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8584          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8585       assert(Op0.getOperand(0).getValueType() == VT &&
8586              "Unexpected value type!");
8587       return Op0.getOperand(0);
8588     }
8589 
8590     // This is a target-specific version of a DAGCombine performed in
8591     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8592     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8593     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8594     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8595         !Op0.getNode()->hasOneUse())
8596       break;
8597     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8598     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8599     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8600     if (Op0.getOpcode() == ISD::FNEG)
8601       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8602                          DAG.getConstant(SignBit, DL, VT));
8603 
8604     assert(Op0.getOpcode() == ISD::FABS);
8605     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8606                        DAG.getConstant(~SignBit, DL, VT));
8607   }
8608   case ISD::ADD:
8609     return performADDCombine(N, DAG, Subtarget);
8610   case ISD::SUB:
8611     return performSUBCombine(N, DAG);
8612   case ISD::AND:
8613     return performANDCombine(N, DAG, Subtarget);
8614   case ISD::OR:
8615     return performORCombine(N, DAG, Subtarget);
8616   case ISD::XOR:
8617     return performXORCombine(N, DAG);
8618   case ISD::FADD:
8619   case ISD::UMAX:
8620   case ISD::UMIN:
8621   case ISD::SMAX:
8622   case ISD::SMIN:
8623   case ISD::FMAXNUM:
8624   case ISD::FMINNUM:
8625     return combineBinOpToReduce(N, DAG);
8626   case ISD::SIGN_EXTEND_INREG:
8627     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8628   case ISD::ZERO_EXTEND:
8629     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8630     // type legalization. This is safe because fp_to_uint produces poison if
8631     // it overflows.
8632     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8633       SDValue Src = N->getOperand(0);
8634       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8635           isTypeLegal(Src.getOperand(0).getValueType()))
8636         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8637                            Src.getOperand(0));
8638       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8639           isTypeLegal(Src.getOperand(1).getValueType())) {
8640         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8641         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8642                                   Src.getOperand(0), Src.getOperand(1));
8643         DCI.CombineTo(N, Res);
8644         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8645         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8646         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8647       }
8648     }
8649     return SDValue();
8650   case RISCVISD::SELECT_CC: {
8651     // Transform
8652     SDValue LHS = N->getOperand(0);
8653     SDValue RHS = N->getOperand(1);
8654     SDValue TrueV = N->getOperand(3);
8655     SDValue FalseV = N->getOperand(4);
8656 
8657     // If the True and False values are the same, we don't need a select_cc.
8658     if (TrueV == FalseV)
8659       return TrueV;
8660 
8661     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8662     if (!ISD::isIntEqualitySetCC(CCVal))
8663       break;
8664 
8665     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8666     //      (select_cc X, Y, lt, trueV, falseV)
8667     // Sometimes the setcc is introduced after select_cc has been formed.
8668     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8669         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8670       // If we're looking for eq 0 instead of ne 0, we need to invert the
8671       // condition.
8672       bool Invert = CCVal == ISD::SETEQ;
8673       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8674       if (Invert)
8675         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8676 
8677       SDLoc DL(N);
8678       RHS = LHS.getOperand(1);
8679       LHS = LHS.getOperand(0);
8680       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8681 
8682       SDValue TargetCC = DAG.getCondCode(CCVal);
8683       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8684                          {LHS, RHS, TargetCC, TrueV, FalseV});
8685     }
8686 
8687     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8688     //      (select_cc X, Y, eq/ne, trueV, falseV)
8689     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8690       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8691                          {LHS.getOperand(0), LHS.getOperand(1),
8692                           N->getOperand(2), TrueV, FalseV});
8693     // (select_cc X, 1, setne, trueV, falseV) ->
8694     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8695     // This can occur when legalizing some floating point comparisons.
8696     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8697     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8698       SDLoc DL(N);
8699       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8700       SDValue TargetCC = DAG.getCondCode(CCVal);
8701       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8702       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8703                          {LHS, RHS, TargetCC, TrueV, FalseV});
8704     }
8705 
8706     break;
8707   }
8708   case RISCVISD::BR_CC: {
8709     SDValue LHS = N->getOperand(1);
8710     SDValue RHS = N->getOperand(2);
8711     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8712     if (!ISD::isIntEqualitySetCC(CCVal))
8713       break;
8714 
8715     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8716     //      (br_cc X, Y, lt, dest)
8717     // Sometimes the setcc is introduced after br_cc has been formed.
8718     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8719         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8720       // If we're looking for eq 0 instead of ne 0, we need to invert the
8721       // condition.
8722       bool Invert = CCVal == ISD::SETEQ;
8723       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8724       if (Invert)
8725         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8726 
8727       SDLoc DL(N);
8728       RHS = LHS.getOperand(1);
8729       LHS = LHS.getOperand(0);
8730       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8731 
8732       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8733                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8734                          N->getOperand(4));
8735     }
8736 
8737     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8738     //      (br_cc X, Y, eq/ne, trueV, falseV)
8739     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8740       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8741                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8742                          N->getOperand(3), N->getOperand(4));
8743 
8744     // (br_cc X, 1, setne, br_cc) ->
8745     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8746     // This can occur when legalizing some floating point comparisons.
8747     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8748     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8749       SDLoc DL(N);
8750       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8751       SDValue TargetCC = DAG.getCondCode(CCVal);
8752       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8753       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8754                          N->getOperand(0), LHS, RHS, TargetCC,
8755                          N->getOperand(4));
8756     }
8757     break;
8758   }
8759   case ISD::BITREVERSE:
8760     return performBITREVERSECombine(N, DAG, Subtarget);
8761   case ISD::FP_TO_SINT:
8762   case ISD::FP_TO_UINT:
8763     return performFP_TO_INTCombine(N, DCI, Subtarget);
8764   case ISD::FP_TO_SINT_SAT:
8765   case ISD::FP_TO_UINT_SAT:
8766     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8767   case ISD::FCOPYSIGN: {
8768     EVT VT = N->getValueType(0);
8769     if (!VT.isVector())
8770       break;
8771     // There is a form of VFSGNJ which injects the negated sign of its second
8772     // operand. Try and bubble any FNEG up after the extend/round to produce
8773     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8774     // TRUNC=1.
8775     SDValue In2 = N->getOperand(1);
8776     // Avoid cases where the extend/round has multiple uses, as duplicating
8777     // those is typically more expensive than removing a fneg.
8778     if (!In2.hasOneUse())
8779       break;
8780     if (In2.getOpcode() != ISD::FP_EXTEND &&
8781         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8782       break;
8783     In2 = In2.getOperand(0);
8784     if (In2.getOpcode() != ISD::FNEG)
8785       break;
8786     SDLoc DL(N);
8787     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8788     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8789                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8790   }
8791   case ISD::MGATHER:
8792   case ISD::MSCATTER:
8793   case ISD::VP_GATHER:
8794   case ISD::VP_SCATTER: {
8795     if (!DCI.isBeforeLegalize())
8796       break;
8797     SDValue Index, ScaleOp;
8798     bool IsIndexScaled = false;
8799     bool IsIndexSigned = false;
8800     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8801       Index = VPGSN->getIndex();
8802       ScaleOp = VPGSN->getScale();
8803       IsIndexScaled = VPGSN->isIndexScaled();
8804       IsIndexSigned = VPGSN->isIndexSigned();
8805     } else {
8806       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8807       Index = MGSN->getIndex();
8808       ScaleOp = MGSN->getScale();
8809       IsIndexScaled = MGSN->isIndexScaled();
8810       IsIndexSigned = MGSN->isIndexSigned();
8811     }
8812     EVT IndexVT = Index.getValueType();
8813     MVT XLenVT = Subtarget.getXLenVT();
8814     // RISCV indexed loads only support the "unsigned unscaled" addressing
8815     // mode, so anything else must be manually legalized.
8816     bool NeedsIdxLegalization =
8817         IsIndexScaled ||
8818         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8819     if (!NeedsIdxLegalization)
8820       break;
8821 
8822     SDLoc DL(N);
8823 
8824     // Any index legalization should first promote to XLenVT, so we don't lose
8825     // bits when scaling. This may create an illegal index type so we let
8826     // LLVM's legalization take care of the splitting.
8827     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8828     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8829       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8830       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8831                           DL, IndexVT, Index);
8832     }
8833 
8834     if (IsIndexScaled) {
8835       // Manually scale the indices.
8836       // TODO: Sanitize the scale operand here?
8837       // TODO: For VP nodes, should we use VP_SHL here?
8838       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8839       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8840       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8841       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8842       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
8843     }
8844 
8845     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
8846     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8847       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8848                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8849                               ScaleOp, VPGN->getMask(),
8850                               VPGN->getVectorLength()},
8851                              VPGN->getMemOperand(), NewIndexTy);
8852     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8853       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8854                               {VPSN->getChain(), VPSN->getValue(),
8855                                VPSN->getBasePtr(), Index, ScaleOp,
8856                                VPSN->getMask(), VPSN->getVectorLength()},
8857                               VPSN->getMemOperand(), NewIndexTy);
8858     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8859       return DAG.getMaskedGather(
8860           N->getVTList(), MGN->getMemoryVT(), DL,
8861           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8862            MGN->getBasePtr(), Index, ScaleOp},
8863           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8864     const auto *MSN = cast<MaskedScatterSDNode>(N);
8865     return DAG.getMaskedScatter(
8866         N->getVTList(), MSN->getMemoryVT(), DL,
8867         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8868          Index, ScaleOp},
8869         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8870   }
8871   case RISCVISD::SRA_VL:
8872   case RISCVISD::SRL_VL:
8873   case RISCVISD::SHL_VL: {
8874     SDValue ShAmt = N->getOperand(1);
8875     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8876       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8877       SDLoc DL(N);
8878       SDValue VL = N->getOperand(3);
8879       EVT VT = N->getValueType(0);
8880       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8881                           ShAmt.getOperand(1), VL);
8882       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8883                          N->getOperand(2), N->getOperand(3));
8884     }
8885     break;
8886   }
8887   case ISD::SRA:
8888   case ISD::SRL:
8889   case ISD::SHL: {
8890     SDValue ShAmt = N->getOperand(1);
8891     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8892       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8893       SDLoc DL(N);
8894       EVT VT = N->getValueType(0);
8895       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8896                           ShAmt.getOperand(1),
8897                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8898       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8899     }
8900     break;
8901   }
8902   case RISCVISD::ADD_VL:
8903     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8904       return V;
8905     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8906   case RISCVISD::SUB_VL:
8907     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8908   case RISCVISD::VWADD_W_VL:
8909   case RISCVISD::VWADDU_W_VL:
8910   case RISCVISD::VWSUB_W_VL:
8911   case RISCVISD::VWSUBU_W_VL:
8912     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8913   case RISCVISD::MUL_VL:
8914     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8915       return V;
8916     // Mul is commutative.
8917     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8918   case ISD::STORE: {
8919     auto *Store = cast<StoreSDNode>(N);
8920     SDValue Val = Store->getValue();
8921     // Combine store of vmv.x.s to vse with VL of 1.
8922     // FIXME: Support FP.
8923     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8924       SDValue Src = Val.getOperand(0);
8925       EVT VecVT = Src.getValueType();
8926       EVT MemVT = Store->getMemoryVT();
8927       // The memory VT and the element type must match.
8928       if (VecVT.getVectorElementType() == MemVT) {
8929         SDLoc DL(N);
8930         MVT MaskVT = getMaskTypeFor(VecVT);
8931         return DAG.getStoreVP(
8932             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8933             DAG.getConstant(1, DL, MaskVT),
8934             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8935             Store->getMemOperand(), Store->getAddressingMode(),
8936             Store->isTruncatingStore(), /*IsCompress*/ false);
8937       }
8938     }
8939 
8940     break;
8941   }
8942   case ISD::SPLAT_VECTOR: {
8943     EVT VT = N->getValueType(0);
8944     // Only perform this combine on legal MVT types.
8945     if (!isTypeLegal(VT))
8946       break;
8947     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8948                                          DAG, Subtarget))
8949       return Gather;
8950     break;
8951   }
8952   case RISCVISD::VMV_V_X_VL: {
8953     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8954     // scalar input.
8955     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8956     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8957     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8958       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8959         return SDValue(N, 0);
8960 
8961     break;
8962   }
8963   case ISD::INTRINSIC_WO_CHAIN: {
8964     unsigned IntNo = N->getConstantOperandVal(0);
8965     switch (IntNo) {
8966       // By default we do not combine any intrinsic.
8967     default:
8968       return SDValue();
8969     case Intrinsic::riscv_vcpop:
8970     case Intrinsic::riscv_vcpop_mask:
8971     case Intrinsic::riscv_vfirst:
8972     case Intrinsic::riscv_vfirst_mask: {
8973       SDValue VL = N->getOperand(2);
8974       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8975           IntNo == Intrinsic::riscv_vfirst_mask)
8976         VL = N->getOperand(3);
8977       if (!isNullConstant(VL))
8978         return SDValue();
8979       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8980       SDLoc DL(N);
8981       EVT VT = N->getValueType(0);
8982       if (IntNo == Intrinsic::riscv_vfirst ||
8983           IntNo == Intrinsic::riscv_vfirst_mask)
8984         return DAG.getConstant(-1, DL, VT);
8985       return DAG.getConstant(0, DL, VT);
8986     }
8987     }
8988   }
8989   }
8990 
8991   return SDValue();
8992 }
8993 
8994 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8995     const SDNode *N, CombineLevel Level) const {
8996   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8997   // materialised in fewer instructions than `(OP _, c1)`:
8998   //
8999   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9000   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9001   SDValue N0 = N->getOperand(0);
9002   EVT Ty = N0.getValueType();
9003   if (Ty.isScalarInteger() &&
9004       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9005     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9006     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9007     if (C1 && C2) {
9008       const APInt &C1Int = C1->getAPIntValue();
9009       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9010 
9011       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9012       // and the combine should happen, to potentially allow further combines
9013       // later.
9014       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9015           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9016         return true;
9017 
9018       // We can materialise `c1` in an add immediate, so it's "free", and the
9019       // combine should be prevented.
9020       if (C1Int.getMinSignedBits() <= 64 &&
9021           isLegalAddImmediate(C1Int.getSExtValue()))
9022         return false;
9023 
9024       // Neither constant will fit into an immediate, so find materialisation
9025       // costs.
9026       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9027                                               Subtarget.getFeatureBits(),
9028                                               /*CompressionCost*/true);
9029       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9030           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9031           /*CompressionCost*/true);
9032 
9033       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9034       // combine should be prevented.
9035       if (C1Cost < ShiftedC1Cost)
9036         return false;
9037     }
9038   }
9039   return true;
9040 }
9041 
9042 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9043     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9044     TargetLoweringOpt &TLO) const {
9045   // Delay this optimization as late as possible.
9046   if (!TLO.LegalOps)
9047     return false;
9048 
9049   EVT VT = Op.getValueType();
9050   if (VT.isVector())
9051     return false;
9052 
9053   // Only handle AND for now.
9054   if (Op.getOpcode() != ISD::AND)
9055     return false;
9056 
9057   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9058   if (!C)
9059     return false;
9060 
9061   const APInt &Mask = C->getAPIntValue();
9062 
9063   // Clear all non-demanded bits initially.
9064   APInt ShrunkMask = Mask & DemandedBits;
9065 
9066   // Try to make a smaller immediate by setting undemanded bits.
9067 
9068   APInt ExpandedMask = Mask | ~DemandedBits;
9069 
9070   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9071     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9072   };
9073   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9074     if (NewMask == Mask)
9075       return true;
9076     SDLoc DL(Op);
9077     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9078     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9079     return TLO.CombineTo(Op, NewOp);
9080   };
9081 
9082   // If the shrunk mask fits in sign extended 12 bits, let the target
9083   // independent code apply it.
9084   if (ShrunkMask.isSignedIntN(12))
9085     return false;
9086 
9087   // Preserve (and X, 0xffff) when zext.h is supported.
9088   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9089     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9090     if (IsLegalMask(NewMask))
9091       return UseMask(NewMask);
9092   }
9093 
9094   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9095   if (VT == MVT::i64) {
9096     APInt NewMask = APInt(64, 0xffffffff);
9097     if (IsLegalMask(NewMask))
9098       return UseMask(NewMask);
9099   }
9100 
9101   // For the remaining optimizations, we need to be able to make a negative
9102   // number through a combination of mask and undemanded bits.
9103   if (!ExpandedMask.isNegative())
9104     return false;
9105 
9106   // What is the fewest number of bits we need to represent the negative number.
9107   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9108 
9109   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9110   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9111   APInt NewMask = ShrunkMask;
9112   if (MinSignedBits <= 12)
9113     NewMask.setBitsFrom(11);
9114   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9115     NewMask.setBitsFrom(31);
9116   else
9117     return false;
9118 
9119   // Check that our new mask is a subset of the demanded mask.
9120   assert(IsLegalMask(NewMask));
9121   return UseMask(NewMask);
9122 }
9123 
9124 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9125   static const uint64_t GREVMasks[] = {
9126       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9127       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9128 
9129   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9130     unsigned Shift = 1 << Stage;
9131     if (ShAmt & Shift) {
9132       uint64_t Mask = GREVMasks[Stage];
9133       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9134       if (IsGORC)
9135         Res |= x;
9136       x = Res;
9137     }
9138   }
9139 
9140   return x;
9141 }
9142 
9143 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9144                                                         KnownBits &Known,
9145                                                         const APInt &DemandedElts,
9146                                                         const SelectionDAG &DAG,
9147                                                         unsigned Depth) const {
9148   unsigned BitWidth = Known.getBitWidth();
9149   unsigned Opc = Op.getOpcode();
9150   assert((Opc >= ISD::BUILTIN_OP_END ||
9151           Opc == ISD::INTRINSIC_WO_CHAIN ||
9152           Opc == ISD::INTRINSIC_W_CHAIN ||
9153           Opc == ISD::INTRINSIC_VOID) &&
9154          "Should use MaskedValueIsZero if you don't know whether Op"
9155          " is a target node!");
9156 
9157   Known.resetAll();
9158   switch (Opc) {
9159   default: break;
9160   case RISCVISD::SELECT_CC: {
9161     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9162     // If we don't know any bits, early out.
9163     if (Known.isUnknown())
9164       break;
9165     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9166 
9167     // Only known if known in both the LHS and RHS.
9168     Known = KnownBits::commonBits(Known, Known2);
9169     break;
9170   }
9171   case RISCVISD::REMUW: {
9172     KnownBits Known2;
9173     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9174     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9175     // We only care about the lower 32 bits.
9176     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9177     // Restore the original width by sign extending.
9178     Known = Known.sext(BitWidth);
9179     break;
9180   }
9181   case RISCVISD::DIVUW: {
9182     KnownBits Known2;
9183     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9184     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9185     // We only care about the lower 32 bits.
9186     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9187     // Restore the original width by sign extending.
9188     Known = Known.sext(BitWidth);
9189     break;
9190   }
9191   case RISCVISD::CTZW: {
9192     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9193     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9194     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9195     Known.Zero.setBitsFrom(LowBits);
9196     break;
9197   }
9198   case RISCVISD::CLZW: {
9199     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9200     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9201     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9202     Known.Zero.setBitsFrom(LowBits);
9203     break;
9204   }
9205   case RISCVISD::GREV:
9206   case RISCVISD::GORC: {
9207     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9208       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9209       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9210       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9211       // To compute zeros, we need to invert the value and invert it back after.
9212       Known.Zero =
9213           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9214       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9215     }
9216     break;
9217   }
9218   case RISCVISD::READ_VLENB: {
9219     // If we know the minimum VLen from Zvl extensions, we can use that to
9220     // determine the trailing zeros of VLENB.
9221     // FIXME: Limit to 128 bit vectors until we have more testing.
9222     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9223     if (MinVLenB > 0)
9224       Known.Zero.setLowBits(Log2_32(MinVLenB));
9225     // We assume VLENB is no more than 65536 / 8 bytes.
9226     Known.Zero.setBitsFrom(14);
9227     break;
9228   }
9229   case ISD::INTRINSIC_W_CHAIN:
9230   case ISD::INTRINSIC_WO_CHAIN: {
9231     unsigned IntNo =
9232         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9233     switch (IntNo) {
9234     default:
9235       // We can't do anything for most intrinsics.
9236       break;
9237     case Intrinsic::riscv_vsetvli:
9238     case Intrinsic::riscv_vsetvlimax:
9239     case Intrinsic::riscv_vsetvli_opt:
9240     case Intrinsic::riscv_vsetvlimax_opt:
9241       // Assume that VL output is positive and would fit in an int32_t.
9242       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9243       if (BitWidth >= 32)
9244         Known.Zero.setBitsFrom(31);
9245       break;
9246     }
9247     break;
9248   }
9249   }
9250 }
9251 
9252 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9253     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9254     unsigned Depth) const {
9255   switch (Op.getOpcode()) {
9256   default:
9257     break;
9258   case RISCVISD::SELECT_CC: {
9259     unsigned Tmp =
9260         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9261     if (Tmp == 1) return 1;  // Early out.
9262     unsigned Tmp2 =
9263         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9264     return std::min(Tmp, Tmp2);
9265   }
9266   case RISCVISD::SLLW:
9267   case RISCVISD::SRAW:
9268   case RISCVISD::SRLW:
9269   case RISCVISD::DIVW:
9270   case RISCVISD::DIVUW:
9271   case RISCVISD::REMUW:
9272   case RISCVISD::ROLW:
9273   case RISCVISD::RORW:
9274   case RISCVISD::GREVW:
9275   case RISCVISD::GORCW:
9276   case RISCVISD::FSLW:
9277   case RISCVISD::FSRW:
9278   case RISCVISD::SHFLW:
9279   case RISCVISD::UNSHFLW:
9280   case RISCVISD::BCOMPRESSW:
9281   case RISCVISD::BDECOMPRESSW:
9282   case RISCVISD::BFPW:
9283   case RISCVISD::FCVT_W_RV64:
9284   case RISCVISD::FCVT_WU_RV64:
9285   case RISCVISD::STRICT_FCVT_W_RV64:
9286   case RISCVISD::STRICT_FCVT_WU_RV64:
9287     // TODO: As the result is sign-extended, this is conservatively correct. A
9288     // more precise answer could be calculated for SRAW depending on known
9289     // bits in the shift amount.
9290     return 33;
9291   case RISCVISD::SHFL:
9292   case RISCVISD::UNSHFL: {
9293     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9294     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9295     // will stay within the upper 32 bits. If there were more than 32 sign bits
9296     // before there will be at least 33 sign bits after.
9297     if (Op.getValueType() == MVT::i64 &&
9298         isa<ConstantSDNode>(Op.getOperand(1)) &&
9299         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9300       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9301       if (Tmp > 32)
9302         return 33;
9303     }
9304     break;
9305   }
9306   case RISCVISD::VMV_X_S: {
9307     // The number of sign bits of the scalar result is computed by obtaining the
9308     // element type of the input vector operand, subtracting its width from the
9309     // XLEN, and then adding one (sign bit within the element type). If the
9310     // element type is wider than XLen, the least-significant XLEN bits are
9311     // taken.
9312     unsigned XLen = Subtarget.getXLen();
9313     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9314     if (EltBits <= XLen)
9315       return XLen - EltBits + 1;
9316     break;
9317   }
9318   }
9319 
9320   return 1;
9321 }
9322 
9323 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9324                                                   MachineBasicBlock *BB) {
9325   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9326 
9327   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9328   // Should the count have wrapped while it was being read, we need to try
9329   // again.
9330   // ...
9331   // read:
9332   // rdcycleh x3 # load high word of cycle
9333   // rdcycle  x2 # load low word of cycle
9334   // rdcycleh x4 # load high word of cycle
9335   // bne x3, x4, read # check if high word reads match, otherwise try again
9336   // ...
9337 
9338   MachineFunction &MF = *BB->getParent();
9339   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9340   MachineFunction::iterator It = ++BB->getIterator();
9341 
9342   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9343   MF.insert(It, LoopMBB);
9344 
9345   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9346   MF.insert(It, DoneMBB);
9347 
9348   // Transfer the remainder of BB and its successor edges to DoneMBB.
9349   DoneMBB->splice(DoneMBB->begin(), BB,
9350                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9351   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9352 
9353   BB->addSuccessor(LoopMBB);
9354 
9355   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9356   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9357   Register LoReg = MI.getOperand(0).getReg();
9358   Register HiReg = MI.getOperand(1).getReg();
9359   DebugLoc DL = MI.getDebugLoc();
9360 
9361   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9362   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9363       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9364       .addReg(RISCV::X0);
9365   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9366       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9367       .addReg(RISCV::X0);
9368   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9369       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9370       .addReg(RISCV::X0);
9371 
9372   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9373       .addReg(HiReg)
9374       .addReg(ReadAgainReg)
9375       .addMBB(LoopMBB);
9376 
9377   LoopMBB->addSuccessor(LoopMBB);
9378   LoopMBB->addSuccessor(DoneMBB);
9379 
9380   MI.eraseFromParent();
9381 
9382   return DoneMBB;
9383 }
9384 
9385 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9386                                              MachineBasicBlock *BB) {
9387   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9388 
9389   MachineFunction &MF = *BB->getParent();
9390   DebugLoc DL = MI.getDebugLoc();
9391   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9392   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9393   Register LoReg = MI.getOperand(0).getReg();
9394   Register HiReg = MI.getOperand(1).getReg();
9395   Register SrcReg = MI.getOperand(2).getReg();
9396   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9397   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9398 
9399   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9400                           RI);
9401   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9402   MachineMemOperand *MMOLo =
9403       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9404   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9405       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9406   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9407       .addFrameIndex(FI)
9408       .addImm(0)
9409       .addMemOperand(MMOLo);
9410   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9411       .addFrameIndex(FI)
9412       .addImm(4)
9413       .addMemOperand(MMOHi);
9414   MI.eraseFromParent(); // The pseudo instruction is gone now.
9415   return BB;
9416 }
9417 
9418 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9419                                                  MachineBasicBlock *BB) {
9420   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9421          "Unexpected instruction");
9422 
9423   MachineFunction &MF = *BB->getParent();
9424   DebugLoc DL = MI.getDebugLoc();
9425   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9426   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9427   Register DstReg = MI.getOperand(0).getReg();
9428   Register LoReg = MI.getOperand(1).getReg();
9429   Register HiReg = MI.getOperand(2).getReg();
9430   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9431   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9432 
9433   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9434   MachineMemOperand *MMOLo =
9435       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9436   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9437       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9438   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9439       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9440       .addFrameIndex(FI)
9441       .addImm(0)
9442       .addMemOperand(MMOLo);
9443   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9444       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9445       .addFrameIndex(FI)
9446       .addImm(4)
9447       .addMemOperand(MMOHi);
9448   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9449   MI.eraseFromParent(); // The pseudo instruction is gone now.
9450   return BB;
9451 }
9452 
9453 static bool isSelectPseudo(MachineInstr &MI) {
9454   switch (MI.getOpcode()) {
9455   default:
9456     return false;
9457   case RISCV::Select_GPR_Using_CC_GPR:
9458   case RISCV::Select_FPR16_Using_CC_GPR:
9459   case RISCV::Select_FPR32_Using_CC_GPR:
9460   case RISCV::Select_FPR64_Using_CC_GPR:
9461     return true;
9462   }
9463 }
9464 
9465 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9466                                         unsigned RelOpcode, unsigned EqOpcode,
9467                                         const RISCVSubtarget &Subtarget) {
9468   DebugLoc DL = MI.getDebugLoc();
9469   Register DstReg = MI.getOperand(0).getReg();
9470   Register Src1Reg = MI.getOperand(1).getReg();
9471   Register Src2Reg = MI.getOperand(2).getReg();
9472   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9473   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9474   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9475 
9476   // Save the current FFLAGS.
9477   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9478 
9479   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9480                  .addReg(Src1Reg)
9481                  .addReg(Src2Reg);
9482   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9483     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9484 
9485   // Restore the FFLAGS.
9486   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9487       .addReg(SavedFFlags, RegState::Kill);
9488 
9489   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9490   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9491                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9492                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9493   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9494     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9495 
9496   // Erase the pseudoinstruction.
9497   MI.eraseFromParent();
9498   return BB;
9499 }
9500 
9501 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9502                                            MachineBasicBlock *BB,
9503                                            const RISCVSubtarget &Subtarget) {
9504   // To "insert" Select_* instructions, we actually have to insert the triangle
9505   // control-flow pattern.  The incoming instructions know the destination vreg
9506   // to set, the condition code register to branch on, the true/false values to
9507   // select between, and the condcode to use to select the appropriate branch.
9508   //
9509   // We produce the following control flow:
9510   //     HeadMBB
9511   //     |  \
9512   //     |  IfFalseMBB
9513   //     | /
9514   //    TailMBB
9515   //
9516   // When we find a sequence of selects we attempt to optimize their emission
9517   // by sharing the control flow. Currently we only handle cases where we have
9518   // multiple selects with the exact same condition (same LHS, RHS and CC).
9519   // The selects may be interleaved with other instructions if the other
9520   // instructions meet some requirements we deem safe:
9521   // - They are debug instructions. Otherwise,
9522   // - They do not have side-effects, do not access memory and their inputs do
9523   //   not depend on the results of the select pseudo-instructions.
9524   // The TrueV/FalseV operands of the selects cannot depend on the result of
9525   // previous selects in the sequence.
9526   // These conditions could be further relaxed. See the X86 target for a
9527   // related approach and more information.
9528   Register LHS = MI.getOperand(1).getReg();
9529   Register RHS = MI.getOperand(2).getReg();
9530   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9531 
9532   SmallVector<MachineInstr *, 4> SelectDebugValues;
9533   SmallSet<Register, 4> SelectDests;
9534   SelectDests.insert(MI.getOperand(0).getReg());
9535 
9536   MachineInstr *LastSelectPseudo = &MI;
9537 
9538   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9539        SequenceMBBI != E; ++SequenceMBBI) {
9540     if (SequenceMBBI->isDebugInstr())
9541       continue;
9542     if (isSelectPseudo(*SequenceMBBI)) {
9543       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9544           SequenceMBBI->getOperand(2).getReg() != RHS ||
9545           SequenceMBBI->getOperand(3).getImm() != CC ||
9546           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9547           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9548         break;
9549       LastSelectPseudo = &*SequenceMBBI;
9550       SequenceMBBI->collectDebugValues(SelectDebugValues);
9551       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9552     } else {
9553       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9554           SequenceMBBI->mayLoadOrStore())
9555         break;
9556       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9557             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9558           }))
9559         break;
9560     }
9561   }
9562 
9563   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9564   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9565   DebugLoc DL = MI.getDebugLoc();
9566   MachineFunction::iterator I = ++BB->getIterator();
9567 
9568   MachineBasicBlock *HeadMBB = BB;
9569   MachineFunction *F = BB->getParent();
9570   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9571   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9572 
9573   F->insert(I, IfFalseMBB);
9574   F->insert(I, TailMBB);
9575 
9576   // Transfer debug instructions associated with the selects to TailMBB.
9577   for (MachineInstr *DebugInstr : SelectDebugValues) {
9578     TailMBB->push_back(DebugInstr->removeFromParent());
9579   }
9580 
9581   // Move all instructions after the sequence to TailMBB.
9582   TailMBB->splice(TailMBB->end(), HeadMBB,
9583                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9584   // Update machine-CFG edges by transferring all successors of the current
9585   // block to the new block which will contain the Phi nodes for the selects.
9586   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9587   // Set the successors for HeadMBB.
9588   HeadMBB->addSuccessor(IfFalseMBB);
9589   HeadMBB->addSuccessor(TailMBB);
9590 
9591   // Insert appropriate branch.
9592   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9593     .addReg(LHS)
9594     .addReg(RHS)
9595     .addMBB(TailMBB);
9596 
9597   // IfFalseMBB just falls through to TailMBB.
9598   IfFalseMBB->addSuccessor(TailMBB);
9599 
9600   // Create PHIs for all of the select pseudo-instructions.
9601   auto SelectMBBI = MI.getIterator();
9602   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9603   auto InsertionPoint = TailMBB->begin();
9604   while (SelectMBBI != SelectEnd) {
9605     auto Next = std::next(SelectMBBI);
9606     if (isSelectPseudo(*SelectMBBI)) {
9607       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9608       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9609               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9610           .addReg(SelectMBBI->getOperand(4).getReg())
9611           .addMBB(HeadMBB)
9612           .addReg(SelectMBBI->getOperand(5).getReg())
9613           .addMBB(IfFalseMBB);
9614       SelectMBBI->eraseFromParent();
9615     }
9616     SelectMBBI = Next;
9617   }
9618 
9619   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9620   return TailMBB;
9621 }
9622 
9623 MachineBasicBlock *
9624 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9625                                                  MachineBasicBlock *BB) const {
9626   switch (MI.getOpcode()) {
9627   default:
9628     llvm_unreachable("Unexpected instr type to insert");
9629   case RISCV::ReadCycleWide:
9630     assert(!Subtarget.is64Bit() &&
9631            "ReadCycleWrite is only to be used on riscv32");
9632     return emitReadCycleWidePseudo(MI, BB);
9633   case RISCV::Select_GPR_Using_CC_GPR:
9634   case RISCV::Select_FPR16_Using_CC_GPR:
9635   case RISCV::Select_FPR32_Using_CC_GPR:
9636   case RISCV::Select_FPR64_Using_CC_GPR:
9637     return emitSelectPseudo(MI, BB, Subtarget);
9638   case RISCV::BuildPairF64Pseudo:
9639     return emitBuildPairF64Pseudo(MI, BB);
9640   case RISCV::SplitF64Pseudo:
9641     return emitSplitF64Pseudo(MI, BB);
9642   case RISCV::PseudoQuietFLE_H:
9643     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9644   case RISCV::PseudoQuietFLT_H:
9645     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9646   case RISCV::PseudoQuietFLE_S:
9647     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9648   case RISCV::PseudoQuietFLT_S:
9649     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9650   case RISCV::PseudoQuietFLE_D:
9651     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9652   case RISCV::PseudoQuietFLT_D:
9653     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9654   }
9655 }
9656 
9657 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9658                                                         SDNode *Node) const {
9659   // Add FRM dependency to any instructions with dynamic rounding mode.
9660   unsigned Opc = MI.getOpcode();
9661   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9662   if (Idx < 0)
9663     return;
9664   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9665     return;
9666   // If the instruction already reads FRM, don't add another read.
9667   if (MI.readsRegister(RISCV::FRM))
9668     return;
9669   MI.addOperand(
9670       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9671 }
9672 
9673 // Calling Convention Implementation.
9674 // The expectations for frontend ABI lowering vary from target to target.
9675 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9676 // details, but this is a longer term goal. For now, we simply try to keep the
9677 // role of the frontend as simple and well-defined as possible. The rules can
9678 // be summarised as:
9679 // * Never split up large scalar arguments. We handle them here.
9680 // * If a hardfloat calling convention is being used, and the struct may be
9681 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9682 // available, then pass as two separate arguments. If either the GPRs or FPRs
9683 // are exhausted, then pass according to the rule below.
9684 // * If a struct could never be passed in registers or directly in a stack
9685 // slot (as it is larger than 2*XLEN and the floating point rules don't
9686 // apply), then pass it using a pointer with the byval attribute.
9687 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9688 // word-sized array or a 2*XLEN scalar (depending on alignment).
9689 // * The frontend can determine whether a struct is returned by reference or
9690 // not based on its size and fields. If it will be returned by reference, the
9691 // frontend must modify the prototype so a pointer with the sret annotation is
9692 // passed as the first argument. This is not necessary for large scalar
9693 // returns.
9694 // * Struct return values and varargs should be coerced to structs containing
9695 // register-size fields in the same situations they would be for fixed
9696 // arguments.
9697 
9698 static const MCPhysReg ArgGPRs[] = {
9699   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9700   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9701 };
9702 static const MCPhysReg ArgFPR16s[] = {
9703   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9704   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9705 };
9706 static const MCPhysReg ArgFPR32s[] = {
9707   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9708   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9709 };
9710 static const MCPhysReg ArgFPR64s[] = {
9711   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9712   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9713 };
9714 // This is an interim calling convention and it may be changed in the future.
9715 static const MCPhysReg ArgVRs[] = {
9716     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9717     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9718     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9719 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9720                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9721                                      RISCV::V20M2, RISCV::V22M2};
9722 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9723                                      RISCV::V20M4};
9724 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9725 
9726 // Pass a 2*XLEN argument that has been split into two XLEN values through
9727 // registers or the stack as necessary.
9728 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9729                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9730                                 MVT ValVT2, MVT LocVT2,
9731                                 ISD::ArgFlagsTy ArgFlags2) {
9732   unsigned XLenInBytes = XLen / 8;
9733   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9734     // At least one half can be passed via register.
9735     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9736                                      VA1.getLocVT(), CCValAssign::Full));
9737   } else {
9738     // Both halves must be passed on the stack, with proper alignment.
9739     Align StackAlign =
9740         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9741     State.addLoc(
9742         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9743                             State.AllocateStack(XLenInBytes, StackAlign),
9744                             VA1.getLocVT(), CCValAssign::Full));
9745     State.addLoc(CCValAssign::getMem(
9746         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9747         LocVT2, CCValAssign::Full));
9748     return false;
9749   }
9750 
9751   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9752     // The second half can also be passed via register.
9753     State.addLoc(
9754         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9755   } else {
9756     // The second half is passed via the stack, without additional alignment.
9757     State.addLoc(CCValAssign::getMem(
9758         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9759         LocVT2, CCValAssign::Full));
9760   }
9761 
9762   return false;
9763 }
9764 
9765 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9766                                Optional<unsigned> FirstMaskArgument,
9767                                CCState &State, const RISCVTargetLowering &TLI) {
9768   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9769   if (RC == &RISCV::VRRegClass) {
9770     // Assign the first mask argument to V0.
9771     // This is an interim calling convention and it may be changed in the
9772     // future.
9773     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9774       return State.AllocateReg(RISCV::V0);
9775     return State.AllocateReg(ArgVRs);
9776   }
9777   if (RC == &RISCV::VRM2RegClass)
9778     return State.AllocateReg(ArgVRM2s);
9779   if (RC == &RISCV::VRM4RegClass)
9780     return State.AllocateReg(ArgVRM4s);
9781   if (RC == &RISCV::VRM8RegClass)
9782     return State.AllocateReg(ArgVRM8s);
9783   llvm_unreachable("Unhandled register class for ValueType");
9784 }
9785 
9786 // Implements the RISC-V calling convention. Returns true upon failure.
9787 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9788                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9789                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9790                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9791                      Optional<unsigned> FirstMaskArgument) {
9792   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9793   assert(XLen == 32 || XLen == 64);
9794   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9795 
9796   // Any return value split in to more than two values can't be returned
9797   // directly. Vectors are returned via the available vector registers.
9798   if (!LocVT.isVector() && IsRet && ValNo > 1)
9799     return true;
9800 
9801   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9802   // variadic argument, or if no F16/F32 argument registers are available.
9803   bool UseGPRForF16_F32 = true;
9804   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9805   // variadic argument, or if no F64 argument registers are available.
9806   bool UseGPRForF64 = true;
9807 
9808   switch (ABI) {
9809   default:
9810     llvm_unreachable("Unexpected ABI");
9811   case RISCVABI::ABI_ILP32:
9812   case RISCVABI::ABI_LP64:
9813     break;
9814   case RISCVABI::ABI_ILP32F:
9815   case RISCVABI::ABI_LP64F:
9816     UseGPRForF16_F32 = !IsFixed;
9817     break;
9818   case RISCVABI::ABI_ILP32D:
9819   case RISCVABI::ABI_LP64D:
9820     UseGPRForF16_F32 = !IsFixed;
9821     UseGPRForF64 = !IsFixed;
9822     break;
9823   }
9824 
9825   // FPR16, FPR32, and FPR64 alias each other.
9826   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9827     UseGPRForF16_F32 = true;
9828     UseGPRForF64 = true;
9829   }
9830 
9831   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9832   // similar local variables rather than directly checking against the target
9833   // ABI.
9834 
9835   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9836     LocVT = XLenVT;
9837     LocInfo = CCValAssign::BCvt;
9838   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9839     LocVT = MVT::i64;
9840     LocInfo = CCValAssign::BCvt;
9841   }
9842 
9843   // If this is a variadic argument, the RISC-V calling convention requires
9844   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9845   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9846   // be used regardless of whether the original argument was split during
9847   // legalisation or not. The argument will not be passed by registers if the
9848   // original type is larger than 2*XLEN, so the register alignment rule does
9849   // not apply.
9850   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9851   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9852       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9853     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9854     // Skip 'odd' register if necessary.
9855     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9856       State.AllocateReg(ArgGPRs);
9857   }
9858 
9859   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9860   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9861       State.getPendingArgFlags();
9862 
9863   assert(PendingLocs.size() == PendingArgFlags.size() &&
9864          "PendingLocs and PendingArgFlags out of sync");
9865 
9866   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9867   // registers are exhausted.
9868   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9869     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9870            "Can't lower f64 if it is split");
9871     // Depending on available argument GPRS, f64 may be passed in a pair of
9872     // GPRs, split between a GPR and the stack, or passed completely on the
9873     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9874     // cases.
9875     Register Reg = State.AllocateReg(ArgGPRs);
9876     LocVT = MVT::i32;
9877     if (!Reg) {
9878       unsigned StackOffset = State.AllocateStack(8, Align(8));
9879       State.addLoc(
9880           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9881       return false;
9882     }
9883     if (!State.AllocateReg(ArgGPRs))
9884       State.AllocateStack(4, Align(4));
9885     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9886     return false;
9887   }
9888 
9889   // Fixed-length vectors are located in the corresponding scalable-vector
9890   // container types.
9891   if (ValVT.isFixedLengthVector())
9892     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9893 
9894   // Split arguments might be passed indirectly, so keep track of the pending
9895   // values. Split vectors are passed via a mix of registers and indirectly, so
9896   // treat them as we would any other argument.
9897   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9898     LocVT = XLenVT;
9899     LocInfo = CCValAssign::Indirect;
9900     PendingLocs.push_back(
9901         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9902     PendingArgFlags.push_back(ArgFlags);
9903     if (!ArgFlags.isSplitEnd()) {
9904       return false;
9905     }
9906   }
9907 
9908   // If the split argument only had two elements, it should be passed directly
9909   // in registers or on the stack.
9910   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9911       PendingLocs.size() <= 2) {
9912     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9913     // Apply the normal calling convention rules to the first half of the
9914     // split argument.
9915     CCValAssign VA = PendingLocs[0];
9916     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9917     PendingLocs.clear();
9918     PendingArgFlags.clear();
9919     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9920                                ArgFlags);
9921   }
9922 
9923   // Allocate to a register if possible, or else a stack slot.
9924   Register Reg;
9925   unsigned StoreSizeBytes = XLen / 8;
9926   Align StackAlign = Align(XLen / 8);
9927 
9928   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9929     Reg = State.AllocateReg(ArgFPR16s);
9930   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9931     Reg = State.AllocateReg(ArgFPR32s);
9932   else if (ValVT == MVT::f64 && !UseGPRForF64)
9933     Reg = State.AllocateReg(ArgFPR64s);
9934   else if (ValVT.isVector()) {
9935     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9936     if (!Reg) {
9937       // For return values, the vector must be passed fully via registers or
9938       // via the stack.
9939       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9940       // but we're using all of them.
9941       if (IsRet)
9942         return true;
9943       // Try using a GPR to pass the address
9944       if ((Reg = State.AllocateReg(ArgGPRs))) {
9945         LocVT = XLenVT;
9946         LocInfo = CCValAssign::Indirect;
9947       } else if (ValVT.isScalableVector()) {
9948         LocVT = XLenVT;
9949         LocInfo = CCValAssign::Indirect;
9950       } else {
9951         // Pass fixed-length vectors on the stack.
9952         LocVT = ValVT;
9953         StoreSizeBytes = ValVT.getStoreSize();
9954         // Align vectors to their element sizes, being careful for vXi1
9955         // vectors.
9956         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9957       }
9958     }
9959   } else {
9960     Reg = State.AllocateReg(ArgGPRs);
9961   }
9962 
9963   unsigned StackOffset =
9964       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9965 
9966   // If we reach this point and PendingLocs is non-empty, we must be at the
9967   // end of a split argument that must be passed indirectly.
9968   if (!PendingLocs.empty()) {
9969     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9970     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9971 
9972     for (auto &It : PendingLocs) {
9973       if (Reg)
9974         It.convertToReg(Reg);
9975       else
9976         It.convertToMem(StackOffset);
9977       State.addLoc(It);
9978     }
9979     PendingLocs.clear();
9980     PendingArgFlags.clear();
9981     return false;
9982   }
9983 
9984   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9985           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9986          "Expected an XLenVT or vector types at this stage");
9987 
9988   if (Reg) {
9989     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9990     return false;
9991   }
9992 
9993   // When a floating-point value is passed on the stack, no bit-conversion is
9994   // needed.
9995   if (ValVT.isFloatingPoint()) {
9996     LocVT = ValVT;
9997     LocInfo = CCValAssign::Full;
9998   }
9999   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10000   return false;
10001 }
10002 
10003 template <typename ArgTy>
10004 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10005   for (const auto &ArgIdx : enumerate(Args)) {
10006     MVT ArgVT = ArgIdx.value().VT;
10007     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10008       return ArgIdx.index();
10009   }
10010   return None;
10011 }
10012 
10013 void RISCVTargetLowering::analyzeInputArgs(
10014     MachineFunction &MF, CCState &CCInfo,
10015     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10016     RISCVCCAssignFn Fn) const {
10017   unsigned NumArgs = Ins.size();
10018   FunctionType *FType = MF.getFunction().getFunctionType();
10019 
10020   Optional<unsigned> FirstMaskArgument;
10021   if (Subtarget.hasVInstructions())
10022     FirstMaskArgument = preAssignMask(Ins);
10023 
10024   for (unsigned i = 0; i != NumArgs; ++i) {
10025     MVT ArgVT = Ins[i].VT;
10026     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10027 
10028     Type *ArgTy = nullptr;
10029     if (IsRet)
10030       ArgTy = FType->getReturnType();
10031     else if (Ins[i].isOrigArg())
10032       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10033 
10034     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10035     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10036            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10037            FirstMaskArgument)) {
10038       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10039                         << EVT(ArgVT).getEVTString() << '\n');
10040       llvm_unreachable(nullptr);
10041     }
10042   }
10043 }
10044 
10045 void RISCVTargetLowering::analyzeOutputArgs(
10046     MachineFunction &MF, CCState &CCInfo,
10047     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10048     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10049   unsigned NumArgs = Outs.size();
10050 
10051   Optional<unsigned> FirstMaskArgument;
10052   if (Subtarget.hasVInstructions())
10053     FirstMaskArgument = preAssignMask(Outs);
10054 
10055   for (unsigned i = 0; i != NumArgs; i++) {
10056     MVT ArgVT = Outs[i].VT;
10057     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10058     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10059 
10060     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10061     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10062            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10063            FirstMaskArgument)) {
10064       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10065                         << EVT(ArgVT).getEVTString() << "\n");
10066       llvm_unreachable(nullptr);
10067     }
10068   }
10069 }
10070 
10071 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10072 // values.
10073 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10074                                    const CCValAssign &VA, const SDLoc &DL,
10075                                    const RISCVSubtarget &Subtarget) {
10076   switch (VA.getLocInfo()) {
10077   default:
10078     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10079   case CCValAssign::Full:
10080     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10081       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10082     break;
10083   case CCValAssign::BCvt:
10084     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10085       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10086     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10087       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10088     else
10089       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10090     break;
10091   }
10092   return Val;
10093 }
10094 
10095 // The caller is responsible for loading the full value if the argument is
10096 // passed with CCValAssign::Indirect.
10097 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10098                                 const CCValAssign &VA, const SDLoc &DL,
10099                                 const RISCVTargetLowering &TLI) {
10100   MachineFunction &MF = DAG.getMachineFunction();
10101   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10102   EVT LocVT = VA.getLocVT();
10103   SDValue Val;
10104   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10105   Register VReg = RegInfo.createVirtualRegister(RC);
10106   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10107   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10108 
10109   if (VA.getLocInfo() == CCValAssign::Indirect)
10110     return Val;
10111 
10112   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10113 }
10114 
10115 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10116                                    const CCValAssign &VA, const SDLoc &DL,
10117                                    const RISCVSubtarget &Subtarget) {
10118   EVT LocVT = VA.getLocVT();
10119 
10120   switch (VA.getLocInfo()) {
10121   default:
10122     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10123   case CCValAssign::Full:
10124     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10125       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10126     break;
10127   case CCValAssign::BCvt:
10128     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10129       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10130     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10131       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10132     else
10133       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10134     break;
10135   }
10136   return Val;
10137 }
10138 
10139 // The caller is responsible for loading the full value if the argument is
10140 // passed with CCValAssign::Indirect.
10141 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10142                                 const CCValAssign &VA, const SDLoc &DL) {
10143   MachineFunction &MF = DAG.getMachineFunction();
10144   MachineFrameInfo &MFI = MF.getFrameInfo();
10145   EVT LocVT = VA.getLocVT();
10146   EVT ValVT = VA.getValVT();
10147   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10148   if (ValVT.isScalableVector()) {
10149     // When the value is a scalable vector, we save the pointer which points to
10150     // the scalable vector value in the stack. The ValVT will be the pointer
10151     // type, instead of the scalable vector type.
10152     ValVT = LocVT;
10153   }
10154   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10155                                  /*IsImmutable=*/true);
10156   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10157   SDValue Val;
10158 
10159   ISD::LoadExtType ExtType;
10160   switch (VA.getLocInfo()) {
10161   default:
10162     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10163   case CCValAssign::Full:
10164   case CCValAssign::Indirect:
10165   case CCValAssign::BCvt:
10166     ExtType = ISD::NON_EXTLOAD;
10167     break;
10168   }
10169   Val = DAG.getExtLoad(
10170       ExtType, DL, LocVT, Chain, FIN,
10171       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10172   return Val;
10173 }
10174 
10175 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10176                                        const CCValAssign &VA, const SDLoc &DL) {
10177   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10178          "Unexpected VA");
10179   MachineFunction &MF = DAG.getMachineFunction();
10180   MachineFrameInfo &MFI = MF.getFrameInfo();
10181   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10182 
10183   if (VA.isMemLoc()) {
10184     // f64 is passed on the stack.
10185     int FI =
10186         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10187     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10188     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10189                        MachinePointerInfo::getFixedStack(MF, FI));
10190   }
10191 
10192   assert(VA.isRegLoc() && "Expected register VA assignment");
10193 
10194   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10195   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10196   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10197   SDValue Hi;
10198   if (VA.getLocReg() == RISCV::X17) {
10199     // Second half of f64 is passed on the stack.
10200     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10201     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10202     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10203                      MachinePointerInfo::getFixedStack(MF, FI));
10204   } else {
10205     // Second half of f64 is passed in another GPR.
10206     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10207     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10208     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10209   }
10210   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10211 }
10212 
10213 // FastCC has less than 1% performance improvement for some particular
10214 // benchmark. But theoretically, it may has benenfit for some cases.
10215 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10216                             unsigned ValNo, MVT ValVT, MVT LocVT,
10217                             CCValAssign::LocInfo LocInfo,
10218                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10219                             bool IsFixed, bool IsRet, Type *OrigTy,
10220                             const RISCVTargetLowering &TLI,
10221                             Optional<unsigned> FirstMaskArgument) {
10222 
10223   // X5 and X6 might be used for save-restore libcall.
10224   static const MCPhysReg GPRList[] = {
10225       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10226       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10227       RISCV::X29, RISCV::X30, RISCV::X31};
10228 
10229   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10230     if (unsigned Reg = State.AllocateReg(GPRList)) {
10231       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10232       return false;
10233     }
10234   }
10235 
10236   if (LocVT == MVT::f16) {
10237     static const MCPhysReg FPR16List[] = {
10238         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10239         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10240         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10241         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10242     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10243       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10244       return false;
10245     }
10246   }
10247 
10248   if (LocVT == MVT::f32) {
10249     static const MCPhysReg FPR32List[] = {
10250         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10251         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10252         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10253         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10254     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10255       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10256       return false;
10257     }
10258   }
10259 
10260   if (LocVT == MVT::f64) {
10261     static const MCPhysReg FPR64List[] = {
10262         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10263         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10264         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10265         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10266     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10267       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10268       return false;
10269     }
10270   }
10271 
10272   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10273     unsigned Offset4 = State.AllocateStack(4, Align(4));
10274     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10275     return false;
10276   }
10277 
10278   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10279     unsigned Offset5 = State.AllocateStack(8, Align(8));
10280     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10281     return false;
10282   }
10283 
10284   if (LocVT.isVector()) {
10285     if (unsigned Reg =
10286             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10287       // Fixed-length vectors are located in the corresponding scalable-vector
10288       // container types.
10289       if (ValVT.isFixedLengthVector())
10290         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10291       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10292     } else {
10293       // Try and pass the address via a "fast" GPR.
10294       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10295         LocInfo = CCValAssign::Indirect;
10296         LocVT = TLI.getSubtarget().getXLenVT();
10297         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10298       } else if (ValVT.isFixedLengthVector()) {
10299         auto StackAlign =
10300             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10301         unsigned StackOffset =
10302             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10303         State.addLoc(
10304             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10305       } else {
10306         // Can't pass scalable vectors on the stack.
10307         return true;
10308       }
10309     }
10310 
10311     return false;
10312   }
10313 
10314   return true; // CC didn't match.
10315 }
10316 
10317 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10318                          CCValAssign::LocInfo LocInfo,
10319                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10320 
10321   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10322     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10323     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10324     static const MCPhysReg GPRList[] = {
10325         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10326         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10327     if (unsigned Reg = State.AllocateReg(GPRList)) {
10328       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10329       return false;
10330     }
10331   }
10332 
10333   if (LocVT == MVT::f32) {
10334     // Pass in STG registers: F1, ..., F6
10335     //                        fs0 ... fs5
10336     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10337                                           RISCV::F18_F, RISCV::F19_F,
10338                                           RISCV::F20_F, RISCV::F21_F};
10339     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10340       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10341       return false;
10342     }
10343   }
10344 
10345   if (LocVT == MVT::f64) {
10346     // Pass in STG registers: D1, ..., D6
10347     //                        fs6 ... fs11
10348     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10349                                           RISCV::F24_D, RISCV::F25_D,
10350                                           RISCV::F26_D, RISCV::F27_D};
10351     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10352       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10353       return false;
10354     }
10355   }
10356 
10357   report_fatal_error("No registers left in GHC calling convention");
10358   return true;
10359 }
10360 
10361 // Transform physical registers into virtual registers.
10362 SDValue RISCVTargetLowering::LowerFormalArguments(
10363     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10364     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10365     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10366 
10367   MachineFunction &MF = DAG.getMachineFunction();
10368 
10369   switch (CallConv) {
10370   default:
10371     report_fatal_error("Unsupported calling convention");
10372   case CallingConv::C:
10373   case CallingConv::Fast:
10374     break;
10375   case CallingConv::GHC:
10376     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10377         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10378       report_fatal_error(
10379         "GHC calling convention requires the F and D instruction set extensions");
10380   }
10381 
10382   const Function &Func = MF.getFunction();
10383   if (Func.hasFnAttribute("interrupt")) {
10384     if (!Func.arg_empty())
10385       report_fatal_error(
10386         "Functions with the interrupt attribute cannot have arguments!");
10387 
10388     StringRef Kind =
10389       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10390 
10391     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10392       report_fatal_error(
10393         "Function interrupt attribute argument not supported!");
10394   }
10395 
10396   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10397   MVT XLenVT = Subtarget.getXLenVT();
10398   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10399   // Used with vargs to acumulate store chains.
10400   std::vector<SDValue> OutChains;
10401 
10402   // Assign locations to all of the incoming arguments.
10403   SmallVector<CCValAssign, 16> ArgLocs;
10404   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10405 
10406   if (CallConv == CallingConv::GHC)
10407     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10408   else
10409     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10410                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10411                                                    : CC_RISCV);
10412 
10413   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10414     CCValAssign &VA = ArgLocs[i];
10415     SDValue ArgValue;
10416     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10417     // case.
10418     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10419       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10420     else if (VA.isRegLoc())
10421       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10422     else
10423       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10424 
10425     if (VA.getLocInfo() == CCValAssign::Indirect) {
10426       // If the original argument was split and passed by reference (e.g. i128
10427       // on RV32), we need to load all parts of it here (using the same
10428       // address). Vectors may be partly split to registers and partly to the
10429       // stack, in which case the base address is partly offset and subsequent
10430       // stores are relative to that.
10431       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10432                                    MachinePointerInfo()));
10433       unsigned ArgIndex = Ins[i].OrigArgIndex;
10434       unsigned ArgPartOffset = Ins[i].PartOffset;
10435       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10436       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10437         CCValAssign &PartVA = ArgLocs[i + 1];
10438         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10439         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10440         if (PartVA.getValVT().isScalableVector())
10441           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10442         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10443         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10444                                      MachinePointerInfo()));
10445         ++i;
10446       }
10447       continue;
10448     }
10449     InVals.push_back(ArgValue);
10450   }
10451 
10452   if (IsVarArg) {
10453     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10454     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10455     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10456     MachineFrameInfo &MFI = MF.getFrameInfo();
10457     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10458     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10459 
10460     // Offset of the first variable argument from stack pointer, and size of
10461     // the vararg save area. For now, the varargs save area is either zero or
10462     // large enough to hold a0-a7.
10463     int VaArgOffset, VarArgsSaveSize;
10464 
10465     // If all registers are allocated, then all varargs must be passed on the
10466     // stack and we don't need to save any argregs.
10467     if (ArgRegs.size() == Idx) {
10468       VaArgOffset = CCInfo.getNextStackOffset();
10469       VarArgsSaveSize = 0;
10470     } else {
10471       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10472       VaArgOffset = -VarArgsSaveSize;
10473     }
10474 
10475     // Record the frame index of the first variable argument
10476     // which is a value necessary to VASTART.
10477     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10478     RVFI->setVarArgsFrameIndex(FI);
10479 
10480     // If saving an odd number of registers then create an extra stack slot to
10481     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10482     // offsets to even-numbered registered remain 2*XLEN-aligned.
10483     if (Idx % 2) {
10484       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10485       VarArgsSaveSize += XLenInBytes;
10486     }
10487 
10488     // Copy the integer registers that may have been used for passing varargs
10489     // to the vararg save area.
10490     for (unsigned I = Idx; I < ArgRegs.size();
10491          ++I, VaArgOffset += XLenInBytes) {
10492       const Register Reg = RegInfo.createVirtualRegister(RC);
10493       RegInfo.addLiveIn(ArgRegs[I], Reg);
10494       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10495       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10496       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10497       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10498                                    MachinePointerInfo::getFixedStack(MF, FI));
10499       cast<StoreSDNode>(Store.getNode())
10500           ->getMemOperand()
10501           ->setValue((Value *)nullptr);
10502       OutChains.push_back(Store);
10503     }
10504     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10505   }
10506 
10507   // All stores are grouped in one node to allow the matching between
10508   // the size of Ins and InVals. This only happens for vararg functions.
10509   if (!OutChains.empty()) {
10510     OutChains.push_back(Chain);
10511     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10512   }
10513 
10514   return Chain;
10515 }
10516 
10517 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10518 /// for tail call optimization.
10519 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10520 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10521     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10522     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10523 
10524   auto &Callee = CLI.Callee;
10525   auto CalleeCC = CLI.CallConv;
10526   auto &Outs = CLI.Outs;
10527   auto &Caller = MF.getFunction();
10528   auto CallerCC = Caller.getCallingConv();
10529 
10530   // Exception-handling functions need a special set of instructions to
10531   // indicate a return to the hardware. Tail-calling another function would
10532   // probably break this.
10533   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10534   // should be expanded as new function attributes are introduced.
10535   if (Caller.hasFnAttribute("interrupt"))
10536     return false;
10537 
10538   // Do not tail call opt if the stack is used to pass parameters.
10539   if (CCInfo.getNextStackOffset() != 0)
10540     return false;
10541 
10542   // Do not tail call opt if any parameters need to be passed indirectly.
10543   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10544   // passed indirectly. So the address of the value will be passed in a
10545   // register, or if not available, then the address is put on the stack. In
10546   // order to pass indirectly, space on the stack often needs to be allocated
10547   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10548   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10549   // are passed CCValAssign::Indirect.
10550   for (auto &VA : ArgLocs)
10551     if (VA.getLocInfo() == CCValAssign::Indirect)
10552       return false;
10553 
10554   // Do not tail call opt if either caller or callee uses struct return
10555   // semantics.
10556   auto IsCallerStructRet = Caller.hasStructRetAttr();
10557   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10558   if (IsCallerStructRet || IsCalleeStructRet)
10559     return false;
10560 
10561   // Externally-defined functions with weak linkage should not be
10562   // tail-called. The behaviour of branch instructions in this situation (as
10563   // used for tail calls) is implementation-defined, so we cannot rely on the
10564   // linker replacing the tail call with a return.
10565   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10566     const GlobalValue *GV = G->getGlobal();
10567     if (GV->hasExternalWeakLinkage())
10568       return false;
10569   }
10570 
10571   // The callee has to preserve all registers the caller needs to preserve.
10572   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10573   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10574   if (CalleeCC != CallerCC) {
10575     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10576     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10577       return false;
10578   }
10579 
10580   // Byval parameters hand the function a pointer directly into the stack area
10581   // we want to reuse during a tail call. Working around this *is* possible
10582   // but less efficient and uglier in LowerCall.
10583   for (auto &Arg : Outs)
10584     if (Arg.Flags.isByVal())
10585       return false;
10586 
10587   return true;
10588 }
10589 
10590 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10591   return DAG.getDataLayout().getPrefTypeAlign(
10592       VT.getTypeForEVT(*DAG.getContext()));
10593 }
10594 
10595 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10596 // and output parameter nodes.
10597 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10598                                        SmallVectorImpl<SDValue> &InVals) const {
10599   SelectionDAG &DAG = CLI.DAG;
10600   SDLoc &DL = CLI.DL;
10601   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10602   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10603   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10604   SDValue Chain = CLI.Chain;
10605   SDValue Callee = CLI.Callee;
10606   bool &IsTailCall = CLI.IsTailCall;
10607   CallingConv::ID CallConv = CLI.CallConv;
10608   bool IsVarArg = CLI.IsVarArg;
10609   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10610   MVT XLenVT = Subtarget.getXLenVT();
10611 
10612   MachineFunction &MF = DAG.getMachineFunction();
10613 
10614   // Analyze the operands of the call, assigning locations to each operand.
10615   SmallVector<CCValAssign, 16> ArgLocs;
10616   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10617 
10618   if (CallConv == CallingConv::GHC)
10619     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10620   else
10621     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10622                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10623                                                     : CC_RISCV);
10624 
10625   // Check if it's really possible to do a tail call.
10626   if (IsTailCall)
10627     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10628 
10629   if (IsTailCall)
10630     ++NumTailCalls;
10631   else if (CLI.CB && CLI.CB->isMustTailCall())
10632     report_fatal_error("failed to perform tail call elimination on a call "
10633                        "site marked musttail");
10634 
10635   // Get a count of how many bytes are to be pushed on the stack.
10636   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10637 
10638   // Create local copies for byval args
10639   SmallVector<SDValue, 8> ByValArgs;
10640   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10641     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10642     if (!Flags.isByVal())
10643       continue;
10644 
10645     SDValue Arg = OutVals[i];
10646     unsigned Size = Flags.getByValSize();
10647     Align Alignment = Flags.getNonZeroByValAlign();
10648 
10649     int FI =
10650         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10651     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10652     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10653 
10654     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10655                           /*IsVolatile=*/false,
10656                           /*AlwaysInline=*/false, IsTailCall,
10657                           MachinePointerInfo(), MachinePointerInfo());
10658     ByValArgs.push_back(FIPtr);
10659   }
10660 
10661   if (!IsTailCall)
10662     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10663 
10664   // Copy argument values to their designated locations.
10665   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10666   SmallVector<SDValue, 8> MemOpChains;
10667   SDValue StackPtr;
10668   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10669     CCValAssign &VA = ArgLocs[i];
10670     SDValue ArgValue = OutVals[i];
10671     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10672 
10673     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10674     bool IsF64OnRV32DSoftABI =
10675         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10676     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10677       SDValue SplitF64 = DAG.getNode(
10678           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10679       SDValue Lo = SplitF64.getValue(0);
10680       SDValue Hi = SplitF64.getValue(1);
10681 
10682       Register RegLo = VA.getLocReg();
10683       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10684 
10685       if (RegLo == RISCV::X17) {
10686         // Second half of f64 is passed on the stack.
10687         // Work out the address of the stack slot.
10688         if (!StackPtr.getNode())
10689           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10690         // Emit the store.
10691         MemOpChains.push_back(
10692             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10693       } else {
10694         // Second half of f64 is passed in another GPR.
10695         assert(RegLo < RISCV::X31 && "Invalid register pair");
10696         Register RegHigh = RegLo + 1;
10697         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10698       }
10699       continue;
10700     }
10701 
10702     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10703     // as any other MemLoc.
10704 
10705     // Promote the value if needed.
10706     // For now, only handle fully promoted and indirect arguments.
10707     if (VA.getLocInfo() == CCValAssign::Indirect) {
10708       // Store the argument in a stack slot and pass its address.
10709       Align StackAlign =
10710           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10711                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10712       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10713       // If the original argument was split (e.g. i128), we need
10714       // to store the required parts of it here (and pass just one address).
10715       // Vectors may be partly split to registers and partly to the stack, in
10716       // which case the base address is partly offset and subsequent stores are
10717       // relative to that.
10718       unsigned ArgIndex = Outs[i].OrigArgIndex;
10719       unsigned ArgPartOffset = Outs[i].PartOffset;
10720       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10721       // Calculate the total size to store. We don't have access to what we're
10722       // actually storing other than performing the loop and collecting the
10723       // info.
10724       SmallVector<std::pair<SDValue, SDValue>> Parts;
10725       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10726         SDValue PartValue = OutVals[i + 1];
10727         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10728         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10729         EVT PartVT = PartValue.getValueType();
10730         if (PartVT.isScalableVector())
10731           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10732         StoredSize += PartVT.getStoreSize();
10733         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10734         Parts.push_back(std::make_pair(PartValue, Offset));
10735         ++i;
10736       }
10737       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10738       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10739       MemOpChains.push_back(
10740           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10741                        MachinePointerInfo::getFixedStack(MF, FI)));
10742       for (const auto &Part : Parts) {
10743         SDValue PartValue = Part.first;
10744         SDValue PartOffset = Part.second;
10745         SDValue Address =
10746             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10747         MemOpChains.push_back(
10748             DAG.getStore(Chain, DL, PartValue, Address,
10749                          MachinePointerInfo::getFixedStack(MF, FI)));
10750       }
10751       ArgValue = SpillSlot;
10752     } else {
10753       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10754     }
10755 
10756     // Use local copy if it is a byval arg.
10757     if (Flags.isByVal())
10758       ArgValue = ByValArgs[j++];
10759 
10760     if (VA.isRegLoc()) {
10761       // Queue up the argument copies and emit them at the end.
10762       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10763     } else {
10764       assert(VA.isMemLoc() && "Argument not register or memory");
10765       assert(!IsTailCall && "Tail call not allowed if stack is used "
10766                             "for passing parameters");
10767 
10768       // Work out the address of the stack slot.
10769       if (!StackPtr.getNode())
10770         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10771       SDValue Address =
10772           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10773                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10774 
10775       // Emit the store.
10776       MemOpChains.push_back(
10777           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10778     }
10779   }
10780 
10781   // Join the stores, which are independent of one another.
10782   if (!MemOpChains.empty())
10783     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10784 
10785   SDValue Glue;
10786 
10787   // Build a sequence of copy-to-reg nodes, chained and glued together.
10788   for (auto &Reg : RegsToPass) {
10789     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10790     Glue = Chain.getValue(1);
10791   }
10792 
10793   // Validate that none of the argument registers have been marked as
10794   // reserved, if so report an error. Do the same for the return address if this
10795   // is not a tailcall.
10796   validateCCReservedRegs(RegsToPass, MF);
10797   if (!IsTailCall &&
10798       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10799     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10800         MF.getFunction(),
10801         "Return address register required, but has been reserved."});
10802 
10803   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10804   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10805   // split it and then direct call can be matched by PseudoCALL.
10806   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10807     const GlobalValue *GV = S->getGlobal();
10808 
10809     unsigned OpFlags = RISCVII::MO_CALL;
10810     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10811       OpFlags = RISCVII::MO_PLT;
10812 
10813     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10814   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10815     unsigned OpFlags = RISCVII::MO_CALL;
10816 
10817     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10818                                                  nullptr))
10819       OpFlags = RISCVII::MO_PLT;
10820 
10821     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10822   }
10823 
10824   // The first call operand is the chain and the second is the target address.
10825   SmallVector<SDValue, 8> Ops;
10826   Ops.push_back(Chain);
10827   Ops.push_back(Callee);
10828 
10829   // Add argument registers to the end of the list so that they are
10830   // known live into the call.
10831   for (auto &Reg : RegsToPass)
10832     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10833 
10834   if (!IsTailCall) {
10835     // Add a register mask operand representing the call-preserved registers.
10836     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10837     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10838     assert(Mask && "Missing call preserved mask for calling convention");
10839     Ops.push_back(DAG.getRegisterMask(Mask));
10840   }
10841 
10842   // Glue the call to the argument copies, if any.
10843   if (Glue.getNode())
10844     Ops.push_back(Glue);
10845 
10846   // Emit the call.
10847   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10848 
10849   if (IsTailCall) {
10850     MF.getFrameInfo().setHasTailCall();
10851     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10852   }
10853 
10854   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10855   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10856   Glue = Chain.getValue(1);
10857 
10858   // Mark the end of the call, which is glued to the call itself.
10859   Chain = DAG.getCALLSEQ_END(Chain,
10860                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10861                              DAG.getConstant(0, DL, PtrVT, true),
10862                              Glue, DL);
10863   Glue = Chain.getValue(1);
10864 
10865   // Assign locations to each value returned by this call.
10866   SmallVector<CCValAssign, 16> RVLocs;
10867   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10868   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10869 
10870   // Copy all of the result registers out of their specified physreg.
10871   for (auto &VA : RVLocs) {
10872     // Copy the value out
10873     SDValue RetValue =
10874         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10875     // Glue the RetValue to the end of the call sequence
10876     Chain = RetValue.getValue(1);
10877     Glue = RetValue.getValue(2);
10878 
10879     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10880       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10881       SDValue RetValue2 =
10882           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10883       Chain = RetValue2.getValue(1);
10884       Glue = RetValue2.getValue(2);
10885       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10886                              RetValue2);
10887     }
10888 
10889     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10890 
10891     InVals.push_back(RetValue);
10892   }
10893 
10894   return Chain;
10895 }
10896 
10897 bool RISCVTargetLowering::CanLowerReturn(
10898     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10899     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10900   SmallVector<CCValAssign, 16> RVLocs;
10901   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10902 
10903   Optional<unsigned> FirstMaskArgument;
10904   if (Subtarget.hasVInstructions())
10905     FirstMaskArgument = preAssignMask(Outs);
10906 
10907   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10908     MVT VT = Outs[i].VT;
10909     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10910     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10911     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10912                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10913                  *this, FirstMaskArgument))
10914       return false;
10915   }
10916   return true;
10917 }
10918 
10919 SDValue
10920 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10921                                  bool IsVarArg,
10922                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10923                                  const SmallVectorImpl<SDValue> &OutVals,
10924                                  const SDLoc &DL, SelectionDAG &DAG) const {
10925   const MachineFunction &MF = DAG.getMachineFunction();
10926   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10927 
10928   // Stores the assignment of the return value to a location.
10929   SmallVector<CCValAssign, 16> RVLocs;
10930 
10931   // Info about the registers and stack slot.
10932   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10933                  *DAG.getContext());
10934 
10935   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10936                     nullptr, CC_RISCV);
10937 
10938   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10939     report_fatal_error("GHC functions return void only");
10940 
10941   SDValue Glue;
10942   SmallVector<SDValue, 4> RetOps(1, Chain);
10943 
10944   // Copy the result values into the output registers.
10945   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10946     SDValue Val = OutVals[i];
10947     CCValAssign &VA = RVLocs[i];
10948     assert(VA.isRegLoc() && "Can only return in registers!");
10949 
10950     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10951       // Handle returning f64 on RV32D with a soft float ABI.
10952       assert(VA.isRegLoc() && "Expected return via registers");
10953       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10954                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10955       SDValue Lo = SplitF64.getValue(0);
10956       SDValue Hi = SplitF64.getValue(1);
10957       Register RegLo = VA.getLocReg();
10958       assert(RegLo < RISCV::X31 && "Invalid register pair");
10959       Register RegHi = RegLo + 1;
10960 
10961       if (STI.isRegisterReservedByUser(RegLo) ||
10962           STI.isRegisterReservedByUser(RegHi))
10963         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10964             MF.getFunction(),
10965             "Return value register required, but has been reserved."});
10966 
10967       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10968       Glue = Chain.getValue(1);
10969       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10970       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10971       Glue = Chain.getValue(1);
10972       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10973     } else {
10974       // Handle a 'normal' return.
10975       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10976       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10977 
10978       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10979         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10980             MF.getFunction(),
10981             "Return value register required, but has been reserved."});
10982 
10983       // Guarantee that all emitted copies are stuck together.
10984       Glue = Chain.getValue(1);
10985       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10986     }
10987   }
10988 
10989   RetOps[0] = Chain; // Update chain.
10990 
10991   // Add the glue node if we have it.
10992   if (Glue.getNode()) {
10993     RetOps.push_back(Glue);
10994   }
10995 
10996   unsigned RetOpc = RISCVISD::RET_FLAG;
10997   // Interrupt service routines use different return instructions.
10998   const Function &Func = DAG.getMachineFunction().getFunction();
10999   if (Func.hasFnAttribute("interrupt")) {
11000     if (!Func.getReturnType()->isVoidTy())
11001       report_fatal_error(
11002           "Functions with the interrupt attribute must have void return type!");
11003 
11004     MachineFunction &MF = DAG.getMachineFunction();
11005     StringRef Kind =
11006       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11007 
11008     if (Kind == "user")
11009       RetOpc = RISCVISD::URET_FLAG;
11010     else if (Kind == "supervisor")
11011       RetOpc = RISCVISD::SRET_FLAG;
11012     else
11013       RetOpc = RISCVISD::MRET_FLAG;
11014   }
11015 
11016   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11017 }
11018 
11019 void RISCVTargetLowering::validateCCReservedRegs(
11020     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11021     MachineFunction &MF) const {
11022   const Function &F = MF.getFunction();
11023   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11024 
11025   if (llvm::any_of(Regs, [&STI](auto Reg) {
11026         return STI.isRegisterReservedByUser(Reg.first);
11027       }))
11028     F.getContext().diagnose(DiagnosticInfoUnsupported{
11029         F, "Argument register required, but has been reserved."});
11030 }
11031 
11032 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11033   return CI->isTailCall();
11034 }
11035 
11036 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11037 #define NODE_NAME_CASE(NODE)                                                   \
11038   case RISCVISD::NODE:                                                         \
11039     return "RISCVISD::" #NODE;
11040   // clang-format off
11041   switch ((RISCVISD::NodeType)Opcode) {
11042   case RISCVISD::FIRST_NUMBER:
11043     break;
11044   NODE_NAME_CASE(RET_FLAG)
11045   NODE_NAME_CASE(URET_FLAG)
11046   NODE_NAME_CASE(SRET_FLAG)
11047   NODE_NAME_CASE(MRET_FLAG)
11048   NODE_NAME_CASE(CALL)
11049   NODE_NAME_CASE(SELECT_CC)
11050   NODE_NAME_CASE(BR_CC)
11051   NODE_NAME_CASE(BuildPairF64)
11052   NODE_NAME_CASE(SplitF64)
11053   NODE_NAME_CASE(TAIL)
11054   NODE_NAME_CASE(MULHSU)
11055   NODE_NAME_CASE(SLLW)
11056   NODE_NAME_CASE(SRAW)
11057   NODE_NAME_CASE(SRLW)
11058   NODE_NAME_CASE(DIVW)
11059   NODE_NAME_CASE(DIVUW)
11060   NODE_NAME_CASE(REMUW)
11061   NODE_NAME_CASE(ROLW)
11062   NODE_NAME_CASE(RORW)
11063   NODE_NAME_CASE(CLZW)
11064   NODE_NAME_CASE(CTZW)
11065   NODE_NAME_CASE(FSLW)
11066   NODE_NAME_CASE(FSRW)
11067   NODE_NAME_CASE(FSL)
11068   NODE_NAME_CASE(FSR)
11069   NODE_NAME_CASE(FMV_H_X)
11070   NODE_NAME_CASE(FMV_X_ANYEXTH)
11071   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11072   NODE_NAME_CASE(FMV_W_X_RV64)
11073   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11074   NODE_NAME_CASE(FCVT_X)
11075   NODE_NAME_CASE(FCVT_XU)
11076   NODE_NAME_CASE(FCVT_W_RV64)
11077   NODE_NAME_CASE(FCVT_WU_RV64)
11078   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11079   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11080   NODE_NAME_CASE(READ_CYCLE_WIDE)
11081   NODE_NAME_CASE(GREV)
11082   NODE_NAME_CASE(GREVW)
11083   NODE_NAME_CASE(GORC)
11084   NODE_NAME_CASE(GORCW)
11085   NODE_NAME_CASE(SHFL)
11086   NODE_NAME_CASE(SHFLW)
11087   NODE_NAME_CASE(UNSHFL)
11088   NODE_NAME_CASE(UNSHFLW)
11089   NODE_NAME_CASE(BFP)
11090   NODE_NAME_CASE(BFPW)
11091   NODE_NAME_CASE(BCOMPRESS)
11092   NODE_NAME_CASE(BCOMPRESSW)
11093   NODE_NAME_CASE(BDECOMPRESS)
11094   NODE_NAME_CASE(BDECOMPRESSW)
11095   NODE_NAME_CASE(VMV_V_X_VL)
11096   NODE_NAME_CASE(VFMV_V_F_VL)
11097   NODE_NAME_CASE(VMV_X_S)
11098   NODE_NAME_CASE(VMV_S_X_VL)
11099   NODE_NAME_CASE(VFMV_S_F_VL)
11100   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11101   NODE_NAME_CASE(READ_VLENB)
11102   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11103   NODE_NAME_CASE(VSLIDEUP_VL)
11104   NODE_NAME_CASE(VSLIDE1UP_VL)
11105   NODE_NAME_CASE(VSLIDEDOWN_VL)
11106   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11107   NODE_NAME_CASE(VID_VL)
11108   NODE_NAME_CASE(VFNCVT_ROD_VL)
11109   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11110   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11111   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11112   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11113   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11114   NODE_NAME_CASE(VECREDUCE_AND_VL)
11115   NODE_NAME_CASE(VECREDUCE_OR_VL)
11116   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11117   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11118   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11119   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11120   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11121   NODE_NAME_CASE(ADD_VL)
11122   NODE_NAME_CASE(AND_VL)
11123   NODE_NAME_CASE(MUL_VL)
11124   NODE_NAME_CASE(OR_VL)
11125   NODE_NAME_CASE(SDIV_VL)
11126   NODE_NAME_CASE(SHL_VL)
11127   NODE_NAME_CASE(SREM_VL)
11128   NODE_NAME_CASE(SRA_VL)
11129   NODE_NAME_CASE(SRL_VL)
11130   NODE_NAME_CASE(SUB_VL)
11131   NODE_NAME_CASE(UDIV_VL)
11132   NODE_NAME_CASE(UREM_VL)
11133   NODE_NAME_CASE(XOR_VL)
11134   NODE_NAME_CASE(SADDSAT_VL)
11135   NODE_NAME_CASE(UADDSAT_VL)
11136   NODE_NAME_CASE(SSUBSAT_VL)
11137   NODE_NAME_CASE(USUBSAT_VL)
11138   NODE_NAME_CASE(FADD_VL)
11139   NODE_NAME_CASE(FSUB_VL)
11140   NODE_NAME_CASE(FMUL_VL)
11141   NODE_NAME_CASE(FDIV_VL)
11142   NODE_NAME_CASE(FNEG_VL)
11143   NODE_NAME_CASE(FABS_VL)
11144   NODE_NAME_CASE(FSQRT_VL)
11145   NODE_NAME_CASE(FMA_VL)
11146   NODE_NAME_CASE(FCOPYSIGN_VL)
11147   NODE_NAME_CASE(SMIN_VL)
11148   NODE_NAME_CASE(SMAX_VL)
11149   NODE_NAME_CASE(UMIN_VL)
11150   NODE_NAME_CASE(UMAX_VL)
11151   NODE_NAME_CASE(FMINNUM_VL)
11152   NODE_NAME_CASE(FMAXNUM_VL)
11153   NODE_NAME_CASE(MULHS_VL)
11154   NODE_NAME_CASE(MULHU_VL)
11155   NODE_NAME_CASE(FP_TO_SINT_VL)
11156   NODE_NAME_CASE(FP_TO_UINT_VL)
11157   NODE_NAME_CASE(SINT_TO_FP_VL)
11158   NODE_NAME_CASE(UINT_TO_FP_VL)
11159   NODE_NAME_CASE(FP_EXTEND_VL)
11160   NODE_NAME_CASE(FP_ROUND_VL)
11161   NODE_NAME_CASE(VWMUL_VL)
11162   NODE_NAME_CASE(VWMULU_VL)
11163   NODE_NAME_CASE(VWMULSU_VL)
11164   NODE_NAME_CASE(VWADD_VL)
11165   NODE_NAME_CASE(VWADDU_VL)
11166   NODE_NAME_CASE(VWSUB_VL)
11167   NODE_NAME_CASE(VWSUBU_VL)
11168   NODE_NAME_CASE(VWADD_W_VL)
11169   NODE_NAME_CASE(VWADDU_W_VL)
11170   NODE_NAME_CASE(VWSUB_W_VL)
11171   NODE_NAME_CASE(VWSUBU_W_VL)
11172   NODE_NAME_CASE(SETCC_VL)
11173   NODE_NAME_CASE(VSELECT_VL)
11174   NODE_NAME_CASE(VP_MERGE_VL)
11175   NODE_NAME_CASE(VMAND_VL)
11176   NODE_NAME_CASE(VMOR_VL)
11177   NODE_NAME_CASE(VMXOR_VL)
11178   NODE_NAME_CASE(VMCLR_VL)
11179   NODE_NAME_CASE(VMSET_VL)
11180   NODE_NAME_CASE(VRGATHER_VX_VL)
11181   NODE_NAME_CASE(VRGATHER_VV_VL)
11182   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11183   NODE_NAME_CASE(VSEXT_VL)
11184   NODE_NAME_CASE(VZEXT_VL)
11185   NODE_NAME_CASE(VCPOP_VL)
11186   NODE_NAME_CASE(READ_CSR)
11187   NODE_NAME_CASE(WRITE_CSR)
11188   NODE_NAME_CASE(SWAP_CSR)
11189   }
11190   // clang-format on
11191   return nullptr;
11192 #undef NODE_NAME_CASE
11193 }
11194 
11195 /// getConstraintType - Given a constraint letter, return the type of
11196 /// constraint it is for this target.
11197 RISCVTargetLowering::ConstraintType
11198 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11199   if (Constraint.size() == 1) {
11200     switch (Constraint[0]) {
11201     default:
11202       break;
11203     case 'f':
11204       return C_RegisterClass;
11205     case 'I':
11206     case 'J':
11207     case 'K':
11208       return C_Immediate;
11209     case 'A':
11210       return C_Memory;
11211     case 'S': // A symbolic address
11212       return C_Other;
11213     }
11214   } else {
11215     if (Constraint == "vr" || Constraint == "vm")
11216       return C_RegisterClass;
11217   }
11218   return TargetLowering::getConstraintType(Constraint);
11219 }
11220 
11221 std::pair<unsigned, const TargetRegisterClass *>
11222 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11223                                                   StringRef Constraint,
11224                                                   MVT VT) const {
11225   // First, see if this is a constraint that directly corresponds to a
11226   // RISCV register class.
11227   if (Constraint.size() == 1) {
11228     switch (Constraint[0]) {
11229     case 'r':
11230       // TODO: Support fixed vectors up to XLen for P extension?
11231       if (VT.isVector())
11232         break;
11233       return std::make_pair(0U, &RISCV::GPRRegClass);
11234     case 'f':
11235       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11236         return std::make_pair(0U, &RISCV::FPR16RegClass);
11237       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11238         return std::make_pair(0U, &RISCV::FPR32RegClass);
11239       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11240         return std::make_pair(0U, &RISCV::FPR64RegClass);
11241       break;
11242     default:
11243       break;
11244     }
11245   } else if (Constraint == "vr") {
11246     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11247                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11248       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11249         return std::make_pair(0U, RC);
11250     }
11251   } else if (Constraint == "vm") {
11252     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11253       return std::make_pair(0U, &RISCV::VMV0RegClass);
11254   }
11255 
11256   // Clang will correctly decode the usage of register name aliases into their
11257   // official names. However, other frontends like `rustc` do not. This allows
11258   // users of these frontends to use the ABI names for registers in LLVM-style
11259   // register constraints.
11260   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11261                                .Case("{zero}", RISCV::X0)
11262                                .Case("{ra}", RISCV::X1)
11263                                .Case("{sp}", RISCV::X2)
11264                                .Case("{gp}", RISCV::X3)
11265                                .Case("{tp}", RISCV::X4)
11266                                .Case("{t0}", RISCV::X5)
11267                                .Case("{t1}", RISCV::X6)
11268                                .Case("{t2}", RISCV::X7)
11269                                .Cases("{s0}", "{fp}", RISCV::X8)
11270                                .Case("{s1}", RISCV::X9)
11271                                .Case("{a0}", RISCV::X10)
11272                                .Case("{a1}", RISCV::X11)
11273                                .Case("{a2}", RISCV::X12)
11274                                .Case("{a3}", RISCV::X13)
11275                                .Case("{a4}", RISCV::X14)
11276                                .Case("{a5}", RISCV::X15)
11277                                .Case("{a6}", RISCV::X16)
11278                                .Case("{a7}", RISCV::X17)
11279                                .Case("{s2}", RISCV::X18)
11280                                .Case("{s3}", RISCV::X19)
11281                                .Case("{s4}", RISCV::X20)
11282                                .Case("{s5}", RISCV::X21)
11283                                .Case("{s6}", RISCV::X22)
11284                                .Case("{s7}", RISCV::X23)
11285                                .Case("{s8}", RISCV::X24)
11286                                .Case("{s9}", RISCV::X25)
11287                                .Case("{s10}", RISCV::X26)
11288                                .Case("{s11}", RISCV::X27)
11289                                .Case("{t3}", RISCV::X28)
11290                                .Case("{t4}", RISCV::X29)
11291                                .Case("{t5}", RISCV::X30)
11292                                .Case("{t6}", RISCV::X31)
11293                                .Default(RISCV::NoRegister);
11294   if (XRegFromAlias != RISCV::NoRegister)
11295     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11296 
11297   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11298   // TableGen record rather than the AsmName to choose registers for InlineAsm
11299   // constraints, plus we want to match those names to the widest floating point
11300   // register type available, manually select floating point registers here.
11301   //
11302   // The second case is the ABI name of the register, so that frontends can also
11303   // use the ABI names in register constraint lists.
11304   if (Subtarget.hasStdExtF()) {
11305     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11306                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11307                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11308                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11309                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11310                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11311                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11312                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11313                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11314                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11315                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11316                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11317                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11318                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11319                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11320                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11321                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11322                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11323                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11324                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11325                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11326                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11327                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11328                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11329                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11330                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11331                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11332                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11333                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11334                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11335                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11336                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11337                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11338                         .Default(RISCV::NoRegister);
11339     if (FReg != RISCV::NoRegister) {
11340       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11341       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11342         unsigned RegNo = FReg - RISCV::F0_F;
11343         unsigned DReg = RISCV::F0_D + RegNo;
11344         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11345       }
11346       if (VT == MVT::f32 || VT == MVT::Other)
11347         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11348       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11349         unsigned RegNo = FReg - RISCV::F0_F;
11350         unsigned HReg = RISCV::F0_H + RegNo;
11351         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11352       }
11353     }
11354   }
11355 
11356   if (Subtarget.hasVInstructions()) {
11357     Register VReg = StringSwitch<Register>(Constraint.lower())
11358                         .Case("{v0}", RISCV::V0)
11359                         .Case("{v1}", RISCV::V1)
11360                         .Case("{v2}", RISCV::V2)
11361                         .Case("{v3}", RISCV::V3)
11362                         .Case("{v4}", RISCV::V4)
11363                         .Case("{v5}", RISCV::V5)
11364                         .Case("{v6}", RISCV::V6)
11365                         .Case("{v7}", RISCV::V7)
11366                         .Case("{v8}", RISCV::V8)
11367                         .Case("{v9}", RISCV::V9)
11368                         .Case("{v10}", RISCV::V10)
11369                         .Case("{v11}", RISCV::V11)
11370                         .Case("{v12}", RISCV::V12)
11371                         .Case("{v13}", RISCV::V13)
11372                         .Case("{v14}", RISCV::V14)
11373                         .Case("{v15}", RISCV::V15)
11374                         .Case("{v16}", RISCV::V16)
11375                         .Case("{v17}", RISCV::V17)
11376                         .Case("{v18}", RISCV::V18)
11377                         .Case("{v19}", RISCV::V19)
11378                         .Case("{v20}", RISCV::V20)
11379                         .Case("{v21}", RISCV::V21)
11380                         .Case("{v22}", RISCV::V22)
11381                         .Case("{v23}", RISCV::V23)
11382                         .Case("{v24}", RISCV::V24)
11383                         .Case("{v25}", RISCV::V25)
11384                         .Case("{v26}", RISCV::V26)
11385                         .Case("{v27}", RISCV::V27)
11386                         .Case("{v28}", RISCV::V28)
11387                         .Case("{v29}", RISCV::V29)
11388                         .Case("{v30}", RISCV::V30)
11389                         .Case("{v31}", RISCV::V31)
11390                         .Default(RISCV::NoRegister);
11391     if (VReg != RISCV::NoRegister) {
11392       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11393         return std::make_pair(VReg, &RISCV::VMRegClass);
11394       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11395         return std::make_pair(VReg, &RISCV::VRRegClass);
11396       for (const auto *RC :
11397            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11398         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11399           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11400           return std::make_pair(VReg, RC);
11401         }
11402       }
11403     }
11404   }
11405 
11406   std::pair<Register, const TargetRegisterClass *> Res =
11407       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11408 
11409   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11410   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11411   // Subtarget into account.
11412   if (Res.second == &RISCV::GPRF16RegClass ||
11413       Res.second == &RISCV::GPRF32RegClass ||
11414       Res.second == &RISCV::GPRF64RegClass)
11415     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11416 
11417   return Res;
11418 }
11419 
11420 unsigned
11421 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11422   // Currently only support length 1 constraints.
11423   if (ConstraintCode.size() == 1) {
11424     switch (ConstraintCode[0]) {
11425     case 'A':
11426       return InlineAsm::Constraint_A;
11427     default:
11428       break;
11429     }
11430   }
11431 
11432   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11433 }
11434 
11435 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11436     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11437     SelectionDAG &DAG) const {
11438   // Currently only support length 1 constraints.
11439   if (Constraint.length() == 1) {
11440     switch (Constraint[0]) {
11441     case 'I':
11442       // Validate & create a 12-bit signed immediate operand.
11443       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11444         uint64_t CVal = C->getSExtValue();
11445         if (isInt<12>(CVal))
11446           Ops.push_back(
11447               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11448       }
11449       return;
11450     case 'J':
11451       // Validate & create an integer zero operand.
11452       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11453         if (C->getZExtValue() == 0)
11454           Ops.push_back(
11455               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11456       return;
11457     case 'K':
11458       // Validate & create a 5-bit unsigned immediate operand.
11459       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11460         uint64_t CVal = C->getZExtValue();
11461         if (isUInt<5>(CVal))
11462           Ops.push_back(
11463               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11464       }
11465       return;
11466     case 'S':
11467       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11468         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11469                                                  GA->getValueType(0)));
11470       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11471         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11472                                                 BA->getValueType(0)));
11473       }
11474       return;
11475     default:
11476       break;
11477     }
11478   }
11479   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11480 }
11481 
11482 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11483                                                    Instruction *Inst,
11484                                                    AtomicOrdering Ord) const {
11485   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11486     return Builder.CreateFence(Ord);
11487   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11488     return Builder.CreateFence(AtomicOrdering::Release);
11489   return nullptr;
11490 }
11491 
11492 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11493                                                     Instruction *Inst,
11494                                                     AtomicOrdering Ord) const {
11495   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11496     return Builder.CreateFence(AtomicOrdering::Acquire);
11497   return nullptr;
11498 }
11499 
11500 TargetLowering::AtomicExpansionKind
11501 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11502   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11503   // point operations can't be used in an lr/sc sequence without breaking the
11504   // forward-progress guarantee.
11505   if (AI->isFloatingPointOperation())
11506     return AtomicExpansionKind::CmpXChg;
11507 
11508   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11509   if (Size == 8 || Size == 16)
11510     return AtomicExpansionKind::MaskedIntrinsic;
11511   return AtomicExpansionKind::None;
11512 }
11513 
11514 static Intrinsic::ID
11515 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11516   if (XLen == 32) {
11517     switch (BinOp) {
11518     default:
11519       llvm_unreachable("Unexpected AtomicRMW BinOp");
11520     case AtomicRMWInst::Xchg:
11521       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11522     case AtomicRMWInst::Add:
11523       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11524     case AtomicRMWInst::Sub:
11525       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11526     case AtomicRMWInst::Nand:
11527       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11528     case AtomicRMWInst::Max:
11529       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11530     case AtomicRMWInst::Min:
11531       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11532     case AtomicRMWInst::UMax:
11533       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11534     case AtomicRMWInst::UMin:
11535       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11536     }
11537   }
11538 
11539   if (XLen == 64) {
11540     switch (BinOp) {
11541     default:
11542       llvm_unreachable("Unexpected AtomicRMW BinOp");
11543     case AtomicRMWInst::Xchg:
11544       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11545     case AtomicRMWInst::Add:
11546       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11547     case AtomicRMWInst::Sub:
11548       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11549     case AtomicRMWInst::Nand:
11550       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11551     case AtomicRMWInst::Max:
11552       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11553     case AtomicRMWInst::Min:
11554       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11555     case AtomicRMWInst::UMax:
11556       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11557     case AtomicRMWInst::UMin:
11558       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11559     }
11560   }
11561 
11562   llvm_unreachable("Unexpected XLen\n");
11563 }
11564 
11565 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11566     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11567     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11568   unsigned XLen = Subtarget.getXLen();
11569   Value *Ordering =
11570       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11571   Type *Tys[] = {AlignedAddr->getType()};
11572   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11573       AI->getModule(),
11574       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11575 
11576   if (XLen == 64) {
11577     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11578     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11579     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11580   }
11581 
11582   Value *Result;
11583 
11584   // Must pass the shift amount needed to sign extend the loaded value prior
11585   // to performing a signed comparison for min/max. ShiftAmt is the number of
11586   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11587   // is the number of bits to left+right shift the value in order to
11588   // sign-extend.
11589   if (AI->getOperation() == AtomicRMWInst::Min ||
11590       AI->getOperation() == AtomicRMWInst::Max) {
11591     const DataLayout &DL = AI->getModule()->getDataLayout();
11592     unsigned ValWidth =
11593         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11594     Value *SextShamt =
11595         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11596     Result = Builder.CreateCall(LrwOpScwLoop,
11597                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11598   } else {
11599     Result =
11600         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11601   }
11602 
11603   if (XLen == 64)
11604     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11605   return Result;
11606 }
11607 
11608 TargetLowering::AtomicExpansionKind
11609 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11610     AtomicCmpXchgInst *CI) const {
11611   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11612   if (Size == 8 || Size == 16)
11613     return AtomicExpansionKind::MaskedIntrinsic;
11614   return AtomicExpansionKind::None;
11615 }
11616 
11617 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11618     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11619     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11620   unsigned XLen = Subtarget.getXLen();
11621   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11622   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11623   if (XLen == 64) {
11624     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11625     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11626     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11627     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11628   }
11629   Type *Tys[] = {AlignedAddr->getType()};
11630   Function *MaskedCmpXchg =
11631       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11632   Value *Result = Builder.CreateCall(
11633       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11634   if (XLen == 64)
11635     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11636   return Result;
11637 }
11638 
11639 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
11640                                                         EVT DataVT) const {
11641   return false;
11642 }
11643 
11644 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11645                                                EVT VT) const {
11646   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11647     return false;
11648 
11649   switch (FPVT.getSimpleVT().SimpleTy) {
11650   case MVT::f16:
11651     return Subtarget.hasStdExtZfh();
11652   case MVT::f32:
11653     return Subtarget.hasStdExtF();
11654   case MVT::f64:
11655     return Subtarget.hasStdExtD();
11656   default:
11657     return false;
11658   }
11659 }
11660 
11661 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11662   // If we are using the small code model, we can reduce size of jump table
11663   // entry to 4 bytes.
11664   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11665       getTargetMachine().getCodeModel() == CodeModel::Small) {
11666     return MachineJumpTableInfo::EK_Custom32;
11667   }
11668   return TargetLowering::getJumpTableEncoding();
11669 }
11670 
11671 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11672     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11673     unsigned uid, MCContext &Ctx) const {
11674   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11675          getTargetMachine().getCodeModel() == CodeModel::Small);
11676   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11677 }
11678 
11679 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11680                                                      EVT VT) const {
11681   VT = VT.getScalarType();
11682 
11683   if (!VT.isSimple())
11684     return false;
11685 
11686   switch (VT.getSimpleVT().SimpleTy) {
11687   case MVT::f16:
11688     return Subtarget.hasStdExtZfh();
11689   case MVT::f32:
11690     return Subtarget.hasStdExtF();
11691   case MVT::f64:
11692     return Subtarget.hasStdExtD();
11693   default:
11694     break;
11695   }
11696 
11697   return false;
11698 }
11699 
11700 Register RISCVTargetLowering::getExceptionPointerRegister(
11701     const Constant *PersonalityFn) const {
11702   return RISCV::X10;
11703 }
11704 
11705 Register RISCVTargetLowering::getExceptionSelectorRegister(
11706     const Constant *PersonalityFn) const {
11707   return RISCV::X11;
11708 }
11709 
11710 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11711   // Return false to suppress the unnecessary extensions if the LibCall
11712   // arguments or return value is f32 type for LP64 ABI.
11713   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11714   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11715     return false;
11716 
11717   return true;
11718 }
11719 
11720 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11721   if (Subtarget.is64Bit() && Type == MVT::i32)
11722     return true;
11723 
11724   return IsSigned;
11725 }
11726 
11727 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11728                                                  SDValue C) const {
11729   // Check integral scalar types.
11730   if (VT.isScalarInteger()) {
11731     // Omit the optimization if the sub target has the M extension and the data
11732     // size exceeds XLen.
11733     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11734       return false;
11735     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11736       // Break the MUL to a SLLI and an ADD/SUB.
11737       const APInt &Imm = ConstNode->getAPIntValue();
11738       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11739           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11740         return true;
11741       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11742       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11743           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11744            (Imm - 8).isPowerOf2()))
11745         return true;
11746       // Omit the following optimization if the sub target has the M extension
11747       // and the data size >= XLen.
11748       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11749         return false;
11750       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11751       // a pair of LUI/ADDI.
11752       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11753         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11754         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11755             (1 - ImmS).isPowerOf2())
11756         return true;
11757       }
11758     }
11759   }
11760 
11761   return false;
11762 }
11763 
11764 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11765                                                       SDValue ConstNode) const {
11766   // Let the DAGCombiner decide for vectors.
11767   EVT VT = AddNode.getValueType();
11768   if (VT.isVector())
11769     return true;
11770 
11771   // Let the DAGCombiner decide for larger types.
11772   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11773     return true;
11774 
11775   // It is worse if c1 is simm12 while c1*c2 is not.
11776   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11777   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11778   const APInt &C1 = C1Node->getAPIntValue();
11779   const APInt &C2 = C2Node->getAPIntValue();
11780   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11781     return false;
11782 
11783   // Default to true and let the DAGCombiner decide.
11784   return true;
11785 }
11786 
11787 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11788     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11789     bool *Fast) const {
11790   if (!VT.isVector())
11791     return false;
11792 
11793   EVT ElemVT = VT.getVectorElementType();
11794   if (Alignment >= ElemVT.getStoreSize()) {
11795     if (Fast)
11796       *Fast = true;
11797     return true;
11798   }
11799 
11800   return false;
11801 }
11802 
11803 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11804     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11805     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11806   bool IsABIRegCopy = CC.hasValue();
11807   EVT ValueVT = Val.getValueType();
11808   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11809     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11810     // and cast to f32.
11811     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11812     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11813     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11814                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11815     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11816     Parts[0] = Val;
11817     return true;
11818   }
11819 
11820   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11821     LLVMContext &Context = *DAG.getContext();
11822     EVT ValueEltVT = ValueVT.getVectorElementType();
11823     EVT PartEltVT = PartVT.getVectorElementType();
11824     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11825     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11826     if (PartVTBitSize % ValueVTBitSize == 0) {
11827       assert(PartVTBitSize >= ValueVTBitSize);
11828       // If the element types are different, bitcast to the same element type of
11829       // PartVT first.
11830       // Give an example here, we want copy a <vscale x 1 x i8> value to
11831       // <vscale x 4 x i16>.
11832       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11833       // subvector, then we can bitcast to <vscale x 4 x i16>.
11834       if (ValueEltVT != PartEltVT) {
11835         if (PartVTBitSize > ValueVTBitSize) {
11836           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11837           assert(Count != 0 && "The number of element should not be zero.");
11838           EVT SameEltTypeVT =
11839               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11840           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11841                             DAG.getUNDEF(SameEltTypeVT), Val,
11842                             DAG.getVectorIdxConstant(0, DL));
11843         }
11844         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11845       } else {
11846         Val =
11847             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11848                         Val, DAG.getVectorIdxConstant(0, DL));
11849       }
11850       Parts[0] = Val;
11851       return true;
11852     }
11853   }
11854   return false;
11855 }
11856 
11857 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11858     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11859     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11860   bool IsABIRegCopy = CC.hasValue();
11861   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11862     SDValue Val = Parts[0];
11863 
11864     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11865     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11866     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11867     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11868     return Val;
11869   }
11870 
11871   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11872     LLVMContext &Context = *DAG.getContext();
11873     SDValue Val = Parts[0];
11874     EVT ValueEltVT = ValueVT.getVectorElementType();
11875     EVT PartEltVT = PartVT.getVectorElementType();
11876     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11877     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11878     if (PartVTBitSize % ValueVTBitSize == 0) {
11879       assert(PartVTBitSize >= ValueVTBitSize);
11880       EVT SameEltTypeVT = ValueVT;
11881       // If the element types are different, convert it to the same element type
11882       // of PartVT.
11883       // Give an example here, we want copy a <vscale x 1 x i8> value from
11884       // <vscale x 4 x i16>.
11885       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11886       // then we can extract <vscale x 1 x i8>.
11887       if (ValueEltVT != PartEltVT) {
11888         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11889         assert(Count != 0 && "The number of element should not be zero.");
11890         SameEltTypeVT =
11891             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11892         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11893       }
11894       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11895                         DAG.getVectorIdxConstant(0, DL));
11896       return Val;
11897     }
11898   }
11899   return SDValue();
11900 }
11901 
11902 SDValue
11903 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11904                                    SelectionDAG &DAG,
11905                                    SmallVectorImpl<SDNode *> &Created) const {
11906   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11907   if (isIntDivCheap(N->getValueType(0), Attr))
11908     return SDValue(N, 0); // Lower SDIV as SDIV
11909 
11910   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11911          "Unexpected divisor!");
11912 
11913   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11914   if (!Subtarget.hasStdExtZbt())
11915     return SDValue();
11916 
11917   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11918   // Besides, more critical path instructions will be generated when dividing
11919   // by 2. So we keep using the original DAGs for these cases.
11920   unsigned Lg2 = Divisor.countTrailingZeros();
11921   if (Lg2 == 1 || Lg2 >= 12)
11922     return SDValue();
11923 
11924   // fold (sdiv X, pow2)
11925   EVT VT = N->getValueType(0);
11926   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11927     return SDValue();
11928 
11929   SDLoc DL(N);
11930   SDValue N0 = N->getOperand(0);
11931   SDValue Zero = DAG.getConstant(0, DL, VT);
11932   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11933 
11934   // Add (N0 < 0) ? Pow2 - 1 : 0;
11935   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11936   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11937   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11938 
11939   Created.push_back(Cmp.getNode());
11940   Created.push_back(Add.getNode());
11941   Created.push_back(Sel.getNode());
11942 
11943   // Divide by pow2.
11944   SDValue SRA =
11945       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11946 
11947   // If we're dividing by a positive value, we're done.  Otherwise, we must
11948   // negate the result.
11949   if (Divisor.isNonNegative())
11950     return SRA;
11951 
11952   Created.push_back(SRA.getNode());
11953   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11954 }
11955 
11956 #define GET_REGISTER_MATCHER
11957 #include "RISCVGenAsmMatcher.inc"
11958 
11959 Register
11960 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11961                                        const MachineFunction &MF) const {
11962   Register Reg = MatchRegisterAltName(RegName);
11963   if (Reg == RISCV::NoRegister)
11964     Reg = MatchRegisterName(RegName);
11965   if (Reg == RISCV::NoRegister)
11966     report_fatal_error(
11967         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11968   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11969   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11970     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11971                              StringRef(RegName) + "\"."));
11972   return Reg;
11973 }
11974 
11975 namespace llvm {
11976 namespace RISCVVIntrinsicsTable {
11977 
11978 #define GET_RISCVVIntrinsicsTable_IMPL
11979 #include "RISCVGenSearchableTables.inc"
11980 
11981 } // namespace RISCVVIntrinsicsTable
11982 
11983 } // namespace llvm
11984