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     for (auto CC : FPCCToExpand)
311       setCondCodeAction(CC, MVT::f16, Expand);
312     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
313     setOperationAction(ISD::SELECT, MVT::f16, Custom);
314     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
315 
316     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
317                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
318                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
319                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
320                         ISD::FLOG2, ISD::FLOG10},
321                        MVT::f16, Promote);
322 
323     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
324     // complete support for all operations in LegalizeDAG.
325 
326     // We need to custom promote this.
327     if (Subtarget.is64Bit())
328       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
329   }
330 
331   if (Subtarget.hasStdExtF()) {
332     for (auto NT : FPLegalNodeTypes)
333       setOperationAction(NT, MVT::f32, Legal);
334     for (auto CC : FPCCToExpand)
335       setCondCodeAction(CC, MVT::f32, Expand);
336     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
337     setOperationAction(ISD::SELECT, MVT::f32, Custom);
338     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
339     for (auto Op : FPOpToExpand)
340       setOperationAction(Op, MVT::f32, Expand);
341     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
342     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
343   }
344 
345   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
346     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
347 
348   if (Subtarget.hasStdExtD()) {
349     for (auto NT : FPLegalNodeTypes)
350       setOperationAction(NT, MVT::f64, Legal);
351     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
352     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
353     for (auto CC : FPCCToExpand)
354       setCondCodeAction(CC, MVT::f64, Expand);
355     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
356     setOperationAction(ISD::SELECT, MVT::f64, Custom);
357     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
358     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
359     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
360     for (auto Op : FPOpToExpand)
361       setOperationAction(Op, MVT::f64, Expand);
362     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
363     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
364   }
365 
366   if (Subtarget.is64Bit())
367     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
368                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
369                        MVT::i32, Custom);
370 
371   if (Subtarget.hasStdExtF()) {
372     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
373                        Custom);
374 
375     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
376                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
377                        XLenVT, Legal);
378 
379     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
380     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
381   }
382 
383   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
384                       ISD::JumpTable},
385                      XLenVT, Custom);
386 
387   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
388 
389   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
390   // Unfortunately this can't be determined just from the ISA naming string.
391   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
392                      Subtarget.is64Bit() ? Legal : Custom);
393 
394   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
395   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
396   if (Subtarget.is64Bit())
397     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
398 
399   if (Subtarget.hasStdExtA()) {
400     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
401     setMinCmpXchgSizeInBits(32);
402   } else {
403     setMaxAtomicSizeInBitsSupported(0);
404   }
405 
406   setBooleanContents(ZeroOrOneBooleanContent);
407 
408   if (Subtarget.hasVInstructions()) {
409     setBooleanVectorContents(ZeroOrOneBooleanContent);
410 
411     setOperationAction(ISD::VSCALE, XLenVT, Custom);
412 
413     // RVV intrinsics may have illegal operands.
414     // We also need to custom legalize vmv.x.s.
415     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
416                        {MVT::i8, MVT::i16}, Custom);
417     if (Subtarget.is64Bit())
418       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
419     else
420       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
421                          MVT::i64, Custom);
422 
423     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
424                        MVT::Other, Custom);
425 
426     static const unsigned IntegerVPOps[] = {
427         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
428         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
429         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
430         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
431         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
432         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
433         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
434         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
435         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SEXT,
436         ISD::VP_ZEXT,        ISD::VP_TRUNC};
437 
438     static const unsigned FloatingPointVPOps[] = {
439         ISD::VP_FADD,        ISD::VP_FSUB,
440         ISD::VP_FMUL,        ISD::VP_FDIV,
441         ISD::VP_FNEG,        ISD::VP_FMA,
442         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
443         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
444         ISD::VP_MERGE,       ISD::VP_SELECT,
445         ISD::VP_SITOFP,      ISD::VP_UITOFP,
446         ISD::VP_SETCC,       ISD::VP_FP_ROUND};
447 
448     if (!Subtarget.is64Bit()) {
449       // We must custom-lower certain vXi64 operations on RV32 due to the vector
450       // element type being illegal.
451       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
452                          MVT::i64, Custom);
453 
454       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
455                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
456                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
457                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
458                          MVT::i64, Custom);
459 
460       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
461                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
462                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
463                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
464                          MVT::i64, Custom);
465     }
466 
467     for (MVT VT : BoolVecVTs) {
468       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
469 
470       // Mask VTs are custom-expanded into a series of standard nodes
471       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
472                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
473                          VT, Custom);
474 
475       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
476                          Custom);
477 
478       setOperationAction(ISD::SELECT, VT, Custom);
479       setOperationAction(
480           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
481           Expand);
482 
483       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
484 
485       setOperationAction(
486           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
487           Custom);
488 
489       setOperationAction(
490           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
491           Custom);
492 
493       // RVV has native int->float & float->int conversions where the
494       // element type sizes are within one power-of-two of each other. Any
495       // wider distances between type sizes have to be lowered as sequences
496       // which progressively narrow the gap in stages.
497       setOperationAction(
498           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
499           VT, Custom);
500 
501       // Expand all extending loads to types larger than this, and truncating
502       // stores from types larger than this.
503       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
504         setTruncStoreAction(OtherVT, VT, Expand);
505         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
506                          VT, Expand);
507       }
508 
509       setOperationAction(
510           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNC, ISD::VP_SETCC}, VT,
511           Custom);
512     }
513 
514     for (MVT VT : IntVecVTs) {
515       if (VT.getVectorElementType() == MVT::i64 &&
516           !Subtarget.hasVInstructionsI64())
517         continue;
518 
519       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
520       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
521 
522       // Vectors implement MULHS/MULHU.
523       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
524 
525       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
526       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
527         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
528 
529       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
530                          Legal);
531 
532       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
533 
534       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
535                          Expand);
536 
537       setOperationAction(ISD::BSWAP, VT, Expand);
538 
539       // Custom-lower extensions and truncations from/to mask types.
540       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
541                          VT, Custom);
542 
543       // RVV has native int->float & float->int conversions where the
544       // element type sizes are within one power-of-two of each other. Any
545       // wider distances between type sizes have to be lowered as sequences
546       // which progressively narrow the gap in stages.
547       setOperationAction(
548           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
549           VT, Custom);
550 
551       setOperationAction(
552           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
553 
554       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
555       // nodes which truncate by one power of two at a time.
556       setOperationAction(ISD::TRUNCATE, VT, Custom);
557 
558       // Custom-lower insert/extract operations to simplify patterns.
559       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
560                          Custom);
561 
562       // Custom-lower reduction operations to set up the corresponding custom
563       // nodes' operands.
564       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
565                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
566                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
567                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
568                          VT, Custom);
569 
570       for (unsigned VPOpc : IntegerVPOps)
571         setOperationAction(VPOpc, VT, Custom);
572 
573       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
574 
575       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
576                          VT, Custom);
577 
578       setOperationAction(
579           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
580           Custom);
581 
582       setOperationAction(
583           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
584           VT, Custom);
585 
586       setOperationAction(ISD::SELECT, VT, Custom);
587       setOperationAction(ISD::SELECT_CC, VT, Expand);
588 
589       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
590 
591       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
592         setTruncStoreAction(VT, OtherVT, Expand);
593         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
594                          VT, Expand);
595       }
596 
597       // Splice
598       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
599 
600       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
601       // type that can represent the value exactly.
602       if (VT.getVectorElementType() != MVT::i64) {
603         MVT FloatEltVT =
604             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
605         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
606         if (isTypeLegal(FloatVT)) {
607           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
608                              Custom);
609         }
610       }
611     }
612 
613     // Expand various CCs to best match the RVV ISA, which natively supports UNE
614     // but no other unordered comparisons, and supports all ordered comparisons
615     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
616     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
617     // and we pattern-match those back to the "original", swapping operands once
618     // more. This way we catch both operations and both "vf" and "fv" forms with
619     // fewer patterns.
620     static const ISD::CondCode VFPCCToExpand[] = {
621         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
622         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
623         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
624     };
625 
626     // Sets common operation actions on RVV floating-point vector types.
627     const auto SetCommonVFPActions = [&](MVT VT) {
628       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
629       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
630       // sizes are within one power-of-two of each other. Therefore conversions
631       // between vXf16 and vXf64 must be lowered as sequences which convert via
632       // vXf32.
633       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
634       // Custom-lower insert/extract operations to simplify patterns.
635       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
636                          Custom);
637       // Expand various condition codes (explained above).
638       for (auto CC : VFPCCToExpand)
639         setCondCodeAction(CC, VT, Expand);
640 
641       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
642 
643       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
644                          VT, Custom);
645 
646       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
647                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
648                          VT, Custom);
649 
650       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
651 
652       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
653 
654       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
655                          VT, Custom);
656 
657       setOperationAction(
658           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
659           Custom);
660 
661       setOperationAction(ISD::SELECT, VT, Custom);
662       setOperationAction(ISD::SELECT_CC, VT, Expand);
663 
664       setOperationAction(
665           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
666           VT, Custom);
667 
668       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
669 
670       for (unsigned VPOpc : FloatingPointVPOps)
671         setOperationAction(VPOpc, VT, Custom);
672     };
673 
674     // Sets common extload/truncstore actions on RVV floating-point vector
675     // types.
676     const auto SetCommonVFPExtLoadTruncStoreActions =
677         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
678           for (auto SmallVT : SmallerVTs) {
679             setTruncStoreAction(VT, SmallVT, Expand);
680             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
681           }
682         };
683 
684     if (Subtarget.hasVInstructionsF16())
685       for (MVT VT : F16VecVTs)
686         SetCommonVFPActions(VT);
687 
688     for (MVT VT : F32VecVTs) {
689       if (Subtarget.hasVInstructionsF32())
690         SetCommonVFPActions(VT);
691       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
692     }
693 
694     for (MVT VT : F64VecVTs) {
695       if (Subtarget.hasVInstructionsF64())
696         SetCommonVFPActions(VT);
697       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
698       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
699     }
700 
701     if (Subtarget.useRVVForFixedLengthVectors()) {
702       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
703         if (!useRVVForFixedLengthVectorVT(VT))
704           continue;
705 
706         // By default everything must be expanded.
707         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
708           setOperationAction(Op, VT, Expand);
709         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
710           setTruncStoreAction(VT, OtherVT, Expand);
711           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
712                            OtherVT, VT, Expand);
713         }
714 
715         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
716         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
717                            Custom);
718 
719         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
720                            Custom);
721 
722         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
723                            VT, Custom);
724 
725         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
726 
727         setOperationAction(ISD::SETCC, VT, Custom);
728 
729         setOperationAction(ISD::SELECT, VT, Custom);
730 
731         setOperationAction(ISD::TRUNCATE, VT, Custom);
732 
733         setOperationAction(ISD::BITCAST, VT, Custom);
734 
735         setOperationAction(
736             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
737             Custom);
738 
739         setOperationAction(
740             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
741             Custom);
742 
743         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
744                             ISD::FP_TO_UINT},
745                            VT, Custom);
746 
747         // Operations below are different for between masks and other vectors.
748         if (VT.getVectorElementType() == MVT::i1) {
749           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
750                               ISD::OR, ISD::XOR},
751                              VT, Custom);
752 
753           setOperationAction(
754               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNC},
755               VT, Custom);
756           continue;
757         }
758 
759         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
760         // it before type legalization for i64 vectors on RV32. It will then be
761         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
762         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
763         // improvements first.
764         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
765           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
766           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
767         }
768 
769         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
770         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
771 
772         setOperationAction(
773             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
774 
775         setOperationAction(
776             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
777             Custom);
778 
779         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
780                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
781                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
782                            VT, Custom);
783 
784         setOperationAction(
785             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
786 
787         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
788         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
789           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
790 
791         setOperationAction(
792             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
793             Custom);
794 
795         setOperationAction(ISD::VSELECT, VT, Custom);
796         setOperationAction(ISD::SELECT_CC, VT, Expand);
797 
798         setOperationAction(
799             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
800 
801         // Custom-lower reduction operations to set up the corresponding custom
802         // nodes' operands.
803         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
804                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
805                             ISD::VECREDUCE_UMIN},
806                            VT, Custom);
807 
808         for (unsigned VPOpc : IntegerVPOps)
809           setOperationAction(VPOpc, VT, Custom);
810 
811         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
812         // type that can represent the value exactly.
813         if (VT.getVectorElementType() != MVT::i64) {
814           MVT FloatEltVT =
815               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
816           EVT FloatVT =
817               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
818           if (isTypeLegal(FloatVT))
819             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
820                                Custom);
821         }
822       }
823 
824       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
825         if (!useRVVForFixedLengthVectorVT(VT))
826           continue;
827 
828         // By default everything must be expanded.
829         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
830           setOperationAction(Op, VT, Expand);
831         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
832           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
833           setTruncStoreAction(VT, OtherVT, Expand);
834         }
835 
836         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
837         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
838                            Custom);
839 
840         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
841                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
842                             ISD::EXTRACT_VECTOR_ELT},
843                            VT, Custom);
844 
845         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
846                             ISD::MGATHER, ISD::MSCATTER},
847                            VT, Custom);
848 
849         setOperationAction(
850             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
851             Custom);
852 
853         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
854                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
855                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
856                            VT, Custom);
857 
858         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
859 
860         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
861                            VT, Custom);
862 
863         for (auto CC : VFPCCToExpand)
864           setCondCodeAction(CC, VT, Expand);
865 
866         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
867         setOperationAction(ISD::SELECT_CC, VT, Expand);
868 
869         setOperationAction(ISD::BITCAST, VT, Custom);
870 
871         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
872                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
873                            VT, Custom);
874 
875         for (unsigned VPOpc : FloatingPointVPOps)
876           setOperationAction(VPOpc, VT, Custom);
877       }
878 
879       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
880       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
881                          Custom);
882       if (Subtarget.hasStdExtZfh())
883         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
884       if (Subtarget.hasStdExtF())
885         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
886       if (Subtarget.hasStdExtD())
887         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
888     }
889   }
890 
891   // Function alignments.
892   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
893   setMinFunctionAlignment(FunctionAlignment);
894   setPrefFunctionAlignment(FunctionAlignment);
895 
896   setMinimumJumpTableEntries(5);
897 
898   // Jumps are expensive, compared to logic
899   setJumpIsExpensive();
900 
901   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
902                        ISD::OR, ISD::XOR});
903 
904   if (Subtarget.hasStdExtZbp())
905     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
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   // Require a 12-bit signed offset.
1011   if (!isInt<12>(AM.BaseOffs))
1012     return false;
1013 
1014   switch (AM.Scale) {
1015   case 0: // "r+i" or just "i", depending on HasBaseReg.
1016     break;
1017   case 1:
1018     if (!AM.HasBaseReg) // allow "r+i".
1019       break;
1020     return false; // disallow "r+r" or "r+r+i".
1021   default:
1022     return false;
1023   }
1024 
1025   return true;
1026 }
1027 
1028 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1029   return isInt<12>(Imm);
1030 }
1031 
1032 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1033   return isInt<12>(Imm);
1034 }
1035 
1036 // On RV32, 64-bit integers are split into their high and low parts and held
1037 // in two different registers, so the trunc is free since the low register can
1038 // just be used.
1039 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1040   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1041     return false;
1042   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1043   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1044   return (SrcBits == 64 && DestBits == 32);
1045 }
1046 
1047 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1048   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1049       !SrcVT.isInteger() || !DstVT.isInteger())
1050     return false;
1051   unsigned SrcBits = SrcVT.getSizeInBits();
1052   unsigned DestBits = DstVT.getSizeInBits();
1053   return (SrcBits == 64 && DestBits == 32);
1054 }
1055 
1056 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1057   // Zexts are free if they can be combined with a load.
1058   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1059   // poorly with type legalization of compares preferring sext.
1060   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1061     EVT MemVT = LD->getMemoryVT();
1062     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1063         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1064          LD->getExtensionType() == ISD::ZEXTLOAD))
1065       return true;
1066   }
1067 
1068   return TargetLowering::isZExtFree(Val, VT2);
1069 }
1070 
1071 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1072   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1073 }
1074 
1075 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1076   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1077 }
1078 
1079 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1080   return Subtarget.hasStdExtZbb();
1081 }
1082 
1083 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1084   return Subtarget.hasStdExtZbb();
1085 }
1086 
1087 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1088   EVT VT = Y.getValueType();
1089 
1090   // FIXME: Support vectors once we have tests.
1091   if (VT.isVector())
1092     return false;
1093 
1094   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1095           Subtarget.hasStdExtZbkb()) &&
1096          !isa<ConstantSDNode>(Y);
1097 }
1098 
1099 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1100   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1101   auto *C = dyn_cast<ConstantSDNode>(Y);
1102   return C && C->getAPIntValue().ule(10);
1103 }
1104 
1105 /// Check if sinking \p I's operands to I's basic block is profitable, because
1106 /// the operands can be folded into a target instruction, e.g.
1107 /// splats of scalars can fold into vector instructions.
1108 bool RISCVTargetLowering::shouldSinkOperands(
1109     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1110   using namespace llvm::PatternMatch;
1111 
1112   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1113     return false;
1114 
1115   auto IsSinker = [&](Instruction *I, int Operand) {
1116     switch (I->getOpcode()) {
1117     case Instruction::Add:
1118     case Instruction::Sub:
1119     case Instruction::Mul:
1120     case Instruction::And:
1121     case Instruction::Or:
1122     case Instruction::Xor:
1123     case Instruction::FAdd:
1124     case Instruction::FSub:
1125     case Instruction::FMul:
1126     case Instruction::FDiv:
1127     case Instruction::ICmp:
1128     case Instruction::FCmp:
1129       return true;
1130     case Instruction::Shl:
1131     case Instruction::LShr:
1132     case Instruction::AShr:
1133     case Instruction::UDiv:
1134     case Instruction::SDiv:
1135     case Instruction::URem:
1136     case Instruction::SRem:
1137       return Operand == 1;
1138     case Instruction::Call:
1139       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1140         switch (II->getIntrinsicID()) {
1141         case Intrinsic::fma:
1142         case Intrinsic::vp_fma:
1143           return Operand == 0 || Operand == 1;
1144         // FIXME: Our patterns can only match vx/vf instructions when the splat
1145         // it on the RHS, because TableGen doesn't recognize our VP operations
1146         // as commutative.
1147         case Intrinsic::vp_add:
1148         case Intrinsic::vp_mul:
1149         case Intrinsic::vp_and:
1150         case Intrinsic::vp_or:
1151         case Intrinsic::vp_xor:
1152         case Intrinsic::vp_fadd:
1153         case Intrinsic::vp_fmul:
1154         case Intrinsic::vp_shl:
1155         case Intrinsic::vp_lshr:
1156         case Intrinsic::vp_ashr:
1157         case Intrinsic::vp_udiv:
1158         case Intrinsic::vp_sdiv:
1159         case Intrinsic::vp_urem:
1160         case Intrinsic::vp_srem:
1161           return Operand == 1;
1162         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1163         // explicit patterns for both LHS and RHS (as 'vr' versions).
1164         case Intrinsic::vp_sub:
1165         case Intrinsic::vp_fsub:
1166         case Intrinsic::vp_fdiv:
1167           return Operand == 0 || Operand == 1;
1168         default:
1169           return false;
1170         }
1171       }
1172       return false;
1173     default:
1174       return false;
1175     }
1176   };
1177 
1178   for (auto OpIdx : enumerate(I->operands())) {
1179     if (!IsSinker(I, OpIdx.index()))
1180       continue;
1181 
1182     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1183     // Make sure we are not already sinking this operand
1184     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1185       continue;
1186 
1187     // We are looking for a splat that can be sunk.
1188     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1189                              m_Undef(), m_ZeroMask())))
1190       continue;
1191 
1192     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1193     // and vector registers
1194     for (Use &U : Op->uses()) {
1195       Instruction *Insn = cast<Instruction>(U.getUser());
1196       if (!IsSinker(Insn, U.getOperandNo()))
1197         return false;
1198     }
1199 
1200     Ops.push_back(&Op->getOperandUse(0));
1201     Ops.push_back(&OpIdx.value());
1202   }
1203   return true;
1204 }
1205 
1206 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1207                                        bool ForCodeSize) const {
1208   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1209   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1210     return false;
1211   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1212     return false;
1213   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1214     return false;
1215   return Imm.isZero();
1216 }
1217 
1218 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1219   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1220          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1221          (VT == MVT::f64 && Subtarget.hasStdExtD());
1222 }
1223 
1224 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1225                                                       CallingConv::ID CC,
1226                                                       EVT VT) const {
1227   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1228   // We might still end up using a GPR but that will be decided based on ABI.
1229   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1230   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1231     return MVT::f32;
1232 
1233   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1234 }
1235 
1236 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1237                                                            CallingConv::ID CC,
1238                                                            EVT VT) const {
1239   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1240   // We might still end up using a GPR but that will be decided based on ABI.
1241   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1242   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1243     return 1;
1244 
1245   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1246 }
1247 
1248 // Changes the condition code and swaps operands if necessary, so the SetCC
1249 // operation matches one of the comparisons supported directly by branches
1250 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1251 // with 1/-1.
1252 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1253                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1254   // Convert X > -1 to X >= 0.
1255   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1256     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1257     CC = ISD::SETGE;
1258     return;
1259   }
1260   // Convert X < 1 to 0 >= X.
1261   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1262     RHS = LHS;
1263     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1264     CC = ISD::SETGE;
1265     return;
1266   }
1267 
1268   switch (CC) {
1269   default:
1270     break;
1271   case ISD::SETGT:
1272   case ISD::SETLE:
1273   case ISD::SETUGT:
1274   case ISD::SETULE:
1275     CC = ISD::getSetCCSwappedOperands(CC);
1276     std::swap(LHS, RHS);
1277     break;
1278   }
1279 }
1280 
1281 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1282   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1283   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1284   if (VT.getVectorElementType() == MVT::i1)
1285     KnownSize *= 8;
1286 
1287   switch (KnownSize) {
1288   default:
1289     llvm_unreachable("Invalid LMUL.");
1290   case 8:
1291     return RISCVII::VLMUL::LMUL_F8;
1292   case 16:
1293     return RISCVII::VLMUL::LMUL_F4;
1294   case 32:
1295     return RISCVII::VLMUL::LMUL_F2;
1296   case 64:
1297     return RISCVII::VLMUL::LMUL_1;
1298   case 128:
1299     return RISCVII::VLMUL::LMUL_2;
1300   case 256:
1301     return RISCVII::VLMUL::LMUL_4;
1302   case 512:
1303     return RISCVII::VLMUL::LMUL_8;
1304   }
1305 }
1306 
1307 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1308   switch (LMul) {
1309   default:
1310     llvm_unreachable("Invalid LMUL.");
1311   case RISCVII::VLMUL::LMUL_F8:
1312   case RISCVII::VLMUL::LMUL_F4:
1313   case RISCVII::VLMUL::LMUL_F2:
1314   case RISCVII::VLMUL::LMUL_1:
1315     return RISCV::VRRegClassID;
1316   case RISCVII::VLMUL::LMUL_2:
1317     return RISCV::VRM2RegClassID;
1318   case RISCVII::VLMUL::LMUL_4:
1319     return RISCV::VRM4RegClassID;
1320   case RISCVII::VLMUL::LMUL_8:
1321     return RISCV::VRM8RegClassID;
1322   }
1323 }
1324 
1325 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1326   RISCVII::VLMUL LMUL = getLMUL(VT);
1327   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1328       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1329       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1330       LMUL == RISCVII::VLMUL::LMUL_1) {
1331     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1332                   "Unexpected subreg numbering");
1333     return RISCV::sub_vrm1_0 + Index;
1334   }
1335   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1336     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1337                   "Unexpected subreg numbering");
1338     return RISCV::sub_vrm2_0 + Index;
1339   }
1340   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1341     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1342                   "Unexpected subreg numbering");
1343     return RISCV::sub_vrm4_0 + Index;
1344   }
1345   llvm_unreachable("Invalid vector type.");
1346 }
1347 
1348 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1349   if (VT.getVectorElementType() == MVT::i1)
1350     return RISCV::VRRegClassID;
1351   return getRegClassIDForLMUL(getLMUL(VT));
1352 }
1353 
1354 // Attempt to decompose a subvector insert/extract between VecVT and
1355 // SubVecVT via subregister indices. Returns the subregister index that
1356 // can perform the subvector insert/extract with the given element index, as
1357 // well as the index corresponding to any leftover subvectors that must be
1358 // further inserted/extracted within the register class for SubVecVT.
1359 std::pair<unsigned, unsigned>
1360 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1361     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1362     const RISCVRegisterInfo *TRI) {
1363   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1364                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1365                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1366                 "Register classes not ordered");
1367   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1368   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1369   // Try to compose a subregister index that takes us from the incoming
1370   // LMUL>1 register class down to the outgoing one. At each step we half
1371   // the LMUL:
1372   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1373   // Note that this is not guaranteed to find a subregister index, such as
1374   // when we are extracting from one VR type to another.
1375   unsigned SubRegIdx = RISCV::NoSubRegister;
1376   for (const unsigned RCID :
1377        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1378     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1379       VecVT = VecVT.getHalfNumVectorElementsVT();
1380       bool IsHi =
1381           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1382       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1383                                             getSubregIndexByMVT(VecVT, IsHi));
1384       if (IsHi)
1385         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1386     }
1387   return {SubRegIdx, InsertExtractIdx};
1388 }
1389 
1390 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1391 // stores for those types.
1392 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1393   return !Subtarget.useRVVForFixedLengthVectors() ||
1394          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1395 }
1396 
1397 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1398   if (ScalarTy->isPointerTy())
1399     return true;
1400 
1401   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1402       ScalarTy->isIntegerTy(32))
1403     return true;
1404 
1405   if (ScalarTy->isIntegerTy(64))
1406     return Subtarget.hasVInstructionsI64();
1407 
1408   if (ScalarTy->isHalfTy())
1409     return Subtarget.hasVInstructionsF16();
1410   if (ScalarTy->isFloatTy())
1411     return Subtarget.hasVInstructionsF32();
1412   if (ScalarTy->isDoubleTy())
1413     return Subtarget.hasVInstructionsF64();
1414 
1415   return false;
1416 }
1417 
1418 static SDValue getVLOperand(SDValue Op) {
1419   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1420           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1421          "Unexpected opcode");
1422   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1423   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1424   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1425       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1426   if (!II)
1427     return SDValue();
1428   return Op.getOperand(II->VLOperand + 1 + HasChain);
1429 }
1430 
1431 static bool useRVVForFixedLengthVectorVT(MVT VT,
1432                                          const RISCVSubtarget &Subtarget) {
1433   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1434   if (!Subtarget.useRVVForFixedLengthVectors())
1435     return false;
1436 
1437   // We only support a set of vector types with a consistent maximum fixed size
1438   // across all supported vector element types to avoid legalization issues.
1439   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1440   // fixed-length vector type we support is 1024 bytes.
1441   if (VT.getFixedSizeInBits() > 1024 * 8)
1442     return false;
1443 
1444   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1445 
1446   MVT EltVT = VT.getVectorElementType();
1447 
1448   // Don't use RVV for vectors we cannot scalarize if required.
1449   switch (EltVT.SimpleTy) {
1450   // i1 is supported but has different rules.
1451   default:
1452     return false;
1453   case MVT::i1:
1454     // Masks can only use a single register.
1455     if (VT.getVectorNumElements() > MinVLen)
1456       return false;
1457     MinVLen /= 8;
1458     break;
1459   case MVT::i8:
1460   case MVT::i16:
1461   case MVT::i32:
1462     break;
1463   case MVT::i64:
1464     if (!Subtarget.hasVInstructionsI64())
1465       return false;
1466     break;
1467   case MVT::f16:
1468     if (!Subtarget.hasVInstructionsF16())
1469       return false;
1470     break;
1471   case MVT::f32:
1472     if (!Subtarget.hasVInstructionsF32())
1473       return false;
1474     break;
1475   case MVT::f64:
1476     if (!Subtarget.hasVInstructionsF64())
1477       return false;
1478     break;
1479   }
1480 
1481   // Reject elements larger than ELEN.
1482   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1483     return false;
1484 
1485   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1486   // Don't use RVV for types that don't fit.
1487   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1488     return false;
1489 
1490   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1491   // the base fixed length RVV support in place.
1492   if (!VT.isPow2VectorType())
1493     return false;
1494 
1495   return true;
1496 }
1497 
1498 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1499   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1500 }
1501 
1502 // Return the largest legal scalable vector type that matches VT's element type.
1503 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1504                                             const RISCVSubtarget &Subtarget) {
1505   // This may be called before legal types are setup.
1506   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1507           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1508          "Expected legal fixed length vector!");
1509 
1510   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1511   unsigned MaxELen = Subtarget.getELEN();
1512 
1513   MVT EltVT = VT.getVectorElementType();
1514   switch (EltVT.SimpleTy) {
1515   default:
1516     llvm_unreachable("unexpected element type for RVV container");
1517   case MVT::i1:
1518   case MVT::i8:
1519   case MVT::i16:
1520   case MVT::i32:
1521   case MVT::i64:
1522   case MVT::f16:
1523   case MVT::f32:
1524   case MVT::f64: {
1525     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1526     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1527     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1528     unsigned NumElts =
1529         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1530     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1531     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1532     return MVT::getScalableVectorVT(EltVT, NumElts);
1533   }
1534   }
1535 }
1536 
1537 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1538                                             const RISCVSubtarget &Subtarget) {
1539   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1540                                           Subtarget);
1541 }
1542 
1543 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1544   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1545 }
1546 
1547 // Grow V to consume an entire RVV register.
1548 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1549                                        const RISCVSubtarget &Subtarget) {
1550   assert(VT.isScalableVector() &&
1551          "Expected to convert into a scalable vector!");
1552   assert(V.getValueType().isFixedLengthVector() &&
1553          "Expected a fixed length vector operand!");
1554   SDLoc DL(V);
1555   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1556   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1557 }
1558 
1559 // Shrink V so it's just big enough to maintain a VT's worth of data.
1560 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1561                                          const RISCVSubtarget &Subtarget) {
1562   assert(VT.isFixedLengthVector() &&
1563          "Expected to convert into a fixed length vector!");
1564   assert(V.getValueType().isScalableVector() &&
1565          "Expected a scalable vector operand!");
1566   SDLoc DL(V);
1567   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1568   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1569 }
1570 
1571 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1572 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1573 // the vector type that it is contained in.
1574 static std::pair<SDValue, SDValue>
1575 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1576                 const RISCVSubtarget &Subtarget) {
1577   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1578   MVT XLenVT = Subtarget.getXLenVT();
1579   SDValue VL = VecVT.isFixedLengthVector()
1580                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1581                    : DAG.getRegister(RISCV::X0, XLenVT);
1582   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1583   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1584   return {Mask, VL};
1585 }
1586 
1587 // As above but assuming the given type is a scalable vector type.
1588 static std::pair<SDValue, SDValue>
1589 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1590                         const RISCVSubtarget &Subtarget) {
1591   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1592   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1593 }
1594 
1595 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1596 // of either is (currently) supported. This can get us into an infinite loop
1597 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1598 // as a ..., etc.
1599 // Until either (or both) of these can reliably lower any node, reporting that
1600 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1601 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1602 // which is not desirable.
1603 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1604     EVT VT, unsigned DefinedValues) const {
1605   return false;
1606 }
1607 
1608 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1609                                   const RISCVSubtarget &Subtarget) {
1610   // RISCV FP-to-int conversions saturate to the destination register size, but
1611   // don't produce 0 for nan. We can use a conversion instruction and fix the
1612   // nan case with a compare and a select.
1613   SDValue Src = Op.getOperand(0);
1614 
1615   EVT DstVT = Op.getValueType();
1616   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1617 
1618   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1619   unsigned Opc;
1620   if (SatVT == DstVT)
1621     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1622   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1623     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1624   else
1625     return SDValue();
1626   // FIXME: Support other SatVTs by clamping before or after the conversion.
1627 
1628   SDLoc DL(Op);
1629   SDValue FpToInt = DAG.getNode(
1630       Opc, DL, DstVT, Src,
1631       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1632 
1633   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1634   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1635 }
1636 
1637 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1638 // and back. Taking care to avoid converting values that are nan or already
1639 // correct.
1640 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1641 // have FRM dependencies modeled yet.
1642 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1643   MVT VT = Op.getSimpleValueType();
1644   assert(VT.isVector() && "Unexpected type");
1645 
1646   SDLoc DL(Op);
1647 
1648   // Freeze the source since we are increasing the number of uses.
1649   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1650 
1651   // Truncate to integer and convert back to FP.
1652   MVT IntVT = VT.changeVectorElementTypeToInteger();
1653   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1654   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1655 
1656   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1657 
1658   if (Op.getOpcode() == ISD::FCEIL) {
1659     // If the truncated value is the greater than or equal to the original
1660     // value, we've computed the ceil. Otherwise, we went the wrong way and
1661     // need to increase by 1.
1662     // FIXME: This should use a masked operation. Handle here or in isel?
1663     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1664                                  DAG.getConstantFP(1.0, DL, VT));
1665     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1666     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1667   } else if (Op.getOpcode() == ISD::FFLOOR) {
1668     // If the truncated value is the less than or equal to the original value,
1669     // we've computed the floor. Otherwise, we went the wrong way and need to
1670     // decrease by 1.
1671     // FIXME: This should use a masked operation. Handle here or in isel?
1672     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1673                                  DAG.getConstantFP(1.0, DL, VT));
1674     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1675     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1676   }
1677 
1678   // Restore the original sign so that -0.0 is preserved.
1679   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1680 
1681   // Determine the largest integer that can be represented exactly. This and
1682   // values larger than it don't have any fractional bits so don't need to
1683   // be converted.
1684   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1685   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1686   APFloat MaxVal = APFloat(FltSem);
1687   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1688                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1689   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1690 
1691   // If abs(Src) was larger than MaxVal or nan, keep it.
1692   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1693   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1694   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1695 }
1696 
1697 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1698 // This mode isn't supported in vector hardware on RISCV. But as long as we
1699 // aren't compiling with trapping math, we can emulate this with
1700 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1701 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1702 // dependencies modeled yet.
1703 // FIXME: Use masked operations to avoid final merge.
1704 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1705   MVT VT = Op.getSimpleValueType();
1706   assert(VT.isVector() && "Unexpected type");
1707 
1708   SDLoc DL(Op);
1709 
1710   // Freeze the source since we are increasing the number of uses.
1711   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1712 
1713   // We do the conversion on the absolute value and fix the sign at the end.
1714   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1715 
1716   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1717   bool Ignored;
1718   APFloat Point5Pred = APFloat(0.5f);
1719   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1720   Point5Pred.next(/*nextDown*/ true);
1721 
1722   // Add the adjustment.
1723   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1724                                DAG.getConstantFP(Point5Pred, DL, VT));
1725 
1726   // Truncate to integer and convert back to fp.
1727   MVT IntVT = VT.changeVectorElementTypeToInteger();
1728   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1729   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1730 
1731   // Restore the original sign.
1732   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1733 
1734   // Determine the largest integer that can be represented exactly. This and
1735   // values larger than it don't have any fractional bits so don't need to
1736   // be converted.
1737   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1738   APFloat MaxVal = APFloat(FltSem);
1739   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1740                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1741   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1742 
1743   // If abs(Src) was larger than MaxVal or nan, keep it.
1744   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1745   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1746   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1747 }
1748 
1749 struct VIDSequence {
1750   int64_t StepNumerator;
1751   unsigned StepDenominator;
1752   int64_t Addend;
1753 };
1754 
1755 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1756 // to the (non-zero) step S and start value X. This can be then lowered as the
1757 // RVV sequence (VID * S) + X, for example.
1758 // The step S is represented as an integer numerator divided by a positive
1759 // denominator. Note that the implementation currently only identifies
1760 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1761 // cannot detect 2/3, for example.
1762 // Note that this method will also match potentially unappealing index
1763 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1764 // determine whether this is worth generating code for.
1765 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1766   unsigned NumElts = Op.getNumOperands();
1767   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1768   if (!Op.getValueType().isInteger())
1769     return None;
1770 
1771   Optional<unsigned> SeqStepDenom;
1772   Optional<int64_t> SeqStepNum, SeqAddend;
1773   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1774   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1775   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1776     // Assume undef elements match the sequence; we just have to be careful
1777     // when interpolating across them.
1778     if (Op.getOperand(Idx).isUndef())
1779       continue;
1780     // The BUILD_VECTOR must be all constants.
1781     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1782       return None;
1783 
1784     uint64_t Val = Op.getConstantOperandVal(Idx) &
1785                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1786 
1787     if (PrevElt) {
1788       // Calculate the step since the last non-undef element, and ensure
1789       // it's consistent across the entire sequence.
1790       unsigned IdxDiff = Idx - PrevElt->second;
1791       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1792 
1793       // A zero-value value difference means that we're somewhere in the middle
1794       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1795       // step change before evaluating the sequence.
1796       if (ValDiff == 0)
1797         continue;
1798 
1799       int64_t Remainder = ValDiff % IdxDiff;
1800       // Normalize the step if it's greater than 1.
1801       if (Remainder != ValDiff) {
1802         // The difference must cleanly divide the element span.
1803         if (Remainder != 0)
1804           return None;
1805         ValDiff /= IdxDiff;
1806         IdxDiff = 1;
1807       }
1808 
1809       if (!SeqStepNum)
1810         SeqStepNum = ValDiff;
1811       else if (ValDiff != SeqStepNum)
1812         return None;
1813 
1814       if (!SeqStepDenom)
1815         SeqStepDenom = IdxDiff;
1816       else if (IdxDiff != *SeqStepDenom)
1817         return None;
1818     }
1819 
1820     // Record this non-undef element for later.
1821     if (!PrevElt || PrevElt->first != Val)
1822       PrevElt = std::make_pair(Val, Idx);
1823   }
1824 
1825   // We need to have logged a step for this to count as a legal index sequence.
1826   if (!SeqStepNum || !SeqStepDenom)
1827     return None;
1828 
1829   // Loop back through the sequence and validate elements we might have skipped
1830   // while waiting for a valid step. While doing this, log any sequence addend.
1831   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1832     if (Op.getOperand(Idx).isUndef())
1833       continue;
1834     uint64_t Val = Op.getConstantOperandVal(Idx) &
1835                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1836     uint64_t ExpectedVal =
1837         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1838     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1839     if (!SeqAddend)
1840       SeqAddend = Addend;
1841     else if (Addend != SeqAddend)
1842       return None;
1843   }
1844 
1845   assert(SeqAddend && "Must have an addend if we have a step");
1846 
1847   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1848 }
1849 
1850 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1851 // and lower it as a VRGATHER_VX_VL from the source vector.
1852 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1853                                   SelectionDAG &DAG,
1854                                   const RISCVSubtarget &Subtarget) {
1855   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1856     return SDValue();
1857   SDValue Vec = SplatVal.getOperand(0);
1858   // Only perform this optimization on vectors of the same size for simplicity.
1859   if (Vec.getValueType() != VT)
1860     return SDValue();
1861   SDValue Idx = SplatVal.getOperand(1);
1862   // The index must be a legal type.
1863   if (Idx.getValueType() != Subtarget.getXLenVT())
1864     return SDValue();
1865 
1866   MVT ContainerVT = VT;
1867   if (VT.isFixedLengthVector()) {
1868     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1869     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1870   }
1871 
1872   SDValue Mask, VL;
1873   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1874 
1875   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
1876                                Idx, Mask, VL);
1877 
1878   if (!VT.isFixedLengthVector())
1879     return Gather;
1880 
1881   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1882 }
1883 
1884 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1885                                  const RISCVSubtarget &Subtarget) {
1886   MVT VT = Op.getSimpleValueType();
1887   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1888 
1889   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1890 
1891   SDLoc DL(Op);
1892   SDValue Mask, VL;
1893   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1894 
1895   MVT XLenVT = Subtarget.getXLenVT();
1896   unsigned NumElts = Op.getNumOperands();
1897 
1898   if (VT.getVectorElementType() == MVT::i1) {
1899     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1900       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1901       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1902     }
1903 
1904     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1905       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1906       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1907     }
1908 
1909     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1910     // scalar integer chunks whose bit-width depends on the number of mask
1911     // bits and XLEN.
1912     // First, determine the most appropriate scalar integer type to use. This
1913     // is at most XLenVT, but may be shrunk to a smaller vector element type
1914     // according to the size of the final vector - use i8 chunks rather than
1915     // XLenVT if we're producing a v8i1. This results in more consistent
1916     // codegen across RV32 and RV64.
1917     unsigned NumViaIntegerBits =
1918         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1919     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
1920     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1921       // If we have to use more than one INSERT_VECTOR_ELT then this
1922       // optimization is likely to increase code size; avoid peforming it in
1923       // such a case. We can use a load from a constant pool in this case.
1924       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1925         return SDValue();
1926       // Now we can create our integer vector type. Note that it may be larger
1927       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1928       MVT IntegerViaVecVT =
1929           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1930                            divideCeil(NumElts, NumViaIntegerBits));
1931 
1932       uint64_t Bits = 0;
1933       unsigned BitPos = 0, IntegerEltIdx = 0;
1934       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1935 
1936       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1937         // Once we accumulate enough bits to fill our scalar type, insert into
1938         // our vector and clear our accumulated data.
1939         if (I != 0 && I % NumViaIntegerBits == 0) {
1940           if (NumViaIntegerBits <= 32)
1941             Bits = SignExtend64(Bits, 32);
1942           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1943           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1944                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1945           Bits = 0;
1946           BitPos = 0;
1947           IntegerEltIdx++;
1948         }
1949         SDValue V = Op.getOperand(I);
1950         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1951         Bits |= ((uint64_t)BitValue << BitPos);
1952       }
1953 
1954       // Insert the (remaining) scalar value into position in our integer
1955       // vector type.
1956       if (NumViaIntegerBits <= 32)
1957         Bits = SignExtend64(Bits, 32);
1958       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1959       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1960                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1961 
1962       if (NumElts < NumViaIntegerBits) {
1963         // If we're producing a smaller vector than our minimum legal integer
1964         // type, bitcast to the equivalent (known-legal) mask type, and extract
1965         // our final mask.
1966         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1967         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1968         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1969                           DAG.getConstant(0, DL, XLenVT));
1970       } else {
1971         // Else we must have produced an integer type with the same size as the
1972         // mask type; bitcast for the final result.
1973         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1974         Vec = DAG.getBitcast(VT, Vec);
1975       }
1976 
1977       return Vec;
1978     }
1979 
1980     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1981     // vector type, we have a legal equivalently-sized i8 type, so we can use
1982     // that.
1983     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1984     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1985 
1986     SDValue WideVec;
1987     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1988       // For a splat, perform a scalar truncate before creating the wider
1989       // vector.
1990       assert(Splat.getValueType() == XLenVT &&
1991              "Unexpected type for i1 splat value");
1992       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1993                           DAG.getConstant(1, DL, XLenVT));
1994       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1995     } else {
1996       SmallVector<SDValue, 8> Ops(Op->op_values());
1997       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1998       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1999       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2000     }
2001 
2002     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2003   }
2004 
2005   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2006     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2007       return Gather;
2008     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2009                                         : RISCVISD::VMV_V_X_VL;
2010     Splat =
2011         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2012     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2013   }
2014 
2015   // Try and match index sequences, which we can lower to the vid instruction
2016   // with optional modifications. An all-undef vector is matched by
2017   // getSplatValue, above.
2018   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2019     int64_t StepNumerator = SimpleVID->StepNumerator;
2020     unsigned StepDenominator = SimpleVID->StepDenominator;
2021     int64_t Addend = SimpleVID->Addend;
2022 
2023     assert(StepNumerator != 0 && "Invalid step");
2024     bool Negate = false;
2025     int64_t SplatStepVal = StepNumerator;
2026     unsigned StepOpcode = ISD::MUL;
2027     if (StepNumerator != 1) {
2028       if (isPowerOf2_64(std::abs(StepNumerator))) {
2029         Negate = StepNumerator < 0;
2030         StepOpcode = ISD::SHL;
2031         SplatStepVal = Log2_64(std::abs(StepNumerator));
2032       }
2033     }
2034 
2035     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2036     // threshold since it's the immediate value many RVV instructions accept.
2037     // There is no vmul.vi instruction so ensure multiply constant can fit in
2038     // a single addi instruction.
2039     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2040          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2041         isPowerOf2_32(StepDenominator) &&
2042         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2043       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2044       // Convert right out of the scalable type so we can use standard ISD
2045       // nodes for the rest of the computation. If we used scalable types with
2046       // these, we'd lose the fixed-length vector info and generate worse
2047       // vsetvli code.
2048       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2049       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2050           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2051         SDValue SplatStep = DAG.getSplatBuildVector(
2052             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2053         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2054       }
2055       if (StepDenominator != 1) {
2056         SDValue SplatStep = DAG.getSplatBuildVector(
2057             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2058         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2059       }
2060       if (Addend != 0 || Negate) {
2061         SDValue SplatAddend = DAG.getSplatBuildVector(
2062             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2063         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2064       }
2065       return VID;
2066     }
2067   }
2068 
2069   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2070   // when re-interpreted as a vector with a larger element type. For example,
2071   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2072   // could be instead splat as
2073   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2074   // TODO: This optimization could also work on non-constant splats, but it
2075   // would require bit-manipulation instructions to construct the splat value.
2076   SmallVector<SDValue> Sequence;
2077   unsigned EltBitSize = VT.getScalarSizeInBits();
2078   const auto *BV = cast<BuildVectorSDNode>(Op);
2079   if (VT.isInteger() && EltBitSize < 64 &&
2080       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2081       BV->getRepeatedSequence(Sequence) &&
2082       (Sequence.size() * EltBitSize) <= 64) {
2083     unsigned SeqLen = Sequence.size();
2084     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2085     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2086     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2087             ViaIntVT == MVT::i64) &&
2088            "Unexpected sequence type");
2089 
2090     unsigned EltIdx = 0;
2091     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2092     uint64_t SplatValue = 0;
2093     // Construct the amalgamated value which can be splatted as this larger
2094     // vector type.
2095     for (const auto &SeqV : Sequence) {
2096       if (!SeqV.isUndef())
2097         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2098                        << (EltIdx * EltBitSize));
2099       EltIdx++;
2100     }
2101 
2102     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2103     // achieve better constant materializion.
2104     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2105       SplatValue = SignExtend64(SplatValue, 32);
2106 
2107     // Since we can't introduce illegal i64 types at this stage, we can only
2108     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2109     // way we can use RVV instructions to splat.
2110     assert((ViaIntVT.bitsLE(XLenVT) ||
2111             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2112            "Unexpected bitcast sequence");
2113     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2114       SDValue ViaVL =
2115           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2116       MVT ViaContainerVT =
2117           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2118       SDValue Splat =
2119           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2120                       DAG.getUNDEF(ViaContainerVT),
2121                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2122       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2123       return DAG.getBitcast(VT, Splat);
2124     }
2125   }
2126 
2127   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2128   // which constitute a large proportion of the elements. In such cases we can
2129   // splat a vector with the dominant element and make up the shortfall with
2130   // INSERT_VECTOR_ELTs.
2131   // Note that this includes vectors of 2 elements by association. The
2132   // upper-most element is the "dominant" one, allowing us to use a splat to
2133   // "insert" the upper element, and an insert of the lower element at position
2134   // 0, which improves codegen.
2135   SDValue DominantValue;
2136   unsigned MostCommonCount = 0;
2137   DenseMap<SDValue, unsigned> ValueCounts;
2138   unsigned NumUndefElts =
2139       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2140 
2141   // Track the number of scalar loads we know we'd be inserting, estimated as
2142   // any non-zero floating-point constant. Other kinds of element are either
2143   // already in registers or are materialized on demand. The threshold at which
2144   // a vector load is more desirable than several scalar materializion and
2145   // vector-insertion instructions is not known.
2146   unsigned NumScalarLoads = 0;
2147 
2148   for (SDValue V : Op->op_values()) {
2149     if (V.isUndef())
2150       continue;
2151 
2152     ValueCounts.insert(std::make_pair(V, 0));
2153     unsigned &Count = ValueCounts[V];
2154 
2155     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2156       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2157 
2158     // Is this value dominant? In case of a tie, prefer the highest element as
2159     // it's cheaper to insert near the beginning of a vector than it is at the
2160     // end.
2161     if (++Count >= MostCommonCount) {
2162       DominantValue = V;
2163       MostCommonCount = Count;
2164     }
2165   }
2166 
2167   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2168   unsigned NumDefElts = NumElts - NumUndefElts;
2169   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2170 
2171   // Don't perform this optimization when optimizing for size, since
2172   // materializing elements and inserting them tends to cause code bloat.
2173   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2174       ((MostCommonCount > DominantValueCountThreshold) ||
2175        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2176     // Start by splatting the most common element.
2177     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2178 
2179     DenseSet<SDValue> Processed{DominantValue};
2180     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2181     for (const auto &OpIdx : enumerate(Op->ops())) {
2182       const SDValue &V = OpIdx.value();
2183       if (V.isUndef() || !Processed.insert(V).second)
2184         continue;
2185       if (ValueCounts[V] == 1) {
2186         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2187                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2188       } else {
2189         // Blend in all instances of this value using a VSELECT, using a
2190         // mask where each bit signals whether that element is the one
2191         // we're after.
2192         SmallVector<SDValue> Ops;
2193         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2194           return DAG.getConstant(V == V1, DL, XLenVT);
2195         });
2196         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2197                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2198                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2199       }
2200     }
2201 
2202     return Vec;
2203   }
2204 
2205   return SDValue();
2206 }
2207 
2208 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2209                                    SDValue Lo, SDValue Hi, SDValue VL,
2210                                    SelectionDAG &DAG) {
2211   if (!Passthru)
2212     Passthru = DAG.getUNDEF(VT);
2213   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2214     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2215     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2216     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2217     // node in order to try and match RVV vector/scalar instructions.
2218     if ((LoC >> 31) == HiC)
2219       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2220 
2221     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2222     // vmv.v.x whose EEW = 32 to lower it.
2223     auto *Const = dyn_cast<ConstantSDNode>(VL);
2224     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2225       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2226       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2227       // access the subtarget here now.
2228       auto InterVec = DAG.getNode(
2229           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2230                                   DAG.getRegister(RISCV::X0, MVT::i32));
2231       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2232     }
2233   }
2234 
2235   // Fall back to a stack store and stride x0 vector load.
2236   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2237                      Hi, VL);
2238 }
2239 
2240 // Called by type legalization to handle splat of i64 on RV32.
2241 // FIXME: We can optimize this when the type has sign or zero bits in one
2242 // of the halves.
2243 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2244                                    SDValue Scalar, SDValue VL,
2245                                    SelectionDAG &DAG) {
2246   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2247   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2248                            DAG.getConstant(0, DL, MVT::i32));
2249   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2250                            DAG.getConstant(1, DL, MVT::i32));
2251   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2252 }
2253 
2254 // This function lowers a splat of a scalar operand Splat with the vector
2255 // length VL. It ensures the final sequence is type legal, which is useful when
2256 // lowering a splat after type legalization.
2257 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2258                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2259                                 const RISCVSubtarget &Subtarget) {
2260   bool HasPassthru = Passthru && !Passthru.isUndef();
2261   if (!HasPassthru && !Passthru)
2262     Passthru = DAG.getUNDEF(VT);
2263   if (VT.isFloatingPoint()) {
2264     // If VL is 1, we could use vfmv.s.f.
2265     if (isOneConstant(VL))
2266       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2267     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2268   }
2269 
2270   MVT XLenVT = Subtarget.getXLenVT();
2271 
2272   // Simplest case is that the operand needs to be promoted to XLenVT.
2273   if (Scalar.getValueType().bitsLE(XLenVT)) {
2274     // If the operand is a constant, sign extend to increase our chances
2275     // of being able to use a .vi instruction. ANY_EXTEND would become a
2276     // a zero extend and the simm5 check in isel would fail.
2277     // FIXME: Should we ignore the upper bits in isel instead?
2278     unsigned ExtOpc =
2279         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2280     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2281     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2282     // If VL is 1 and the scalar value won't benefit from immediate, we could
2283     // use vmv.s.x.
2284     if (isOneConstant(VL) &&
2285         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2286       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2287     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2288   }
2289 
2290   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2291          "Unexpected scalar for splat lowering!");
2292 
2293   if (isOneConstant(VL) && isNullConstant(Scalar))
2294     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2295                        DAG.getConstant(0, DL, XLenVT), VL);
2296 
2297   // Otherwise use the more complicated splatting algorithm.
2298   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2299 }
2300 
2301 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2302                                 const RISCVSubtarget &Subtarget) {
2303   // We need to be able to widen elements to the next larger integer type.
2304   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2305     return false;
2306 
2307   int Size = Mask.size();
2308   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2309 
2310   int Srcs[] = {-1, -1};
2311   for (int i = 0; i != Size; ++i) {
2312     // Ignore undef elements.
2313     if (Mask[i] < 0)
2314       continue;
2315 
2316     // Is this an even or odd element.
2317     int Pol = i % 2;
2318 
2319     // Ensure we consistently use the same source for this element polarity.
2320     int Src = Mask[i] / Size;
2321     if (Srcs[Pol] < 0)
2322       Srcs[Pol] = Src;
2323     if (Srcs[Pol] != Src)
2324       return false;
2325 
2326     // Make sure the element within the source is appropriate for this element
2327     // in the destination.
2328     int Elt = Mask[i] % Size;
2329     if (Elt != i / 2)
2330       return false;
2331   }
2332 
2333   // We need to find a source for each polarity and they can't be the same.
2334   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2335     return false;
2336 
2337   // Swap the sources if the second source was in the even polarity.
2338   SwapSources = Srcs[0] > Srcs[1];
2339 
2340   return true;
2341 }
2342 
2343 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2344 /// and then extract the original number of elements from the rotated result.
2345 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2346 /// returned rotation amount is for a rotate right, where elements move from
2347 /// higher elements to lower elements. \p LoSrc indicates the first source
2348 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2349 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2350 /// 0 or 1 if a rotation is found.
2351 ///
2352 /// NOTE: We talk about rotate to the right which matches how bit shift and
2353 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2354 /// and the table below write vectors with the lowest elements on the left.
2355 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2356   int Size = Mask.size();
2357 
2358   // We need to detect various ways of spelling a rotation:
2359   //   [11, 12, 13, 14, 15,  0,  1,  2]
2360   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2361   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2362   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2363   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2364   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2365   int Rotation = 0;
2366   LoSrc = -1;
2367   HiSrc = -1;
2368   for (int i = 0; i != Size; ++i) {
2369     int M = Mask[i];
2370     if (M < 0)
2371       continue;
2372 
2373     // Determine where a rotate vector would have started.
2374     int StartIdx = i - (M % Size);
2375     // The identity rotation isn't interesting, stop.
2376     if (StartIdx == 0)
2377       return -1;
2378 
2379     // If we found the tail of a vector the rotation must be the missing
2380     // front. If we found the head of a vector, it must be how much of the
2381     // head.
2382     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2383 
2384     if (Rotation == 0)
2385       Rotation = CandidateRotation;
2386     else if (Rotation != CandidateRotation)
2387       // The rotations don't match, so we can't match this mask.
2388       return -1;
2389 
2390     // Compute which value this mask is pointing at.
2391     int MaskSrc = M < Size ? 0 : 1;
2392 
2393     // Compute which of the two target values this index should be assigned to.
2394     // This reflects whether the high elements are remaining or the low elemnts
2395     // are remaining.
2396     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2397 
2398     // Either set up this value if we've not encountered it before, or check
2399     // that it remains consistent.
2400     if (TargetSrc < 0)
2401       TargetSrc = MaskSrc;
2402     else if (TargetSrc != MaskSrc)
2403       // This may be a rotation, but it pulls from the inputs in some
2404       // unsupported interleaving.
2405       return -1;
2406   }
2407 
2408   // Check that we successfully analyzed the mask, and normalize the results.
2409   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2410   assert((LoSrc >= 0 || HiSrc >= 0) &&
2411          "Failed to find a rotated input vector!");
2412 
2413   return Rotation;
2414 }
2415 
2416 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2417                                    const RISCVSubtarget &Subtarget) {
2418   SDValue V1 = Op.getOperand(0);
2419   SDValue V2 = Op.getOperand(1);
2420   SDLoc DL(Op);
2421   MVT XLenVT = Subtarget.getXLenVT();
2422   MVT VT = Op.getSimpleValueType();
2423   unsigned NumElts = VT.getVectorNumElements();
2424   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2425 
2426   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2427 
2428   SDValue TrueMask, VL;
2429   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2430 
2431   if (SVN->isSplat()) {
2432     const int Lane = SVN->getSplatIndex();
2433     if (Lane >= 0) {
2434       MVT SVT = VT.getVectorElementType();
2435 
2436       // Turn splatted vector load into a strided load with an X0 stride.
2437       SDValue V = V1;
2438       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2439       // with undef.
2440       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2441       int Offset = Lane;
2442       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2443         int OpElements =
2444             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2445         V = V.getOperand(Offset / OpElements);
2446         Offset %= OpElements;
2447       }
2448 
2449       // We need to ensure the load isn't atomic or volatile.
2450       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2451         auto *Ld = cast<LoadSDNode>(V);
2452         Offset *= SVT.getStoreSize();
2453         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2454                                                    TypeSize::Fixed(Offset), DL);
2455 
2456         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2457         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2458           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2459           SDValue IntID =
2460               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2461           SDValue Ops[] = {Ld->getChain(),
2462                            IntID,
2463                            DAG.getUNDEF(ContainerVT),
2464                            NewAddr,
2465                            DAG.getRegister(RISCV::X0, XLenVT),
2466                            VL};
2467           SDValue NewLoad = DAG.getMemIntrinsicNode(
2468               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2469               DAG.getMachineFunction().getMachineMemOperand(
2470                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2471           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2472           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2473         }
2474 
2475         // Otherwise use a scalar load and splat. This will give the best
2476         // opportunity to fold a splat into the operation. ISel can turn it into
2477         // the x0 strided load if we aren't able to fold away the select.
2478         if (SVT.isFloatingPoint())
2479           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2480                           Ld->getPointerInfo().getWithOffset(Offset),
2481                           Ld->getOriginalAlign(),
2482                           Ld->getMemOperand()->getFlags());
2483         else
2484           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2485                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2486                              Ld->getOriginalAlign(),
2487                              Ld->getMemOperand()->getFlags());
2488         DAG.makeEquivalentMemoryOrdering(Ld, V);
2489 
2490         unsigned Opc =
2491             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2492         SDValue Splat =
2493             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2494         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2495       }
2496 
2497       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2498       assert(Lane < (int)NumElts && "Unexpected lane!");
2499       SDValue Gather =
2500           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2501                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2502       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2503     }
2504   }
2505 
2506   ArrayRef<int> Mask = SVN->getMask();
2507 
2508   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2509   // be undef which can be handled with a single SLIDEDOWN/UP.
2510   int LoSrc, HiSrc;
2511   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2512   if (Rotation > 0) {
2513     SDValue LoV, HiV;
2514     if (LoSrc >= 0) {
2515       LoV = LoSrc == 0 ? V1 : V2;
2516       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2517     }
2518     if (HiSrc >= 0) {
2519       HiV = HiSrc == 0 ? V1 : V2;
2520       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2521     }
2522 
2523     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2524     // to slide LoV up by (NumElts - Rotation).
2525     unsigned InvRotate = NumElts - Rotation;
2526 
2527     SDValue Res = DAG.getUNDEF(ContainerVT);
2528     if (HiV) {
2529       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2530       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2531       // causes multiple vsetvlis in some test cases such as lowering
2532       // reduce.mul
2533       SDValue DownVL = VL;
2534       if (LoV)
2535         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2536       Res =
2537           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2538                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2539     }
2540     if (LoV)
2541       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2542                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2543 
2544     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2545   }
2546 
2547   // Detect an interleave shuffle and lower to
2548   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2549   bool SwapSources;
2550   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2551     // Swap sources if needed.
2552     if (SwapSources)
2553       std::swap(V1, V2);
2554 
2555     // Extract the lower half of the vectors.
2556     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2557     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2558                      DAG.getConstant(0, DL, XLenVT));
2559     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2560                      DAG.getConstant(0, DL, XLenVT));
2561 
2562     // Double the element width and halve the number of elements in an int type.
2563     unsigned EltBits = VT.getScalarSizeInBits();
2564     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2565     MVT WideIntVT =
2566         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2567     // Convert this to a scalable vector. We need to base this on the
2568     // destination size to ensure there's always a type with a smaller LMUL.
2569     MVT WideIntContainerVT =
2570         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2571 
2572     // Convert sources to scalable vectors with the same element count as the
2573     // larger type.
2574     MVT HalfContainerVT = MVT::getVectorVT(
2575         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2576     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2577     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2578 
2579     // Cast sources to integer.
2580     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2581     MVT IntHalfVT =
2582         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2583     V1 = DAG.getBitcast(IntHalfVT, V1);
2584     V2 = DAG.getBitcast(IntHalfVT, V2);
2585 
2586     // Freeze V2 since we use it twice and we need to be sure that the add and
2587     // multiply see the same value.
2588     V2 = DAG.getFreeze(V2);
2589 
2590     // Recreate TrueMask using the widened type's element count.
2591     MVT MaskVT =
2592         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2593     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2594 
2595     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2596     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2597                               V2, TrueMask, VL);
2598     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2599     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2600                                      DAG.getUNDEF(IntHalfVT),
2601                                      DAG.getAllOnesConstant(DL, XLenVT));
2602     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2603                                    V2, Multiplier, TrueMask, VL);
2604     // Add the new copies to our previous addition giving us 2^eltbits copies of
2605     // V2. This is equivalent to shifting V2 left by eltbits. This should
2606     // combine with the vwmulu.vv above to form vwmaccu.vv.
2607     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2608                       TrueMask, VL);
2609     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2610     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2611     // vector VT.
2612     ContainerVT =
2613         MVT::getVectorVT(VT.getVectorElementType(),
2614                          WideIntContainerVT.getVectorElementCount() * 2);
2615     Add = DAG.getBitcast(ContainerVT, Add);
2616     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2617   }
2618 
2619   // Detect shuffles which can be re-expressed as vector selects; these are
2620   // shuffles in which each element in the destination is taken from an element
2621   // at the corresponding index in either source vectors.
2622   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2623     int MaskIndex = MaskIdx.value();
2624     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2625   });
2626 
2627   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2628 
2629   SmallVector<SDValue> MaskVals;
2630   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2631   // merged with a second vrgather.
2632   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2633 
2634   // By default we preserve the original operand order, and use a mask to
2635   // select LHS as true and RHS as false. However, since RVV vector selects may
2636   // feature splats but only on the LHS, we may choose to invert our mask and
2637   // instead select between RHS and LHS.
2638   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2639   bool InvertMask = IsSelect == SwapOps;
2640 
2641   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2642   // half.
2643   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2644 
2645   // Now construct the mask that will be used by the vselect or blended
2646   // vrgather operation. For vrgathers, construct the appropriate indices into
2647   // each vector.
2648   for (int MaskIndex : Mask) {
2649     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2650     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2651     if (!IsSelect) {
2652       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2653       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2654                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2655                                      : DAG.getUNDEF(XLenVT));
2656       GatherIndicesRHS.push_back(
2657           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2658                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2659       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2660         ++LHSIndexCounts[MaskIndex];
2661       if (!IsLHSOrUndefIndex)
2662         ++RHSIndexCounts[MaskIndex - NumElts];
2663     }
2664   }
2665 
2666   if (SwapOps) {
2667     std::swap(V1, V2);
2668     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2669   }
2670 
2671   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2672   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2673   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2674 
2675   if (IsSelect)
2676     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2677 
2678   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2679     // On such a large vector we're unable to use i8 as the index type.
2680     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2681     // may involve vector splitting if we're already at LMUL=8, or our
2682     // user-supplied maximum fixed-length LMUL.
2683     return SDValue();
2684   }
2685 
2686   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2687   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2688   MVT IndexVT = VT.changeTypeToInteger();
2689   // Since we can't introduce illegal index types at this stage, use i16 and
2690   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2691   // than XLenVT.
2692   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2693     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2694     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2695   }
2696 
2697   MVT IndexContainerVT =
2698       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2699 
2700   SDValue Gather;
2701   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2702   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2703   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2704     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2705                               Subtarget);
2706   } else {
2707     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2708     // If only one index is used, we can use a "splat" vrgather.
2709     // TODO: We can splat the most-common index and fix-up any stragglers, if
2710     // that's beneficial.
2711     if (LHSIndexCounts.size() == 1) {
2712       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2713       Gather =
2714           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2715                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2716     } else {
2717       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2718       LHSIndices =
2719           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2720 
2721       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2722                            TrueMask, VL);
2723     }
2724   }
2725 
2726   // If a second vector operand is used by this shuffle, blend it in with an
2727   // additional vrgather.
2728   if (!V2.isUndef()) {
2729     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2730     // If only one index is used, we can use a "splat" vrgather.
2731     // TODO: We can splat the most-common index and fix-up any stragglers, if
2732     // that's beneficial.
2733     if (RHSIndexCounts.size() == 1) {
2734       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2735       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2736                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2737     } else {
2738       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2739       RHSIndices =
2740           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2741       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2742                        VL);
2743     }
2744 
2745     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2746     SelectMask =
2747         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2748 
2749     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2750                          Gather, VL);
2751   }
2752 
2753   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2754 }
2755 
2756 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2757   // Support splats for any type. These should type legalize well.
2758   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2759     return true;
2760 
2761   // Only support legal VTs for other shuffles for now.
2762   if (!isTypeLegal(VT))
2763     return false;
2764 
2765   MVT SVT = VT.getSimpleVT();
2766 
2767   bool SwapSources;
2768   int LoSrc, HiSrc;
2769   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2770          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2771 }
2772 
2773 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2774                                      SDLoc DL, SelectionDAG &DAG,
2775                                      const RISCVSubtarget &Subtarget) {
2776   if (VT.isScalableVector())
2777     return DAG.getFPExtendOrRound(Op, DL, VT);
2778   assert(VT.isFixedLengthVector() &&
2779          "Unexpected value type for RVV FP extend/round lowering");
2780   SDValue Mask, VL;
2781   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2782   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2783                         ? RISCVISD::FP_EXTEND_VL
2784                         : RISCVISD::FP_ROUND_VL;
2785   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2786 }
2787 
2788 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2789 // the exponent.
2790 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2791   MVT VT = Op.getSimpleValueType();
2792   unsigned EltSize = VT.getScalarSizeInBits();
2793   SDValue Src = Op.getOperand(0);
2794   SDLoc DL(Op);
2795 
2796   // We need a FP type that can represent the value.
2797   // TODO: Use f16 for i8 when possible?
2798   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2799   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2800 
2801   // Legal types should have been checked in the RISCVTargetLowering
2802   // constructor.
2803   // TODO: Splitting may make sense in some cases.
2804   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2805          "Expected legal float type!");
2806 
2807   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2808   // The trailing zero count is equal to log2 of this single bit value.
2809   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2810     SDValue Neg =
2811         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2812     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2813   }
2814 
2815   // We have a legal FP type, convert to it.
2816   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2817   // Bitcast to integer and shift the exponent to the LSB.
2818   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2819   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2820   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2821   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2822                               DAG.getConstant(ShiftAmt, DL, IntVT));
2823   // Truncate back to original type to allow vnsrl.
2824   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2825   // The exponent contains log2 of the value in biased form.
2826   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2827 
2828   // For trailing zeros, we just need to subtract the bias.
2829   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2830     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2831                        DAG.getConstant(ExponentBias, DL, VT));
2832 
2833   // For leading zeros, we need to remove the bias and convert from log2 to
2834   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2835   unsigned Adjust = ExponentBias + (EltSize - 1);
2836   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2837 }
2838 
2839 // While RVV has alignment restrictions, we should always be able to load as a
2840 // legal equivalently-sized byte-typed vector instead. This method is
2841 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2842 // the load is already correctly-aligned, it returns SDValue().
2843 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2844                                                     SelectionDAG &DAG) const {
2845   auto *Load = cast<LoadSDNode>(Op);
2846   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2847 
2848   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2849                                      Load->getMemoryVT(),
2850                                      *Load->getMemOperand()))
2851     return SDValue();
2852 
2853   SDLoc DL(Op);
2854   MVT VT = Op.getSimpleValueType();
2855   unsigned EltSizeBits = VT.getScalarSizeInBits();
2856   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2857          "Unexpected unaligned RVV load type");
2858   MVT NewVT =
2859       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2860   assert(NewVT.isValid() &&
2861          "Expecting equally-sized RVV vector types to be legal");
2862   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2863                           Load->getPointerInfo(), Load->getOriginalAlign(),
2864                           Load->getMemOperand()->getFlags());
2865   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2866 }
2867 
2868 // While RVV has alignment restrictions, we should always be able to store as a
2869 // legal equivalently-sized byte-typed vector instead. This method is
2870 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2871 // returns SDValue() if the store is already correctly aligned.
2872 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2873                                                      SelectionDAG &DAG) const {
2874   auto *Store = cast<StoreSDNode>(Op);
2875   assert(Store && Store->getValue().getValueType().isVector() &&
2876          "Expected vector store");
2877 
2878   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2879                                      Store->getMemoryVT(),
2880                                      *Store->getMemOperand()))
2881     return SDValue();
2882 
2883   SDLoc DL(Op);
2884   SDValue StoredVal = Store->getValue();
2885   MVT VT = StoredVal.getSimpleValueType();
2886   unsigned EltSizeBits = VT.getScalarSizeInBits();
2887   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2888          "Unexpected unaligned RVV store type");
2889   MVT NewVT =
2890       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2891   assert(NewVT.isValid() &&
2892          "Expecting equally-sized RVV vector types to be legal");
2893   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2894   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2895                       Store->getPointerInfo(), Store->getOriginalAlign(),
2896                       Store->getMemOperand()->getFlags());
2897 }
2898 
2899 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2900                                             SelectionDAG &DAG) const {
2901   switch (Op.getOpcode()) {
2902   default:
2903     report_fatal_error("unimplemented operand");
2904   case ISD::GlobalAddress:
2905     return lowerGlobalAddress(Op, DAG);
2906   case ISD::BlockAddress:
2907     return lowerBlockAddress(Op, DAG);
2908   case ISD::ConstantPool:
2909     return lowerConstantPool(Op, DAG);
2910   case ISD::JumpTable:
2911     return lowerJumpTable(Op, DAG);
2912   case ISD::GlobalTLSAddress:
2913     return lowerGlobalTLSAddress(Op, DAG);
2914   case ISD::SELECT:
2915     return lowerSELECT(Op, DAG);
2916   case ISD::BRCOND:
2917     return lowerBRCOND(Op, DAG);
2918   case ISD::VASTART:
2919     return lowerVASTART(Op, DAG);
2920   case ISD::FRAMEADDR:
2921     return lowerFRAMEADDR(Op, DAG);
2922   case ISD::RETURNADDR:
2923     return lowerRETURNADDR(Op, DAG);
2924   case ISD::SHL_PARTS:
2925     return lowerShiftLeftParts(Op, DAG);
2926   case ISD::SRA_PARTS:
2927     return lowerShiftRightParts(Op, DAG, true);
2928   case ISD::SRL_PARTS:
2929     return lowerShiftRightParts(Op, DAG, false);
2930   case ISD::BITCAST: {
2931     SDLoc DL(Op);
2932     EVT VT = Op.getValueType();
2933     SDValue Op0 = Op.getOperand(0);
2934     EVT Op0VT = Op0.getValueType();
2935     MVT XLenVT = Subtarget.getXLenVT();
2936     if (VT.isFixedLengthVector()) {
2937       // We can handle fixed length vector bitcasts with a simple replacement
2938       // in isel.
2939       if (Op0VT.isFixedLengthVector())
2940         return Op;
2941       // When bitcasting from scalar to fixed-length vector, insert the scalar
2942       // into a one-element vector of the result type, and perform a vector
2943       // bitcast.
2944       if (!Op0VT.isVector()) {
2945         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2946         if (!isTypeLegal(BVT))
2947           return SDValue();
2948         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2949                                               DAG.getUNDEF(BVT), Op0,
2950                                               DAG.getConstant(0, DL, XLenVT)));
2951       }
2952       return SDValue();
2953     }
2954     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2955     // thus: bitcast the vector to a one-element vector type whose element type
2956     // is the same as the result type, and extract the first element.
2957     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2958       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2959       if (!isTypeLegal(BVT))
2960         return SDValue();
2961       SDValue BVec = DAG.getBitcast(BVT, Op0);
2962       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2963                          DAG.getConstant(0, DL, XLenVT));
2964     }
2965     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2966       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2967       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2968       return FPConv;
2969     }
2970     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2971         Subtarget.hasStdExtF()) {
2972       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2973       SDValue FPConv =
2974           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2975       return FPConv;
2976     }
2977     return SDValue();
2978   }
2979   case ISD::INTRINSIC_WO_CHAIN:
2980     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2981   case ISD::INTRINSIC_W_CHAIN:
2982     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2983   case ISD::INTRINSIC_VOID:
2984     return LowerINTRINSIC_VOID(Op, DAG);
2985   case ISD::BSWAP:
2986   case ISD::BITREVERSE: {
2987     MVT VT = Op.getSimpleValueType();
2988     SDLoc DL(Op);
2989     if (Subtarget.hasStdExtZbp()) {
2990       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2991       // Start with the maximum immediate value which is the bitwidth - 1.
2992       unsigned Imm = VT.getSizeInBits() - 1;
2993       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2994       if (Op.getOpcode() == ISD::BSWAP)
2995         Imm &= ~0x7U;
2996       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2997                          DAG.getConstant(Imm, DL, VT));
2998     }
2999     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3000     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3001     // Expand bitreverse to a bswap(rev8) followed by brev8.
3002     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3003     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3004     // as brev8 by an isel pattern.
3005     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3006                        DAG.getConstant(7, DL, VT));
3007   }
3008   case ISD::FSHL:
3009   case ISD::FSHR: {
3010     MVT VT = Op.getSimpleValueType();
3011     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3012     SDLoc DL(Op);
3013     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3014     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3015     // accidentally setting the extra bit.
3016     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3017     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3018                                 DAG.getConstant(ShAmtWidth, DL, VT));
3019     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3020     // instruction use different orders. fshl will return its first operand for
3021     // shift of zero, fshr will return its second operand. fsl and fsr both
3022     // return rs1 so the ISD nodes need to have different operand orders.
3023     // Shift amount is in rs2.
3024     SDValue Op0 = Op.getOperand(0);
3025     SDValue Op1 = Op.getOperand(1);
3026     unsigned Opc = RISCVISD::FSL;
3027     if (Op.getOpcode() == ISD::FSHR) {
3028       std::swap(Op0, Op1);
3029       Opc = RISCVISD::FSR;
3030     }
3031     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3032   }
3033   case ISD::TRUNCATE:
3034     // Only custom-lower vector truncates
3035     if (!Op.getSimpleValueType().isVector())
3036       return Op;
3037     return lowerVectorTruncLike(Op, DAG);
3038   case ISD::ANY_EXTEND:
3039   case ISD::ZERO_EXTEND:
3040     if (Op.getOperand(0).getValueType().isVector() &&
3041         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3042       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3043     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3044   case ISD::SIGN_EXTEND:
3045     if (Op.getOperand(0).getValueType().isVector() &&
3046         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3047       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3048     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3049   case ISD::SPLAT_VECTOR_PARTS:
3050     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3051   case ISD::INSERT_VECTOR_ELT:
3052     return lowerINSERT_VECTOR_ELT(Op, DAG);
3053   case ISD::EXTRACT_VECTOR_ELT:
3054     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3055   case ISD::VSCALE: {
3056     MVT VT = Op.getSimpleValueType();
3057     SDLoc DL(Op);
3058     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3059     // We define our scalable vector types for lmul=1 to use a 64 bit known
3060     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3061     // vscale as VLENB / 8.
3062     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3063     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3064       report_fatal_error("Support for VLEN==32 is incomplete.");
3065     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3066       // We assume VLENB is a multiple of 8. We manually choose the best shift
3067       // here because SimplifyDemandedBits isn't always able to simplify it.
3068       uint64_t Val = Op.getConstantOperandVal(0);
3069       if (isPowerOf2_64(Val)) {
3070         uint64_t Log2 = Log2_64(Val);
3071         if (Log2 < 3)
3072           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3073                              DAG.getConstant(3 - Log2, DL, VT));
3074         if (Log2 > 3)
3075           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3076                              DAG.getConstant(Log2 - 3, DL, VT));
3077         return VLENB;
3078       }
3079       // If the multiplier is a multiple of 8, scale it down to avoid needing
3080       // to shift the VLENB value.
3081       if ((Val % 8) == 0)
3082         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3083                            DAG.getConstant(Val / 8, DL, VT));
3084     }
3085 
3086     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3087                                  DAG.getConstant(3, DL, VT));
3088     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3089   }
3090   case ISD::FPOWI: {
3091     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3092     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3093     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3094         Op.getOperand(1).getValueType() == MVT::i32) {
3095       SDLoc DL(Op);
3096       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3097       SDValue Powi =
3098           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3099       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3100                          DAG.getIntPtrConstant(0, DL));
3101     }
3102     return SDValue();
3103   }
3104   case ISD::FP_EXTEND: {
3105     // RVV can only do fp_extend to types double the size as the source. We
3106     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3107     // via f32.
3108     SDLoc DL(Op);
3109     MVT VT = Op.getSimpleValueType();
3110     SDValue Src = Op.getOperand(0);
3111     MVT SrcVT = Src.getSimpleValueType();
3112 
3113     // Prepare any fixed-length vector operands.
3114     MVT ContainerVT = VT;
3115     if (SrcVT.isFixedLengthVector()) {
3116       ContainerVT = getContainerForFixedLengthVector(VT);
3117       MVT SrcContainerVT =
3118           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3119       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3120     }
3121 
3122     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3123         SrcVT.getVectorElementType() != MVT::f16) {
3124       // For scalable vectors, we only need to close the gap between
3125       // vXf16->vXf64.
3126       if (!VT.isFixedLengthVector())
3127         return Op;
3128       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3129       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3130       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3131     }
3132 
3133     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3134     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3135     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3136         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3137 
3138     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3139                                            DL, DAG, Subtarget);
3140     if (VT.isFixedLengthVector())
3141       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3142     return Extend;
3143   }
3144   case ISD::FP_ROUND:
3145     if (!Op.getValueType().isVector())
3146       return Op;
3147     return lowerVectorFPRoundLike(Op, DAG);
3148   case ISD::FP_TO_SINT:
3149   case ISD::FP_TO_UINT:
3150   case ISD::SINT_TO_FP:
3151   case ISD::UINT_TO_FP: {
3152     // RVV can only do fp<->int conversions to types half/double the size as
3153     // the source. We custom-lower any conversions that do two hops into
3154     // sequences.
3155     MVT VT = Op.getSimpleValueType();
3156     if (!VT.isVector())
3157       return Op;
3158     SDLoc DL(Op);
3159     SDValue Src = Op.getOperand(0);
3160     MVT EltVT = VT.getVectorElementType();
3161     MVT SrcVT = Src.getSimpleValueType();
3162     MVT SrcEltVT = SrcVT.getVectorElementType();
3163     unsigned EltSize = EltVT.getSizeInBits();
3164     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3165     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3166            "Unexpected vector element types");
3167 
3168     bool IsInt2FP = SrcEltVT.isInteger();
3169     // Widening conversions
3170     if (EltSize > (2 * SrcEltSize)) {
3171       if (IsInt2FP) {
3172         // Do a regular integer sign/zero extension then convert to float.
3173         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3174                                       VT.getVectorElementCount());
3175         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3176                                  ? ISD::ZERO_EXTEND
3177                                  : ISD::SIGN_EXTEND;
3178         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3179         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3180       }
3181       // FP2Int
3182       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3183       // Do one doubling fp_extend then complete the operation by converting
3184       // to int.
3185       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3186       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3187       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3188     }
3189 
3190     // Narrowing conversions
3191     if (SrcEltSize > (2 * EltSize)) {
3192       if (IsInt2FP) {
3193         // One narrowing int_to_fp, then an fp_round.
3194         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3195         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3196         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3197         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3198       }
3199       // FP2Int
3200       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3201       // representable by the integer, the result is poison.
3202       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3203                                     VT.getVectorElementCount());
3204       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3205       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3206     }
3207 
3208     // Scalable vectors can exit here. Patterns will handle equally-sized
3209     // conversions halving/doubling ones.
3210     if (!VT.isFixedLengthVector())
3211       return Op;
3212 
3213     // For fixed-length vectors we lower to a custom "VL" node.
3214     unsigned RVVOpc = 0;
3215     switch (Op.getOpcode()) {
3216     default:
3217       llvm_unreachable("Impossible opcode");
3218     case ISD::FP_TO_SINT:
3219       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3220       break;
3221     case ISD::FP_TO_UINT:
3222       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3223       break;
3224     case ISD::SINT_TO_FP:
3225       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3226       break;
3227     case ISD::UINT_TO_FP:
3228       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3229       break;
3230     }
3231 
3232     MVT ContainerVT, SrcContainerVT;
3233     // Derive the reference container type from the larger vector type.
3234     if (SrcEltSize > EltSize) {
3235       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3236       ContainerVT =
3237           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3238     } else {
3239       ContainerVT = getContainerForFixedLengthVector(VT);
3240       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3241     }
3242 
3243     SDValue Mask, VL;
3244     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3245 
3246     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3247     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3248     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3249   }
3250   case ISD::FP_TO_SINT_SAT:
3251   case ISD::FP_TO_UINT_SAT:
3252     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3253   case ISD::FTRUNC:
3254   case ISD::FCEIL:
3255   case ISD::FFLOOR:
3256     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3257   case ISD::FROUND:
3258     return lowerFROUND(Op, DAG);
3259   case ISD::VECREDUCE_ADD:
3260   case ISD::VECREDUCE_UMAX:
3261   case ISD::VECREDUCE_SMAX:
3262   case ISD::VECREDUCE_UMIN:
3263   case ISD::VECREDUCE_SMIN:
3264     return lowerVECREDUCE(Op, DAG);
3265   case ISD::VECREDUCE_AND:
3266   case ISD::VECREDUCE_OR:
3267   case ISD::VECREDUCE_XOR:
3268     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3269       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3270     return lowerVECREDUCE(Op, DAG);
3271   case ISD::VECREDUCE_FADD:
3272   case ISD::VECREDUCE_SEQ_FADD:
3273   case ISD::VECREDUCE_FMIN:
3274   case ISD::VECREDUCE_FMAX:
3275     return lowerFPVECREDUCE(Op, DAG);
3276   case ISD::VP_REDUCE_ADD:
3277   case ISD::VP_REDUCE_UMAX:
3278   case ISD::VP_REDUCE_SMAX:
3279   case ISD::VP_REDUCE_UMIN:
3280   case ISD::VP_REDUCE_SMIN:
3281   case ISD::VP_REDUCE_FADD:
3282   case ISD::VP_REDUCE_SEQ_FADD:
3283   case ISD::VP_REDUCE_FMIN:
3284   case ISD::VP_REDUCE_FMAX:
3285     return lowerVPREDUCE(Op, DAG);
3286   case ISD::VP_REDUCE_AND:
3287   case ISD::VP_REDUCE_OR:
3288   case ISD::VP_REDUCE_XOR:
3289     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3290       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3291     return lowerVPREDUCE(Op, DAG);
3292   case ISD::INSERT_SUBVECTOR:
3293     return lowerINSERT_SUBVECTOR(Op, DAG);
3294   case ISD::EXTRACT_SUBVECTOR:
3295     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3296   case ISD::STEP_VECTOR:
3297     return lowerSTEP_VECTOR(Op, DAG);
3298   case ISD::VECTOR_REVERSE:
3299     return lowerVECTOR_REVERSE(Op, DAG);
3300   case ISD::VECTOR_SPLICE:
3301     return lowerVECTOR_SPLICE(Op, DAG);
3302   case ISD::BUILD_VECTOR:
3303     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3304   case ISD::SPLAT_VECTOR:
3305     if (Op.getValueType().getVectorElementType() == MVT::i1)
3306       return lowerVectorMaskSplat(Op, DAG);
3307     return SDValue();
3308   case ISD::VECTOR_SHUFFLE:
3309     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3310   case ISD::CONCAT_VECTORS: {
3311     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3312     // better than going through the stack, as the default expansion does.
3313     SDLoc DL(Op);
3314     MVT VT = Op.getSimpleValueType();
3315     unsigned NumOpElts =
3316         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3317     SDValue Vec = DAG.getUNDEF(VT);
3318     for (const auto &OpIdx : enumerate(Op->ops())) {
3319       SDValue SubVec = OpIdx.value();
3320       // Don't insert undef subvectors.
3321       if (SubVec.isUndef())
3322         continue;
3323       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3324                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3325     }
3326     return Vec;
3327   }
3328   case ISD::LOAD:
3329     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3330       return V;
3331     if (Op.getValueType().isFixedLengthVector())
3332       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3333     return Op;
3334   case ISD::STORE:
3335     if (auto V = expandUnalignedRVVStore(Op, DAG))
3336       return V;
3337     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3338       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3339     return Op;
3340   case ISD::MLOAD:
3341   case ISD::VP_LOAD:
3342     return lowerMaskedLoad(Op, DAG);
3343   case ISD::MSTORE:
3344   case ISD::VP_STORE:
3345     return lowerMaskedStore(Op, DAG);
3346   case ISD::SETCC:
3347     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3348   case ISD::ADD:
3349     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3350   case ISD::SUB:
3351     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3352   case ISD::MUL:
3353     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3354   case ISD::MULHS:
3355     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3356   case ISD::MULHU:
3357     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3358   case ISD::AND:
3359     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3360                                               RISCVISD::AND_VL);
3361   case ISD::OR:
3362     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3363                                               RISCVISD::OR_VL);
3364   case ISD::XOR:
3365     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3366                                               RISCVISD::XOR_VL);
3367   case ISD::SDIV:
3368     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3369   case ISD::SREM:
3370     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3371   case ISD::UDIV:
3372     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3373   case ISD::UREM:
3374     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3375   case ISD::SHL:
3376   case ISD::SRA:
3377   case ISD::SRL:
3378     if (Op.getSimpleValueType().isFixedLengthVector())
3379       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3380     // This can be called for an i32 shift amount that needs to be promoted.
3381     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3382            "Unexpected custom legalisation");
3383     return SDValue();
3384   case ISD::SADDSAT:
3385     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3386   case ISD::UADDSAT:
3387     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3388   case ISD::SSUBSAT:
3389     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3390   case ISD::USUBSAT:
3391     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3392   case ISD::FADD:
3393     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3394   case ISD::FSUB:
3395     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3396   case ISD::FMUL:
3397     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3398   case ISD::FDIV:
3399     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3400   case ISD::FNEG:
3401     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3402   case ISD::FABS:
3403     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3404   case ISD::FSQRT:
3405     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3406   case ISD::FMA:
3407     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3408   case ISD::SMIN:
3409     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3410   case ISD::SMAX:
3411     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3412   case ISD::UMIN:
3413     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3414   case ISD::UMAX:
3415     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3416   case ISD::FMINNUM:
3417     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3418   case ISD::FMAXNUM:
3419     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3420   case ISD::ABS:
3421     return lowerABS(Op, DAG);
3422   case ISD::CTLZ_ZERO_UNDEF:
3423   case ISD::CTTZ_ZERO_UNDEF:
3424     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3425   case ISD::VSELECT:
3426     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3427   case ISD::FCOPYSIGN:
3428     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3429   case ISD::MGATHER:
3430   case ISD::VP_GATHER:
3431     return lowerMaskedGather(Op, DAG);
3432   case ISD::MSCATTER:
3433   case ISD::VP_SCATTER:
3434     return lowerMaskedScatter(Op, DAG);
3435   case ISD::FLT_ROUNDS_:
3436     return lowerGET_ROUNDING(Op, DAG);
3437   case ISD::SET_ROUNDING:
3438     return lowerSET_ROUNDING(Op, DAG);
3439   case ISD::VP_SELECT:
3440     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3441   case ISD::VP_MERGE:
3442     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3443   case ISD::VP_ADD:
3444     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3445   case ISD::VP_SUB:
3446     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3447   case ISD::VP_MUL:
3448     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3449   case ISD::VP_SDIV:
3450     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3451   case ISD::VP_UDIV:
3452     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3453   case ISD::VP_SREM:
3454     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3455   case ISD::VP_UREM:
3456     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3457   case ISD::VP_AND:
3458     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3459   case ISD::VP_OR:
3460     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3461   case ISD::VP_XOR:
3462     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3463   case ISD::VP_ASHR:
3464     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3465   case ISD::VP_LSHR:
3466     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3467   case ISD::VP_SHL:
3468     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3469   case ISD::VP_FADD:
3470     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3471   case ISD::VP_FSUB:
3472     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3473   case ISD::VP_FMUL:
3474     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3475   case ISD::VP_FDIV:
3476     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3477   case ISD::VP_FNEG:
3478     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3479   case ISD::VP_FMA:
3480     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3481   case ISD::VP_SEXT:
3482   case ISD::VP_ZEXT:
3483     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3484       return lowerVPExtMaskOp(Op, DAG);
3485     return lowerVPOp(Op, DAG,
3486                      Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL
3487                                                     : RISCVISD::VZEXT_VL);
3488   case ISD::VP_TRUNC:
3489     return lowerVectorTruncLike(Op, DAG);
3490   case ISD::VP_FP_ROUND:
3491     return lowerVectorFPRoundLike(Op, DAG);
3492   case ISD::VP_FPTOSI:
3493     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3494   case ISD::VP_FPTOUI:
3495     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3496   case ISD::VP_SITOFP:
3497     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3498   case ISD::VP_UITOFP:
3499     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3500   case ISD::VP_SETCC:
3501     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3502       return lowerVPSetCCMaskOp(Op, DAG);
3503     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3504   }
3505 }
3506 
3507 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3508                              SelectionDAG &DAG, unsigned Flags) {
3509   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3510 }
3511 
3512 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3513                              SelectionDAG &DAG, unsigned Flags) {
3514   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3515                                    Flags);
3516 }
3517 
3518 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3519                              SelectionDAG &DAG, unsigned Flags) {
3520   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3521                                    N->getOffset(), Flags);
3522 }
3523 
3524 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3525                              SelectionDAG &DAG, unsigned Flags) {
3526   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3527 }
3528 
3529 template <class NodeTy>
3530 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3531                                      bool IsLocal) const {
3532   SDLoc DL(N);
3533   EVT Ty = getPointerTy(DAG.getDataLayout());
3534 
3535   if (isPositionIndependent()) {
3536     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3537     if (IsLocal)
3538       // Use PC-relative addressing to access the symbol. This generates the
3539       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3540       // %pcrel_lo(auipc)).
3541       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3542 
3543     // Use PC-relative addressing to access the GOT for this symbol, then load
3544     // the address from the GOT. This generates the pattern (PseudoLA sym),
3545     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3546     SDValue Load =
3547         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3548     MachineFunction &MF = DAG.getMachineFunction();
3549     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3550         MachinePointerInfo::getGOT(MF),
3551         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3552             MachineMemOperand::MOInvariant,
3553         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3554     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3555     return Load;
3556   }
3557 
3558   switch (getTargetMachine().getCodeModel()) {
3559   default:
3560     report_fatal_error("Unsupported code model for lowering");
3561   case CodeModel::Small: {
3562     // Generate a sequence for accessing addresses within the first 2 GiB of
3563     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3564     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3565     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3566     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3567     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3568   }
3569   case CodeModel::Medium: {
3570     // Generate a sequence for accessing addresses within any 2GiB range within
3571     // the address space. This generates the pattern (PseudoLLA sym), which
3572     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3573     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3574     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3575   }
3576   }
3577 }
3578 
3579 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3580     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3581 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3582     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3583 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3584     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3585 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3586     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3587 
3588 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3589                                                 SelectionDAG &DAG) const {
3590   SDLoc DL(Op);
3591   EVT Ty = Op.getValueType();
3592   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3593   int64_t Offset = N->getOffset();
3594   MVT XLenVT = Subtarget.getXLenVT();
3595 
3596   const GlobalValue *GV = N->getGlobal();
3597   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3598   SDValue Addr = getAddr(N, DAG, IsLocal);
3599 
3600   // In order to maximise the opportunity for common subexpression elimination,
3601   // emit a separate ADD node for the global address offset instead of folding
3602   // it in the global address node. Later peephole optimisations may choose to
3603   // fold it back in when profitable.
3604   if (Offset != 0)
3605     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3606                        DAG.getConstant(Offset, DL, XLenVT));
3607   return Addr;
3608 }
3609 
3610 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3611                                                SelectionDAG &DAG) const {
3612   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3613 
3614   return getAddr(N, DAG);
3615 }
3616 
3617 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3618                                                SelectionDAG &DAG) const {
3619   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3620 
3621   return getAddr(N, DAG);
3622 }
3623 
3624 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3625                                             SelectionDAG &DAG) const {
3626   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3627 
3628   return getAddr(N, DAG);
3629 }
3630 
3631 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3632                                               SelectionDAG &DAG,
3633                                               bool UseGOT) const {
3634   SDLoc DL(N);
3635   EVT Ty = getPointerTy(DAG.getDataLayout());
3636   const GlobalValue *GV = N->getGlobal();
3637   MVT XLenVT = Subtarget.getXLenVT();
3638 
3639   if (UseGOT) {
3640     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3641     // load the address from the GOT and add the thread pointer. This generates
3642     // the pattern (PseudoLA_TLS_IE sym), which expands to
3643     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3644     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3645     SDValue Load =
3646         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3647     MachineFunction &MF = DAG.getMachineFunction();
3648     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3649         MachinePointerInfo::getGOT(MF),
3650         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3651             MachineMemOperand::MOInvariant,
3652         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3653     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3654 
3655     // Add the thread pointer.
3656     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3657     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3658   }
3659 
3660   // Generate a sequence for accessing the address relative to the thread
3661   // pointer, with the appropriate adjustment for the thread pointer offset.
3662   // This generates the pattern
3663   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3664   SDValue AddrHi =
3665       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3666   SDValue AddrAdd =
3667       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3668   SDValue AddrLo =
3669       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3670 
3671   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3672   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3673   SDValue MNAdd = SDValue(
3674       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3675       0);
3676   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3677 }
3678 
3679 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3680                                                SelectionDAG &DAG) const {
3681   SDLoc DL(N);
3682   EVT Ty = getPointerTy(DAG.getDataLayout());
3683   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3684   const GlobalValue *GV = N->getGlobal();
3685 
3686   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3687   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3688   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3689   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3690   SDValue Load =
3691       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3692 
3693   // Prepare argument list to generate call.
3694   ArgListTy Args;
3695   ArgListEntry Entry;
3696   Entry.Node = Load;
3697   Entry.Ty = CallTy;
3698   Args.push_back(Entry);
3699 
3700   // Setup call to __tls_get_addr.
3701   TargetLowering::CallLoweringInfo CLI(DAG);
3702   CLI.setDebugLoc(DL)
3703       .setChain(DAG.getEntryNode())
3704       .setLibCallee(CallingConv::C, CallTy,
3705                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3706                     std::move(Args));
3707 
3708   return LowerCallTo(CLI).first;
3709 }
3710 
3711 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3712                                                    SelectionDAG &DAG) const {
3713   SDLoc DL(Op);
3714   EVT Ty = Op.getValueType();
3715   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3716   int64_t Offset = N->getOffset();
3717   MVT XLenVT = Subtarget.getXLenVT();
3718 
3719   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3720 
3721   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3722       CallingConv::GHC)
3723     report_fatal_error("In GHC calling convention TLS is not supported");
3724 
3725   SDValue Addr;
3726   switch (Model) {
3727   case TLSModel::LocalExec:
3728     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3729     break;
3730   case TLSModel::InitialExec:
3731     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3732     break;
3733   case TLSModel::LocalDynamic:
3734   case TLSModel::GeneralDynamic:
3735     Addr = getDynamicTLSAddr(N, DAG);
3736     break;
3737   }
3738 
3739   // In order to maximise the opportunity for common subexpression elimination,
3740   // emit a separate ADD node for the global address offset instead of folding
3741   // it in the global address node. Later peephole optimisations may choose to
3742   // fold it back in when profitable.
3743   if (Offset != 0)
3744     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3745                        DAG.getConstant(Offset, DL, XLenVT));
3746   return Addr;
3747 }
3748 
3749 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3750   SDValue CondV = Op.getOperand(0);
3751   SDValue TrueV = Op.getOperand(1);
3752   SDValue FalseV = Op.getOperand(2);
3753   SDLoc DL(Op);
3754   MVT VT = Op.getSimpleValueType();
3755   MVT XLenVT = Subtarget.getXLenVT();
3756 
3757   // Lower vector SELECTs to VSELECTs by splatting the condition.
3758   if (VT.isVector()) {
3759     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3760     SDValue CondSplat = VT.isScalableVector()
3761                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3762                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3763     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3764   }
3765 
3766   // If the result type is XLenVT and CondV is the output of a SETCC node
3767   // which also operated on XLenVT inputs, then merge the SETCC node into the
3768   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3769   // compare+branch instructions. i.e.:
3770   // (select (setcc lhs, rhs, cc), truev, falsev)
3771   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3772   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3773       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3774     SDValue LHS = CondV.getOperand(0);
3775     SDValue RHS = CondV.getOperand(1);
3776     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3777     ISD::CondCode CCVal = CC->get();
3778 
3779     // Special case for a select of 2 constants that have a diffence of 1.
3780     // Normally this is done by DAGCombine, but if the select is introduced by
3781     // type legalization or op legalization, we miss it. Restricting to SETLT
3782     // case for now because that is what signed saturating add/sub need.
3783     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3784     // but we would probably want to swap the true/false values if the condition
3785     // is SETGE/SETLE to avoid an XORI.
3786     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3787         CCVal == ISD::SETLT) {
3788       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3789       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3790       if (TrueVal - 1 == FalseVal)
3791         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3792       if (TrueVal + 1 == FalseVal)
3793         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3794     }
3795 
3796     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3797 
3798     SDValue TargetCC = DAG.getCondCode(CCVal);
3799     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3800     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3801   }
3802 
3803   // Otherwise:
3804   // (select condv, truev, falsev)
3805   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3806   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3807   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3808 
3809   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3810 
3811   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3812 }
3813 
3814 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3815   SDValue CondV = Op.getOperand(1);
3816   SDLoc DL(Op);
3817   MVT XLenVT = Subtarget.getXLenVT();
3818 
3819   if (CondV.getOpcode() == ISD::SETCC &&
3820       CondV.getOperand(0).getValueType() == XLenVT) {
3821     SDValue LHS = CondV.getOperand(0);
3822     SDValue RHS = CondV.getOperand(1);
3823     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3824 
3825     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3826 
3827     SDValue TargetCC = DAG.getCondCode(CCVal);
3828     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3829                        LHS, RHS, TargetCC, Op.getOperand(2));
3830   }
3831 
3832   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3833                      CondV, DAG.getConstant(0, DL, XLenVT),
3834                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3835 }
3836 
3837 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3838   MachineFunction &MF = DAG.getMachineFunction();
3839   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3840 
3841   SDLoc DL(Op);
3842   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3843                                  getPointerTy(MF.getDataLayout()));
3844 
3845   // vastart just stores the address of the VarArgsFrameIndex slot into the
3846   // memory location argument.
3847   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3848   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3849                       MachinePointerInfo(SV));
3850 }
3851 
3852 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3853                                             SelectionDAG &DAG) const {
3854   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3855   MachineFunction &MF = DAG.getMachineFunction();
3856   MachineFrameInfo &MFI = MF.getFrameInfo();
3857   MFI.setFrameAddressIsTaken(true);
3858   Register FrameReg = RI.getFrameRegister(MF);
3859   int XLenInBytes = Subtarget.getXLen() / 8;
3860 
3861   EVT VT = Op.getValueType();
3862   SDLoc DL(Op);
3863   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3864   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3865   while (Depth--) {
3866     int Offset = -(XLenInBytes * 2);
3867     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3868                               DAG.getIntPtrConstant(Offset, DL));
3869     FrameAddr =
3870         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3871   }
3872   return FrameAddr;
3873 }
3874 
3875 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3876                                              SelectionDAG &DAG) const {
3877   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3878   MachineFunction &MF = DAG.getMachineFunction();
3879   MachineFrameInfo &MFI = MF.getFrameInfo();
3880   MFI.setReturnAddressIsTaken(true);
3881   MVT XLenVT = Subtarget.getXLenVT();
3882   int XLenInBytes = Subtarget.getXLen() / 8;
3883 
3884   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3885     return SDValue();
3886 
3887   EVT VT = Op.getValueType();
3888   SDLoc DL(Op);
3889   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3890   if (Depth) {
3891     int Off = -XLenInBytes;
3892     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3893     SDValue Offset = DAG.getConstant(Off, DL, VT);
3894     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3895                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3896                        MachinePointerInfo());
3897   }
3898 
3899   // Return the value of the return address register, marking it an implicit
3900   // live-in.
3901   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3902   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3903 }
3904 
3905 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3906                                                  SelectionDAG &DAG) const {
3907   SDLoc DL(Op);
3908   SDValue Lo = Op.getOperand(0);
3909   SDValue Hi = Op.getOperand(1);
3910   SDValue Shamt = Op.getOperand(2);
3911   EVT VT = Lo.getValueType();
3912 
3913   // if Shamt-XLEN < 0: // Shamt < XLEN
3914   //   Lo = Lo << Shamt
3915   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3916   // else:
3917   //   Lo = 0
3918   //   Hi = Lo << (Shamt-XLEN)
3919 
3920   SDValue Zero = DAG.getConstant(0, DL, VT);
3921   SDValue One = DAG.getConstant(1, DL, VT);
3922   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3923   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3924   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3925   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3926 
3927   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3928   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3929   SDValue ShiftRightLo =
3930       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3931   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3932   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3933   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3934 
3935   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3936 
3937   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3938   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3939 
3940   SDValue Parts[2] = {Lo, Hi};
3941   return DAG.getMergeValues(Parts, DL);
3942 }
3943 
3944 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3945                                                   bool IsSRA) const {
3946   SDLoc DL(Op);
3947   SDValue Lo = Op.getOperand(0);
3948   SDValue Hi = Op.getOperand(1);
3949   SDValue Shamt = Op.getOperand(2);
3950   EVT VT = Lo.getValueType();
3951 
3952   // SRA expansion:
3953   //   if Shamt-XLEN < 0: // Shamt < XLEN
3954   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3955   //     Hi = Hi >>s Shamt
3956   //   else:
3957   //     Lo = Hi >>s (Shamt-XLEN);
3958   //     Hi = Hi >>s (XLEN-1)
3959   //
3960   // SRL expansion:
3961   //   if Shamt-XLEN < 0: // Shamt < XLEN
3962   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3963   //     Hi = Hi >>u Shamt
3964   //   else:
3965   //     Lo = Hi >>u (Shamt-XLEN);
3966   //     Hi = 0;
3967 
3968   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3969 
3970   SDValue Zero = DAG.getConstant(0, DL, VT);
3971   SDValue One = DAG.getConstant(1, DL, VT);
3972   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3973   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3974   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3975   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3976 
3977   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3978   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3979   SDValue ShiftLeftHi =
3980       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3981   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3982   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3983   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3984   SDValue HiFalse =
3985       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3986 
3987   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3988 
3989   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3990   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3991 
3992   SDValue Parts[2] = {Lo, Hi};
3993   return DAG.getMergeValues(Parts, DL);
3994 }
3995 
3996 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3997 // legal equivalently-sized i8 type, so we can use that as a go-between.
3998 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3999                                                   SelectionDAG &DAG) const {
4000   SDLoc DL(Op);
4001   MVT VT = Op.getSimpleValueType();
4002   SDValue SplatVal = Op.getOperand(0);
4003   // All-zeros or all-ones splats are handled specially.
4004   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4005     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4006     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4007   }
4008   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4009     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4010     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4011   }
4012   MVT XLenVT = Subtarget.getXLenVT();
4013   assert(SplatVal.getValueType() == XLenVT &&
4014          "Unexpected type for i1 splat value");
4015   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4016   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4017                          DAG.getConstant(1, DL, XLenVT));
4018   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4019   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4020   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4021 }
4022 
4023 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4024 // illegal (currently only vXi64 RV32).
4025 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4026 // them to VMV_V_X_VL.
4027 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4028                                                      SelectionDAG &DAG) const {
4029   SDLoc DL(Op);
4030   MVT VecVT = Op.getSimpleValueType();
4031   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4032          "Unexpected SPLAT_VECTOR_PARTS lowering");
4033 
4034   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4035   SDValue Lo = Op.getOperand(0);
4036   SDValue Hi = Op.getOperand(1);
4037 
4038   if (VecVT.isFixedLengthVector()) {
4039     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4040     SDLoc DL(Op);
4041     SDValue Mask, VL;
4042     std::tie(Mask, VL) =
4043         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4044 
4045     SDValue Res =
4046         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4047     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4048   }
4049 
4050   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4051     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4052     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4053     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4054     // node in order to try and match RVV vector/scalar instructions.
4055     if ((LoC >> 31) == HiC)
4056       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4057                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4058   }
4059 
4060   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4061   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4062       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4063       Hi.getConstantOperandVal(1) == 31)
4064     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4065                        DAG.getRegister(RISCV::X0, MVT::i32));
4066 
4067   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4068   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4069                      DAG.getUNDEF(VecVT), Lo, Hi,
4070                      DAG.getRegister(RISCV::X0, MVT::i32));
4071 }
4072 
4073 // Custom-lower extensions from mask vectors by using a vselect either with 1
4074 // for zero/any-extension or -1 for sign-extension:
4075 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4076 // Note that any-extension is lowered identically to zero-extension.
4077 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4078                                                 int64_t ExtTrueVal) const {
4079   SDLoc DL(Op);
4080   MVT VecVT = Op.getSimpleValueType();
4081   SDValue Src = Op.getOperand(0);
4082   // Only custom-lower extensions from mask types
4083   assert(Src.getValueType().isVector() &&
4084          Src.getValueType().getVectorElementType() == MVT::i1);
4085 
4086   if (VecVT.isScalableVector()) {
4087     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4088     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4089     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4090   }
4091 
4092   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4093   MVT I1ContainerVT =
4094       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4095 
4096   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4097 
4098   SDValue Mask, VL;
4099   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4100 
4101   MVT XLenVT = Subtarget.getXLenVT();
4102   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4103   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4104 
4105   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4106                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4107   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4108                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4109   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4110                                SplatTrueVal, SplatZero, VL);
4111 
4112   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4113 }
4114 
4115 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4116     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4117   MVT ExtVT = Op.getSimpleValueType();
4118   // Only custom-lower extensions from fixed-length vector types.
4119   if (!ExtVT.isFixedLengthVector())
4120     return Op;
4121   MVT VT = Op.getOperand(0).getSimpleValueType();
4122   // Grab the canonical container type for the extended type. Infer the smaller
4123   // type from that to ensure the same number of vector elements, as we know
4124   // the LMUL will be sufficient to hold the smaller type.
4125   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4126   // Get the extended container type manually to ensure the same number of
4127   // vector elements between source and dest.
4128   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4129                                      ContainerExtVT.getVectorElementCount());
4130 
4131   SDValue Op1 =
4132       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4133 
4134   SDLoc DL(Op);
4135   SDValue Mask, VL;
4136   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4137 
4138   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4139 
4140   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4141 }
4142 
4143 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4144 // setcc operation:
4145 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4146 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4147                                                       SelectionDAG &DAG) const {
4148   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4149   SDLoc DL(Op);
4150   EVT MaskVT = Op.getValueType();
4151   // Only expect to custom-lower truncations to mask types
4152   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4153          "Unexpected type for vector mask lowering");
4154   SDValue Src = Op.getOperand(0);
4155   MVT VecVT = Src.getSimpleValueType();
4156   SDValue Mask, VL;
4157   if (IsVPTrunc) {
4158     Mask = Op.getOperand(1);
4159     VL = Op.getOperand(2);
4160   }
4161   // If this is a fixed vector, we need to convert it to a scalable vector.
4162   MVT ContainerVT = VecVT;
4163 
4164   if (VecVT.isFixedLengthVector()) {
4165     ContainerVT = getContainerForFixedLengthVector(VecVT);
4166     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4167     if (IsVPTrunc) {
4168       MVT MaskContainerVT =
4169           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4170       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4171     }
4172   }
4173 
4174   if (!IsVPTrunc) {
4175     std::tie(Mask, VL) =
4176         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4177   }
4178 
4179   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4180   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4181 
4182   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4183                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4184   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4185                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4186 
4187   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4188   SDValue Trunc =
4189       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4190   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4191                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4192   if (MaskVT.isFixedLengthVector())
4193     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4194   return Trunc;
4195 }
4196 
4197 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4198                                                   SelectionDAG &DAG) const {
4199   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4200   SDLoc DL(Op);
4201 
4202   MVT VT = Op.getSimpleValueType();
4203   // Only custom-lower vector truncates
4204   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4205 
4206   // Truncates to mask types are handled differently
4207   if (VT.getVectorElementType() == MVT::i1)
4208     return lowerVectorMaskTruncLike(Op, DAG);
4209 
4210   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4211   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4212   // truncate by one power of two at a time.
4213   MVT DstEltVT = VT.getVectorElementType();
4214 
4215   SDValue Src = Op.getOperand(0);
4216   MVT SrcVT = Src.getSimpleValueType();
4217   MVT SrcEltVT = SrcVT.getVectorElementType();
4218 
4219   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4220          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4221          "Unexpected vector truncate lowering");
4222 
4223   MVT ContainerVT = SrcVT;
4224   SDValue Mask, VL;
4225   if (IsVPTrunc) {
4226     Mask = Op.getOperand(1);
4227     VL = Op.getOperand(2);
4228   }
4229   if (SrcVT.isFixedLengthVector()) {
4230     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4231     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4232     if (IsVPTrunc) {
4233       MVT MaskVT =
4234           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4235       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4236     }
4237   }
4238 
4239   SDValue Result = Src;
4240   if (!IsVPTrunc) {
4241     std::tie(Mask, VL) =
4242         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4243   }
4244 
4245   LLVMContext &Context = *DAG.getContext();
4246   const ElementCount Count = ContainerVT.getVectorElementCount();
4247   do {
4248     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4249     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4250     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4251                          Mask, VL);
4252   } while (SrcEltVT != DstEltVT);
4253 
4254   if (SrcVT.isFixedLengthVector())
4255     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4256 
4257   return Result;
4258 }
4259 
4260 SDValue RISCVTargetLowering::lowerVectorFPRoundLike(SDValue Op,
4261                                                     SelectionDAG &DAG) const {
4262   bool IsVPFPTrunc = Op.getOpcode() == ISD::VP_FP_ROUND;
4263   // RVV can only do truncate fp to types half the size as the source. We
4264   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4265   // conversion instruction.
4266   SDLoc DL(Op);
4267   MVT VT = Op.getSimpleValueType();
4268 
4269   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4270 
4271   SDValue Src = Op.getOperand(0);
4272   MVT SrcVT = Src.getSimpleValueType();
4273 
4274   bool IsDirectConv = VT.getVectorElementType() != MVT::f16 ||
4275                       SrcVT.getVectorElementType() != MVT::f64;
4276 
4277   // For FP_ROUND of scalable vectors, leave it to the pattern.
4278   if (!VT.isFixedLengthVector() && !IsVPFPTrunc && IsDirectConv)
4279     return Op;
4280 
4281   // Prepare any fixed-length vector operands.
4282   MVT ContainerVT = VT;
4283   SDValue Mask, VL;
4284   if (IsVPFPTrunc) {
4285     Mask = Op.getOperand(1);
4286     VL = Op.getOperand(2);
4287   }
4288   if (VT.isFixedLengthVector()) {
4289     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4290     ContainerVT =
4291         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4292     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4293     if (IsVPFPTrunc) {
4294       MVT MaskVT =
4295           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4296       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4297     }
4298   }
4299 
4300   if (!IsVPFPTrunc)
4301     std::tie(Mask, VL) =
4302         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4303 
4304   if (IsDirectConv) {
4305     Src = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, Src, Mask, VL);
4306     if (VT.isFixedLengthVector())
4307       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4308     return Src;
4309   }
4310 
4311   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4312   SDValue IntermediateRound =
4313       DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
4314   SDValue Round = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT,
4315                               IntermediateRound, Mask, VL);
4316   if (VT.isFixedLengthVector())
4317     return convertFromScalableVector(VT, Round, DAG, Subtarget);
4318   return Round;
4319 }
4320 
4321 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4322 // first position of a vector, and that vector is slid up to the insert index.
4323 // By limiting the active vector length to index+1 and merging with the
4324 // original vector (with an undisturbed tail policy for elements >= VL), we
4325 // achieve the desired result of leaving all elements untouched except the one
4326 // at VL-1, which is replaced with the desired value.
4327 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4328                                                     SelectionDAG &DAG) const {
4329   SDLoc DL(Op);
4330   MVT VecVT = Op.getSimpleValueType();
4331   SDValue Vec = Op.getOperand(0);
4332   SDValue Val = Op.getOperand(1);
4333   SDValue Idx = Op.getOperand(2);
4334 
4335   if (VecVT.getVectorElementType() == MVT::i1) {
4336     // FIXME: For now we just promote to an i8 vector and insert into that,
4337     // but this is probably not optimal.
4338     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4339     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4340     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4341     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4342   }
4343 
4344   MVT ContainerVT = VecVT;
4345   // If the operand is a fixed-length vector, convert to a scalable one.
4346   if (VecVT.isFixedLengthVector()) {
4347     ContainerVT = getContainerForFixedLengthVector(VecVT);
4348     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4349   }
4350 
4351   MVT XLenVT = Subtarget.getXLenVT();
4352 
4353   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4354   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4355   // Even i64-element vectors on RV32 can be lowered without scalar
4356   // legalization if the most-significant 32 bits of the value are not affected
4357   // by the sign-extension of the lower 32 bits.
4358   // TODO: We could also catch sign extensions of a 32-bit value.
4359   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4360     const auto *CVal = cast<ConstantSDNode>(Val);
4361     if (isInt<32>(CVal->getSExtValue())) {
4362       IsLegalInsert = true;
4363       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4364     }
4365   }
4366 
4367   SDValue Mask, VL;
4368   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4369 
4370   SDValue ValInVec;
4371 
4372   if (IsLegalInsert) {
4373     unsigned Opc =
4374         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4375     if (isNullConstant(Idx)) {
4376       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4377       if (!VecVT.isFixedLengthVector())
4378         return Vec;
4379       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4380     }
4381     ValInVec =
4382         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4383   } else {
4384     // On RV32, i64-element vectors must be specially handled to place the
4385     // value at element 0, by using two vslide1up instructions in sequence on
4386     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4387     // this.
4388     SDValue One = DAG.getConstant(1, DL, XLenVT);
4389     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4390     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4391     MVT I32ContainerVT =
4392         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4393     SDValue I32Mask =
4394         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4395     // Limit the active VL to two.
4396     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4397     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4398     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4399     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4400                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4401     // First slide in the hi value, then the lo in underneath it.
4402     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4403                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4404                            I32Mask, InsertI64VL);
4405     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4406                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4407                            I32Mask, InsertI64VL);
4408     // Bitcast back to the right container type.
4409     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4410   }
4411 
4412   // Now that the value is in a vector, slide it into position.
4413   SDValue InsertVL =
4414       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4415   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4416                                 ValInVec, Idx, Mask, InsertVL);
4417   if (!VecVT.isFixedLengthVector())
4418     return Slideup;
4419   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4420 }
4421 
4422 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4423 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4424 // types this is done using VMV_X_S to allow us to glean information about the
4425 // sign bits of the result.
4426 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4427                                                      SelectionDAG &DAG) const {
4428   SDLoc DL(Op);
4429   SDValue Idx = Op.getOperand(1);
4430   SDValue Vec = Op.getOperand(0);
4431   EVT EltVT = Op.getValueType();
4432   MVT VecVT = Vec.getSimpleValueType();
4433   MVT XLenVT = Subtarget.getXLenVT();
4434 
4435   if (VecVT.getVectorElementType() == MVT::i1) {
4436     if (VecVT.isFixedLengthVector()) {
4437       unsigned NumElts = VecVT.getVectorNumElements();
4438       if (NumElts >= 8) {
4439         MVT WideEltVT;
4440         unsigned WidenVecLen;
4441         SDValue ExtractElementIdx;
4442         SDValue ExtractBitIdx;
4443         unsigned MaxEEW = Subtarget.getELEN();
4444         MVT LargestEltVT = MVT::getIntegerVT(
4445             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4446         if (NumElts <= LargestEltVT.getSizeInBits()) {
4447           assert(isPowerOf2_32(NumElts) &&
4448                  "the number of elements should be power of 2");
4449           WideEltVT = MVT::getIntegerVT(NumElts);
4450           WidenVecLen = 1;
4451           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4452           ExtractBitIdx = Idx;
4453         } else {
4454           WideEltVT = LargestEltVT;
4455           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4456           // extract element index = index / element width
4457           ExtractElementIdx = DAG.getNode(
4458               ISD::SRL, DL, XLenVT, Idx,
4459               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4460           // mask bit index = index % element width
4461           ExtractBitIdx = DAG.getNode(
4462               ISD::AND, DL, XLenVT, Idx,
4463               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4464         }
4465         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4466         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4467         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4468                                          Vec, ExtractElementIdx);
4469         // Extract the bit from GPR.
4470         SDValue ShiftRight =
4471             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4472         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4473                            DAG.getConstant(1, DL, XLenVT));
4474       }
4475     }
4476     // Otherwise, promote to an i8 vector and extract from that.
4477     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4478     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4479     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4480   }
4481 
4482   // If this is a fixed vector, we need to convert it to a scalable vector.
4483   MVT ContainerVT = VecVT;
4484   if (VecVT.isFixedLengthVector()) {
4485     ContainerVT = getContainerForFixedLengthVector(VecVT);
4486     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4487   }
4488 
4489   // If the index is 0, the vector is already in the right position.
4490   if (!isNullConstant(Idx)) {
4491     // Use a VL of 1 to avoid processing more elements than we need.
4492     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4493     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4494     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4495     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4496                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4497   }
4498 
4499   if (!EltVT.isInteger()) {
4500     // Floating-point extracts are handled in TableGen.
4501     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4502                        DAG.getConstant(0, DL, XLenVT));
4503   }
4504 
4505   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4506   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4507 }
4508 
4509 // Some RVV intrinsics may claim that they want an integer operand to be
4510 // promoted or expanded.
4511 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4512                                            const RISCVSubtarget &Subtarget) {
4513   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4514           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4515          "Unexpected opcode");
4516 
4517   if (!Subtarget.hasVInstructions())
4518     return SDValue();
4519 
4520   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4521   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4522   SDLoc DL(Op);
4523 
4524   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4525       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4526   if (!II || !II->hasScalarOperand())
4527     return SDValue();
4528 
4529   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4530   assert(SplatOp < Op.getNumOperands());
4531 
4532   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4533   SDValue &ScalarOp = Operands[SplatOp];
4534   MVT OpVT = ScalarOp.getSimpleValueType();
4535   MVT XLenVT = Subtarget.getXLenVT();
4536 
4537   // If this isn't a scalar, or its type is XLenVT we're done.
4538   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4539     return SDValue();
4540 
4541   // Simplest case is that the operand needs to be promoted to XLenVT.
4542   if (OpVT.bitsLT(XLenVT)) {
4543     // If the operand is a constant, sign extend to increase our chances
4544     // of being able to use a .vi instruction. ANY_EXTEND would become a
4545     // a zero extend and the simm5 check in isel would fail.
4546     // FIXME: Should we ignore the upper bits in isel instead?
4547     unsigned ExtOpc =
4548         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4549     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4550     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4551   }
4552 
4553   // Use the previous operand to get the vXi64 VT. The result might be a mask
4554   // VT for compares. Using the previous operand assumes that the previous
4555   // operand will never have a smaller element size than a scalar operand and
4556   // that a widening operation never uses SEW=64.
4557   // NOTE: If this fails the below assert, we can probably just find the
4558   // element count from any operand or result and use it to construct the VT.
4559   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4560   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4561 
4562   // The more complex case is when the scalar is larger than XLenVT.
4563   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4564          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4565 
4566   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4567   // instruction to sign-extend since SEW>XLEN.
4568   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4569     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4570     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4571   }
4572 
4573   switch (IntNo) {
4574   case Intrinsic::riscv_vslide1up:
4575   case Intrinsic::riscv_vslide1down:
4576   case Intrinsic::riscv_vslide1up_mask:
4577   case Intrinsic::riscv_vslide1down_mask: {
4578     // We need to special case these when the scalar is larger than XLen.
4579     unsigned NumOps = Op.getNumOperands();
4580     bool IsMasked = NumOps == 7;
4581 
4582     // Convert the vector source to the equivalent nxvXi32 vector.
4583     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4584     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4585 
4586     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4587                                    DAG.getConstant(0, DL, XLenVT));
4588     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4589                                    DAG.getConstant(1, DL, XLenVT));
4590 
4591     // Double the VL since we halved SEW.
4592     SDValue AVL = getVLOperand(Op);
4593     SDValue I32VL;
4594 
4595     // Optimize for constant AVL
4596     if (isa<ConstantSDNode>(AVL)) {
4597       unsigned EltSize = VT.getScalarSizeInBits();
4598       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4599 
4600       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4601       unsigned MaxVLMAX =
4602           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4603 
4604       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4605       unsigned MinVLMAX =
4606           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4607 
4608       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4609       if (AVLInt <= MinVLMAX) {
4610         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4611       } else if (AVLInt >= 2 * MaxVLMAX) {
4612         // Just set vl to VLMAX in this situation
4613         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4614         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4615         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4616         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4617         SDValue SETVLMAX = DAG.getTargetConstant(
4618             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4619         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4620                             LMUL);
4621       } else {
4622         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4623         // is related to the hardware implementation.
4624         // So let the following code handle
4625       }
4626     }
4627     if (!I32VL) {
4628       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4629       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4630       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4631       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4632       SDValue SETVL =
4633           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4634       // Using vsetvli instruction to get actually used length which related to
4635       // the hardware implementation
4636       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4637                                SEW, LMUL);
4638       I32VL =
4639           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4640     }
4641 
4642     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4643     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4644 
4645     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4646     // instructions.
4647     SDValue Passthru;
4648     if (IsMasked)
4649       Passthru = DAG.getUNDEF(I32VT);
4650     else
4651       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4652 
4653     if (IntNo == Intrinsic::riscv_vslide1up ||
4654         IntNo == Intrinsic::riscv_vslide1up_mask) {
4655       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4656                         ScalarHi, I32Mask, I32VL);
4657       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4658                         ScalarLo, I32Mask, I32VL);
4659     } else {
4660       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4661                         ScalarLo, I32Mask, I32VL);
4662       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4663                         ScalarHi, I32Mask, I32VL);
4664     }
4665 
4666     // Convert back to nxvXi64.
4667     Vec = DAG.getBitcast(VT, Vec);
4668 
4669     if (!IsMasked)
4670       return Vec;
4671     // Apply mask after the operation.
4672     SDValue Mask = Operands[NumOps - 3];
4673     SDValue MaskedOff = Operands[1];
4674     // Assume Policy operand is the last operand.
4675     uint64_t Policy =
4676         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4677     // We don't need to select maskedoff if it's undef.
4678     if (MaskedOff.isUndef())
4679       return Vec;
4680     // TAMU
4681     if (Policy == RISCVII::TAIL_AGNOSTIC)
4682       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4683                          AVL);
4684     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4685     // It's fine because vmerge does not care mask policy.
4686     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4687                        AVL);
4688   }
4689   }
4690 
4691   // We need to convert the scalar to a splat vector.
4692   SDValue VL = getVLOperand(Op);
4693   assert(VL.getValueType() == XLenVT);
4694   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4695   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4696 }
4697 
4698 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4699                                                      SelectionDAG &DAG) const {
4700   unsigned IntNo = Op.getConstantOperandVal(0);
4701   SDLoc DL(Op);
4702   MVT XLenVT = Subtarget.getXLenVT();
4703 
4704   switch (IntNo) {
4705   default:
4706     break; // Don't custom lower most intrinsics.
4707   case Intrinsic::thread_pointer: {
4708     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4709     return DAG.getRegister(RISCV::X4, PtrVT);
4710   }
4711   case Intrinsic::riscv_orc_b:
4712   case Intrinsic::riscv_brev8: {
4713     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4714     unsigned Opc =
4715         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4716     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4717                        DAG.getConstant(7, DL, XLenVT));
4718   }
4719   case Intrinsic::riscv_grev:
4720   case Intrinsic::riscv_gorc: {
4721     unsigned Opc =
4722         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4723     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4724   }
4725   case Intrinsic::riscv_zip:
4726   case Intrinsic::riscv_unzip: {
4727     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4728     // For i32 the immediate is 15. For i64 the immediate is 31.
4729     unsigned Opc =
4730         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4731     unsigned BitWidth = Op.getValueSizeInBits();
4732     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4733     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4734                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4735   }
4736   case Intrinsic::riscv_shfl:
4737   case Intrinsic::riscv_unshfl: {
4738     unsigned Opc =
4739         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4740     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4741   }
4742   case Intrinsic::riscv_bcompress:
4743   case Intrinsic::riscv_bdecompress: {
4744     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4745                                                        : RISCVISD::BDECOMPRESS;
4746     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4747   }
4748   case Intrinsic::riscv_bfp:
4749     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4750                        Op.getOperand(2));
4751   case Intrinsic::riscv_fsl:
4752     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4753                        Op.getOperand(2), Op.getOperand(3));
4754   case Intrinsic::riscv_fsr:
4755     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4756                        Op.getOperand(2), Op.getOperand(3));
4757   case Intrinsic::riscv_vmv_x_s:
4758     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4759     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4760                        Op.getOperand(1));
4761   case Intrinsic::riscv_vmv_v_x:
4762     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4763                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4764                             Subtarget);
4765   case Intrinsic::riscv_vfmv_v_f:
4766     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4767                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4768   case Intrinsic::riscv_vmv_s_x: {
4769     SDValue Scalar = Op.getOperand(2);
4770 
4771     if (Scalar.getValueType().bitsLE(XLenVT)) {
4772       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4773       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4774                          Op.getOperand(1), Scalar, Op.getOperand(3));
4775     }
4776 
4777     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4778 
4779     // This is an i64 value that lives in two scalar registers. We have to
4780     // insert this in a convoluted way. First we build vXi64 splat containing
4781     // the two values that we assemble using some bit math. Next we'll use
4782     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4783     // to merge element 0 from our splat into the source vector.
4784     // FIXME: This is probably not the best way to do this, but it is
4785     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4786     // point.
4787     //   sw lo, (a0)
4788     //   sw hi, 4(a0)
4789     //   vlse vX, (a0)
4790     //
4791     //   vid.v      vVid
4792     //   vmseq.vx   mMask, vVid, 0
4793     //   vmerge.vvm vDest, vSrc, vVal, mMask
4794     MVT VT = Op.getSimpleValueType();
4795     SDValue Vec = Op.getOperand(1);
4796     SDValue VL = getVLOperand(Op);
4797 
4798     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4799     if (Op.getOperand(1).isUndef())
4800       return SplattedVal;
4801     SDValue SplattedIdx =
4802         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4803                     DAG.getConstant(0, DL, MVT::i32), VL);
4804 
4805     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4806     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4807     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4808     SDValue SelectCond =
4809         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4810                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4811     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4812                        Vec, VL);
4813   }
4814   }
4815 
4816   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4817 }
4818 
4819 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4820                                                     SelectionDAG &DAG) const {
4821   unsigned IntNo = Op.getConstantOperandVal(1);
4822   switch (IntNo) {
4823   default:
4824     break;
4825   case Intrinsic::riscv_masked_strided_load: {
4826     SDLoc DL(Op);
4827     MVT XLenVT = Subtarget.getXLenVT();
4828 
4829     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4830     // the selection of the masked intrinsics doesn't do this for us.
4831     SDValue Mask = Op.getOperand(5);
4832     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4833 
4834     MVT VT = Op->getSimpleValueType(0);
4835     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4836 
4837     SDValue PassThru = Op.getOperand(2);
4838     if (!IsUnmasked) {
4839       MVT MaskVT =
4840           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4841       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4842       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4843     }
4844 
4845     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4846 
4847     SDValue IntID = DAG.getTargetConstant(
4848         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4849         XLenVT);
4850 
4851     auto *Load = cast<MemIntrinsicSDNode>(Op);
4852     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4853     if (IsUnmasked)
4854       Ops.push_back(DAG.getUNDEF(ContainerVT));
4855     else
4856       Ops.push_back(PassThru);
4857     Ops.push_back(Op.getOperand(3)); // Ptr
4858     Ops.push_back(Op.getOperand(4)); // Stride
4859     if (!IsUnmasked)
4860       Ops.push_back(Mask);
4861     Ops.push_back(VL);
4862     if (!IsUnmasked) {
4863       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4864       Ops.push_back(Policy);
4865     }
4866 
4867     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4868     SDValue Result =
4869         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4870                                 Load->getMemoryVT(), Load->getMemOperand());
4871     SDValue Chain = Result.getValue(1);
4872     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4873     return DAG.getMergeValues({Result, Chain}, DL);
4874   }
4875   case Intrinsic::riscv_seg2_load:
4876   case Intrinsic::riscv_seg3_load:
4877   case Intrinsic::riscv_seg4_load:
4878   case Intrinsic::riscv_seg5_load:
4879   case Intrinsic::riscv_seg6_load:
4880   case Intrinsic::riscv_seg7_load:
4881   case Intrinsic::riscv_seg8_load: {
4882     SDLoc DL(Op);
4883     static const Intrinsic::ID VlsegInts[7] = {
4884         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4885         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4886         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4887         Intrinsic::riscv_vlseg8};
4888     unsigned NF = Op->getNumValues() - 1;
4889     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4890     MVT XLenVT = Subtarget.getXLenVT();
4891     MVT VT = Op->getSimpleValueType(0);
4892     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4893 
4894     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4895     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4896     auto *Load = cast<MemIntrinsicSDNode>(Op);
4897     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4898     ContainerVTs.push_back(MVT::Other);
4899     SDVTList VTs = DAG.getVTList(ContainerVTs);
4900     SDValue Result =
4901         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4902                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4903                                 Load->getMemoryVT(), Load->getMemOperand());
4904     SmallVector<SDValue, 9> Results;
4905     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4906       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4907                                                   DAG, Subtarget));
4908     Results.push_back(Result.getValue(NF));
4909     return DAG.getMergeValues(Results, DL);
4910   }
4911   }
4912 
4913   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4914 }
4915 
4916 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4917                                                  SelectionDAG &DAG) const {
4918   unsigned IntNo = Op.getConstantOperandVal(1);
4919   switch (IntNo) {
4920   default:
4921     break;
4922   case Intrinsic::riscv_masked_strided_store: {
4923     SDLoc DL(Op);
4924     MVT XLenVT = Subtarget.getXLenVT();
4925 
4926     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4927     // the selection of the masked intrinsics doesn't do this for us.
4928     SDValue Mask = Op.getOperand(5);
4929     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4930 
4931     SDValue Val = Op.getOperand(2);
4932     MVT VT = Val.getSimpleValueType();
4933     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4934 
4935     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4936     if (!IsUnmasked) {
4937       MVT MaskVT =
4938           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4939       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4940     }
4941 
4942     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4943 
4944     SDValue IntID = DAG.getTargetConstant(
4945         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4946         XLenVT);
4947 
4948     auto *Store = cast<MemIntrinsicSDNode>(Op);
4949     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4950     Ops.push_back(Val);
4951     Ops.push_back(Op.getOperand(3)); // Ptr
4952     Ops.push_back(Op.getOperand(4)); // Stride
4953     if (!IsUnmasked)
4954       Ops.push_back(Mask);
4955     Ops.push_back(VL);
4956 
4957     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4958                                    Ops, Store->getMemoryVT(),
4959                                    Store->getMemOperand());
4960   }
4961   }
4962 
4963   return SDValue();
4964 }
4965 
4966 static MVT getLMUL1VT(MVT VT) {
4967   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4968          "Unexpected vector MVT");
4969   return MVT::getScalableVectorVT(
4970       VT.getVectorElementType(),
4971       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4972 }
4973 
4974 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4975   switch (ISDOpcode) {
4976   default:
4977     llvm_unreachable("Unhandled reduction");
4978   case ISD::VECREDUCE_ADD:
4979     return RISCVISD::VECREDUCE_ADD_VL;
4980   case ISD::VECREDUCE_UMAX:
4981     return RISCVISD::VECREDUCE_UMAX_VL;
4982   case ISD::VECREDUCE_SMAX:
4983     return RISCVISD::VECREDUCE_SMAX_VL;
4984   case ISD::VECREDUCE_UMIN:
4985     return RISCVISD::VECREDUCE_UMIN_VL;
4986   case ISD::VECREDUCE_SMIN:
4987     return RISCVISD::VECREDUCE_SMIN_VL;
4988   case ISD::VECREDUCE_AND:
4989     return RISCVISD::VECREDUCE_AND_VL;
4990   case ISD::VECREDUCE_OR:
4991     return RISCVISD::VECREDUCE_OR_VL;
4992   case ISD::VECREDUCE_XOR:
4993     return RISCVISD::VECREDUCE_XOR_VL;
4994   }
4995 }
4996 
4997 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4998                                                          SelectionDAG &DAG,
4999                                                          bool IsVP) const {
5000   SDLoc DL(Op);
5001   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5002   MVT VecVT = Vec.getSimpleValueType();
5003   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5004           Op.getOpcode() == ISD::VECREDUCE_OR ||
5005           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5006           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5007           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5008           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5009          "Unexpected reduction lowering");
5010 
5011   MVT XLenVT = Subtarget.getXLenVT();
5012   assert(Op.getValueType() == XLenVT &&
5013          "Expected reduction output to be legalized to XLenVT");
5014 
5015   MVT ContainerVT = VecVT;
5016   if (VecVT.isFixedLengthVector()) {
5017     ContainerVT = getContainerForFixedLengthVector(VecVT);
5018     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5019   }
5020 
5021   SDValue Mask, VL;
5022   if (IsVP) {
5023     Mask = Op.getOperand(2);
5024     VL = Op.getOperand(3);
5025   } else {
5026     std::tie(Mask, VL) =
5027         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5028   }
5029 
5030   unsigned BaseOpc;
5031   ISD::CondCode CC;
5032   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5033 
5034   switch (Op.getOpcode()) {
5035   default:
5036     llvm_unreachable("Unhandled reduction");
5037   case ISD::VECREDUCE_AND:
5038   case ISD::VP_REDUCE_AND: {
5039     // vcpop ~x == 0
5040     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5041     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5042     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5043     CC = ISD::SETEQ;
5044     BaseOpc = ISD::AND;
5045     break;
5046   }
5047   case ISD::VECREDUCE_OR:
5048   case ISD::VP_REDUCE_OR:
5049     // vcpop x != 0
5050     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5051     CC = ISD::SETNE;
5052     BaseOpc = ISD::OR;
5053     break;
5054   case ISD::VECREDUCE_XOR:
5055   case ISD::VP_REDUCE_XOR: {
5056     // ((vcpop x) & 1) != 0
5057     SDValue One = DAG.getConstant(1, DL, XLenVT);
5058     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5059     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5060     CC = ISD::SETNE;
5061     BaseOpc = ISD::XOR;
5062     break;
5063   }
5064   }
5065 
5066   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5067 
5068   if (!IsVP)
5069     return SetCC;
5070 
5071   // Now include the start value in the operation.
5072   // Note that we must return the start value when no elements are operated
5073   // upon. The vcpop instructions we've emitted in each case above will return
5074   // 0 for an inactive vector, and so we've already received the neutral value:
5075   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5076   // can simply include the start value.
5077   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5078 }
5079 
5080 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5081                                             SelectionDAG &DAG) const {
5082   SDLoc DL(Op);
5083   SDValue Vec = Op.getOperand(0);
5084   EVT VecEVT = Vec.getValueType();
5085 
5086   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5087 
5088   // Due to ordering in legalize types we may have a vector type that needs to
5089   // be split. Do that manually so we can get down to a legal type.
5090   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5091          TargetLowering::TypeSplitVector) {
5092     SDValue Lo, Hi;
5093     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5094     VecEVT = Lo.getValueType();
5095     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5096   }
5097 
5098   // TODO: The type may need to be widened rather than split. Or widened before
5099   // it can be split.
5100   if (!isTypeLegal(VecEVT))
5101     return SDValue();
5102 
5103   MVT VecVT = VecEVT.getSimpleVT();
5104   MVT VecEltVT = VecVT.getVectorElementType();
5105   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5106 
5107   MVT ContainerVT = VecVT;
5108   if (VecVT.isFixedLengthVector()) {
5109     ContainerVT = getContainerForFixedLengthVector(VecVT);
5110     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5111   }
5112 
5113   MVT M1VT = getLMUL1VT(ContainerVT);
5114   MVT XLenVT = Subtarget.getXLenVT();
5115 
5116   SDValue Mask, VL;
5117   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5118 
5119   SDValue NeutralElem =
5120       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5121   SDValue IdentitySplat =
5122       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5123                        M1VT, DL, DAG, Subtarget);
5124   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5125                                   IdentitySplat, Mask, VL);
5126   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5127                              DAG.getConstant(0, DL, XLenVT));
5128   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5129 }
5130 
5131 // Given a reduction op, this function returns the matching reduction opcode,
5132 // the vector SDValue and the scalar SDValue required to lower this to a
5133 // RISCVISD node.
5134 static std::tuple<unsigned, SDValue, SDValue>
5135 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5136   SDLoc DL(Op);
5137   auto Flags = Op->getFlags();
5138   unsigned Opcode = Op.getOpcode();
5139   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5140   switch (Opcode) {
5141   default:
5142     llvm_unreachable("Unhandled reduction");
5143   case ISD::VECREDUCE_FADD: {
5144     // Use positive zero if we can. It is cheaper to materialize.
5145     SDValue Zero =
5146         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5147     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5148   }
5149   case ISD::VECREDUCE_SEQ_FADD:
5150     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5151                            Op.getOperand(0));
5152   case ISD::VECREDUCE_FMIN:
5153     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5154                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5155   case ISD::VECREDUCE_FMAX:
5156     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5157                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5158   }
5159 }
5160 
5161 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5162                                               SelectionDAG &DAG) const {
5163   SDLoc DL(Op);
5164   MVT VecEltVT = Op.getSimpleValueType();
5165 
5166   unsigned RVVOpcode;
5167   SDValue VectorVal, ScalarVal;
5168   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5169       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5170   MVT VecVT = VectorVal.getSimpleValueType();
5171 
5172   MVT ContainerVT = VecVT;
5173   if (VecVT.isFixedLengthVector()) {
5174     ContainerVT = getContainerForFixedLengthVector(VecVT);
5175     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5176   }
5177 
5178   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5179   MVT XLenVT = Subtarget.getXLenVT();
5180 
5181   SDValue Mask, VL;
5182   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5183 
5184   SDValue ScalarSplat =
5185       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5186                        M1VT, DL, DAG, Subtarget);
5187   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5188                                   VectorVal, ScalarSplat, Mask, VL);
5189   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5190                      DAG.getConstant(0, DL, XLenVT));
5191 }
5192 
5193 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5194   switch (ISDOpcode) {
5195   default:
5196     llvm_unreachable("Unhandled reduction");
5197   case ISD::VP_REDUCE_ADD:
5198     return RISCVISD::VECREDUCE_ADD_VL;
5199   case ISD::VP_REDUCE_UMAX:
5200     return RISCVISD::VECREDUCE_UMAX_VL;
5201   case ISD::VP_REDUCE_SMAX:
5202     return RISCVISD::VECREDUCE_SMAX_VL;
5203   case ISD::VP_REDUCE_UMIN:
5204     return RISCVISD::VECREDUCE_UMIN_VL;
5205   case ISD::VP_REDUCE_SMIN:
5206     return RISCVISD::VECREDUCE_SMIN_VL;
5207   case ISD::VP_REDUCE_AND:
5208     return RISCVISD::VECREDUCE_AND_VL;
5209   case ISD::VP_REDUCE_OR:
5210     return RISCVISD::VECREDUCE_OR_VL;
5211   case ISD::VP_REDUCE_XOR:
5212     return RISCVISD::VECREDUCE_XOR_VL;
5213   case ISD::VP_REDUCE_FADD:
5214     return RISCVISD::VECREDUCE_FADD_VL;
5215   case ISD::VP_REDUCE_SEQ_FADD:
5216     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5217   case ISD::VP_REDUCE_FMAX:
5218     return RISCVISD::VECREDUCE_FMAX_VL;
5219   case ISD::VP_REDUCE_FMIN:
5220     return RISCVISD::VECREDUCE_FMIN_VL;
5221   }
5222 }
5223 
5224 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5225                                            SelectionDAG &DAG) const {
5226   SDLoc DL(Op);
5227   SDValue Vec = Op.getOperand(1);
5228   EVT VecEVT = Vec.getValueType();
5229 
5230   // TODO: The type may need to be widened rather than split. Or widened before
5231   // it can be split.
5232   if (!isTypeLegal(VecEVT))
5233     return SDValue();
5234 
5235   MVT VecVT = VecEVT.getSimpleVT();
5236   MVT VecEltVT = VecVT.getVectorElementType();
5237   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5238 
5239   MVT ContainerVT = VecVT;
5240   if (VecVT.isFixedLengthVector()) {
5241     ContainerVT = getContainerForFixedLengthVector(VecVT);
5242     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5243   }
5244 
5245   SDValue VL = Op.getOperand(3);
5246   SDValue Mask = Op.getOperand(2);
5247 
5248   MVT M1VT = getLMUL1VT(ContainerVT);
5249   MVT XLenVT = Subtarget.getXLenVT();
5250   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5251 
5252   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5253                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5254                                         DL, DAG, Subtarget);
5255   SDValue Reduction =
5256       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5257   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5258                              DAG.getConstant(0, DL, XLenVT));
5259   if (!VecVT.isInteger())
5260     return Elt0;
5261   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5262 }
5263 
5264 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5265                                                    SelectionDAG &DAG) const {
5266   SDValue Vec = Op.getOperand(0);
5267   SDValue SubVec = Op.getOperand(1);
5268   MVT VecVT = Vec.getSimpleValueType();
5269   MVT SubVecVT = SubVec.getSimpleValueType();
5270 
5271   SDLoc DL(Op);
5272   MVT XLenVT = Subtarget.getXLenVT();
5273   unsigned OrigIdx = Op.getConstantOperandVal(2);
5274   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5275 
5276   // We don't have the ability to slide mask vectors up indexed by their i1
5277   // elements; the smallest we can do is i8. Often we are able to bitcast to
5278   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5279   // into a scalable one, we might not necessarily have enough scalable
5280   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5281   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5282       (OrigIdx != 0 || !Vec.isUndef())) {
5283     if (VecVT.getVectorMinNumElements() >= 8 &&
5284         SubVecVT.getVectorMinNumElements() >= 8) {
5285       assert(OrigIdx % 8 == 0 && "Invalid index");
5286       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5287              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5288              "Unexpected mask vector lowering");
5289       OrigIdx /= 8;
5290       SubVecVT =
5291           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5292                            SubVecVT.isScalableVector());
5293       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5294                                VecVT.isScalableVector());
5295       Vec = DAG.getBitcast(VecVT, Vec);
5296       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5297     } else {
5298       // We can't slide this mask vector up indexed by its i1 elements.
5299       // This poses a problem when we wish to insert a scalable vector which
5300       // can't be re-expressed as a larger type. Just choose the slow path and
5301       // extend to a larger type, then truncate back down.
5302       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5303       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5304       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5305       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5306       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5307                         Op.getOperand(2));
5308       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5309       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5310     }
5311   }
5312 
5313   // If the subvector vector is a fixed-length type, we cannot use subregister
5314   // manipulation to simplify the codegen; we don't know which register of a
5315   // LMUL group contains the specific subvector as we only know the minimum
5316   // register size. Therefore we must slide the vector group up the full
5317   // amount.
5318   if (SubVecVT.isFixedLengthVector()) {
5319     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5320       return Op;
5321     MVT ContainerVT = VecVT;
5322     if (VecVT.isFixedLengthVector()) {
5323       ContainerVT = getContainerForFixedLengthVector(VecVT);
5324       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5325     }
5326     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5327                          DAG.getUNDEF(ContainerVT), SubVec,
5328                          DAG.getConstant(0, DL, XLenVT));
5329     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5330       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5331       return DAG.getBitcast(Op.getValueType(), SubVec);
5332     }
5333     SDValue Mask =
5334         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5335     // Set the vector length to only the number of elements we care about. Note
5336     // that for slideup this includes the offset.
5337     SDValue VL =
5338         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5339     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5340     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5341                                   SubVec, SlideupAmt, Mask, VL);
5342     if (VecVT.isFixedLengthVector())
5343       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5344     return DAG.getBitcast(Op.getValueType(), Slideup);
5345   }
5346 
5347   unsigned SubRegIdx, RemIdx;
5348   std::tie(SubRegIdx, RemIdx) =
5349       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5350           VecVT, SubVecVT, OrigIdx, TRI);
5351 
5352   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5353   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5354                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5355                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5356 
5357   // 1. If the Idx has been completely eliminated and this subvector's size is
5358   // a vector register or a multiple thereof, or the surrounding elements are
5359   // undef, then this is a subvector insert which naturally aligns to a vector
5360   // register. These can easily be handled using subregister manipulation.
5361   // 2. If the subvector is smaller than a vector register, then the insertion
5362   // must preserve the undisturbed elements of the register. We do this by
5363   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5364   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5365   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5366   // LMUL=1 type back into the larger vector (resolving to another subregister
5367   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5368   // to avoid allocating a large register group to hold our subvector.
5369   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5370     return Op;
5371 
5372   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5373   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5374   // (in our case undisturbed). This means we can set up a subvector insertion
5375   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5376   // size of the subvector.
5377   MVT InterSubVT = VecVT;
5378   SDValue AlignedExtract = Vec;
5379   unsigned AlignedIdx = OrigIdx - RemIdx;
5380   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5381     InterSubVT = getLMUL1VT(VecVT);
5382     // Extract a subvector equal to the nearest full vector register type. This
5383     // should resolve to a EXTRACT_SUBREG instruction.
5384     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5385                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5386   }
5387 
5388   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5389   // For scalable vectors this must be further multiplied by vscale.
5390   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5391 
5392   SDValue Mask, VL;
5393   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5394 
5395   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5396   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5397   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5398   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5399 
5400   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5401                        DAG.getUNDEF(InterSubVT), SubVec,
5402                        DAG.getConstant(0, DL, XLenVT));
5403 
5404   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5405                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5406 
5407   // If required, insert this subvector back into the correct vector register.
5408   // This should resolve to an INSERT_SUBREG instruction.
5409   if (VecVT.bitsGT(InterSubVT))
5410     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5411                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5412 
5413   // We might have bitcast from a mask type: cast back to the original type if
5414   // required.
5415   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5416 }
5417 
5418 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5419                                                     SelectionDAG &DAG) const {
5420   SDValue Vec = Op.getOperand(0);
5421   MVT SubVecVT = Op.getSimpleValueType();
5422   MVT VecVT = Vec.getSimpleValueType();
5423 
5424   SDLoc DL(Op);
5425   MVT XLenVT = Subtarget.getXLenVT();
5426   unsigned OrigIdx = Op.getConstantOperandVal(1);
5427   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5428 
5429   // We don't have the ability to slide mask vectors down indexed by their i1
5430   // elements; the smallest we can do is i8. Often we are able to bitcast to
5431   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5432   // from a scalable one, we might not necessarily have enough scalable
5433   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5434   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5435     if (VecVT.getVectorMinNumElements() >= 8 &&
5436         SubVecVT.getVectorMinNumElements() >= 8) {
5437       assert(OrigIdx % 8 == 0 && "Invalid index");
5438       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5439              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5440              "Unexpected mask vector lowering");
5441       OrigIdx /= 8;
5442       SubVecVT =
5443           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5444                            SubVecVT.isScalableVector());
5445       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5446                                VecVT.isScalableVector());
5447       Vec = DAG.getBitcast(VecVT, Vec);
5448     } else {
5449       // We can't slide this mask vector down, indexed by its i1 elements.
5450       // This poses a problem when we wish to extract a scalable vector which
5451       // can't be re-expressed as a larger type. Just choose the slow path and
5452       // extend to a larger type, then truncate back down.
5453       // TODO: We could probably improve this when extracting certain fixed
5454       // from fixed, where we can extract as i8 and shift the correct element
5455       // right to reach the desired subvector?
5456       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5457       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5458       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5459       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5460                         Op.getOperand(1));
5461       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5462       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5463     }
5464   }
5465 
5466   // If the subvector vector is a fixed-length type, we cannot use subregister
5467   // manipulation to simplify the codegen; we don't know which register of a
5468   // LMUL group contains the specific subvector as we only know the minimum
5469   // register size. Therefore we must slide the vector group down the full
5470   // amount.
5471   if (SubVecVT.isFixedLengthVector()) {
5472     // With an index of 0 this is a cast-like subvector, which can be performed
5473     // with subregister operations.
5474     if (OrigIdx == 0)
5475       return Op;
5476     MVT ContainerVT = VecVT;
5477     if (VecVT.isFixedLengthVector()) {
5478       ContainerVT = getContainerForFixedLengthVector(VecVT);
5479       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5480     }
5481     SDValue Mask =
5482         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5483     // Set the vector length to only the number of elements we care about. This
5484     // avoids sliding down elements we're going to discard straight away.
5485     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5486     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5487     SDValue Slidedown =
5488         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5489                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5490     // Now we can use a cast-like subvector extract to get the result.
5491     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5492                             DAG.getConstant(0, DL, XLenVT));
5493     return DAG.getBitcast(Op.getValueType(), Slidedown);
5494   }
5495 
5496   unsigned SubRegIdx, RemIdx;
5497   std::tie(SubRegIdx, RemIdx) =
5498       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5499           VecVT, SubVecVT, OrigIdx, TRI);
5500 
5501   // If the Idx has been completely eliminated then this is a subvector extract
5502   // which naturally aligns to a vector register. These can easily be handled
5503   // using subregister manipulation.
5504   if (RemIdx == 0)
5505     return Op;
5506 
5507   // Else we must shift our vector register directly to extract the subvector.
5508   // Do this using VSLIDEDOWN.
5509 
5510   // If the vector type is an LMUL-group type, extract a subvector equal to the
5511   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5512   // instruction.
5513   MVT InterSubVT = VecVT;
5514   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5515     InterSubVT = getLMUL1VT(VecVT);
5516     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5517                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5518   }
5519 
5520   // Slide this vector register down by the desired number of elements in order
5521   // to place the desired subvector starting at element 0.
5522   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5523   // For scalable vectors this must be further multiplied by vscale.
5524   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5525 
5526   SDValue Mask, VL;
5527   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5528   SDValue Slidedown =
5529       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5530                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5531 
5532   // Now the vector is in the right position, extract our final subvector. This
5533   // should resolve to a COPY.
5534   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5535                           DAG.getConstant(0, DL, XLenVT));
5536 
5537   // We might have bitcast from a mask type: cast back to the original type if
5538   // required.
5539   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5540 }
5541 
5542 // Lower step_vector to the vid instruction. Any non-identity step value must
5543 // be accounted for my manual expansion.
5544 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5545                                               SelectionDAG &DAG) const {
5546   SDLoc DL(Op);
5547   MVT VT = Op.getSimpleValueType();
5548   MVT XLenVT = Subtarget.getXLenVT();
5549   SDValue Mask, VL;
5550   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5551   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5552   uint64_t StepValImm = Op.getConstantOperandVal(0);
5553   if (StepValImm != 1) {
5554     if (isPowerOf2_64(StepValImm)) {
5555       SDValue StepVal =
5556           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5557                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5558       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5559     } else {
5560       SDValue StepVal = lowerScalarSplat(
5561           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5562           VL, VT, DL, DAG, Subtarget);
5563       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5564     }
5565   }
5566   return StepVec;
5567 }
5568 
5569 // Implement vector_reverse using vrgather.vv with indices determined by
5570 // subtracting the id of each element from (VLMAX-1). This will convert
5571 // the indices like so:
5572 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5573 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5574 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5575                                                  SelectionDAG &DAG) const {
5576   SDLoc DL(Op);
5577   MVT VecVT = Op.getSimpleValueType();
5578   unsigned EltSize = VecVT.getScalarSizeInBits();
5579   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5580 
5581   unsigned MaxVLMAX = 0;
5582   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5583   if (VectorBitsMax != 0)
5584     MaxVLMAX =
5585         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5586 
5587   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5588   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5589 
5590   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5591   // to use vrgatherei16.vv.
5592   // TODO: It's also possible to use vrgatherei16.vv for other types to
5593   // decrease register width for the index calculation.
5594   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5595     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5596     // Reverse each half, then reassemble them in reverse order.
5597     // NOTE: It's also possible that after splitting that VLMAX no longer
5598     // requires vrgatherei16.vv.
5599     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5600       SDValue Lo, Hi;
5601       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5602       EVT LoVT, HiVT;
5603       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5604       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5605       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5606       // Reassemble the low and high pieces reversed.
5607       // FIXME: This is a CONCAT_VECTORS.
5608       SDValue Res =
5609           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5610                       DAG.getIntPtrConstant(0, DL));
5611       return DAG.getNode(
5612           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5613           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5614     }
5615 
5616     // Just promote the int type to i16 which will double the LMUL.
5617     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5618     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5619   }
5620 
5621   MVT XLenVT = Subtarget.getXLenVT();
5622   SDValue Mask, VL;
5623   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5624 
5625   // Calculate VLMAX-1 for the desired SEW.
5626   unsigned MinElts = VecVT.getVectorMinNumElements();
5627   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5628                               DAG.getConstant(MinElts, DL, XLenVT));
5629   SDValue VLMinus1 =
5630       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5631 
5632   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5633   bool IsRV32E64 =
5634       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5635   SDValue SplatVL;
5636   if (!IsRV32E64)
5637     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5638   else
5639     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5640                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5641 
5642   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5643   SDValue Indices =
5644       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5645 
5646   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5647 }
5648 
5649 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5650                                                 SelectionDAG &DAG) const {
5651   SDLoc DL(Op);
5652   SDValue V1 = Op.getOperand(0);
5653   SDValue V2 = Op.getOperand(1);
5654   MVT XLenVT = Subtarget.getXLenVT();
5655   MVT VecVT = Op.getSimpleValueType();
5656 
5657   unsigned MinElts = VecVT.getVectorMinNumElements();
5658   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5659                               DAG.getConstant(MinElts, DL, XLenVT));
5660 
5661   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5662   SDValue DownOffset, UpOffset;
5663   if (ImmValue >= 0) {
5664     // The operand is a TargetConstant, we need to rebuild it as a regular
5665     // constant.
5666     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5667     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5668   } else {
5669     // The operand is a TargetConstant, we need to rebuild it as a regular
5670     // constant rather than negating the original operand.
5671     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5672     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5673   }
5674 
5675   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5676   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5677 
5678   SDValue SlideDown =
5679       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5680                   DownOffset, TrueMask, UpOffset);
5681   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5682                      TrueMask,
5683                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5684 }
5685 
5686 SDValue
5687 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5688                                                      SelectionDAG &DAG) const {
5689   SDLoc DL(Op);
5690   auto *Load = cast<LoadSDNode>(Op);
5691 
5692   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5693                                         Load->getMemoryVT(),
5694                                         *Load->getMemOperand()) &&
5695          "Expecting a correctly-aligned load");
5696 
5697   MVT VT = Op.getSimpleValueType();
5698   MVT XLenVT = Subtarget.getXLenVT();
5699   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5700 
5701   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5702 
5703   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5704   SDValue IntID = DAG.getTargetConstant(
5705       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5706   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5707   if (!IsMaskOp)
5708     Ops.push_back(DAG.getUNDEF(ContainerVT));
5709   Ops.push_back(Load->getBasePtr());
5710   Ops.push_back(VL);
5711   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5712   SDValue NewLoad =
5713       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5714                               Load->getMemoryVT(), Load->getMemOperand());
5715 
5716   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5717   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5718 }
5719 
5720 SDValue
5721 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5722                                                       SelectionDAG &DAG) const {
5723   SDLoc DL(Op);
5724   auto *Store = cast<StoreSDNode>(Op);
5725 
5726   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5727                                         Store->getMemoryVT(),
5728                                         *Store->getMemOperand()) &&
5729          "Expecting a correctly-aligned store");
5730 
5731   SDValue StoreVal = Store->getValue();
5732   MVT VT = StoreVal.getSimpleValueType();
5733   MVT XLenVT = Subtarget.getXLenVT();
5734 
5735   // If the size less than a byte, we need to pad with zeros to make a byte.
5736   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5737     VT = MVT::v8i1;
5738     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5739                            DAG.getConstant(0, DL, VT), StoreVal,
5740                            DAG.getIntPtrConstant(0, DL));
5741   }
5742 
5743   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5744 
5745   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5746 
5747   SDValue NewValue =
5748       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5749 
5750   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5751   SDValue IntID = DAG.getTargetConstant(
5752       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5753   return DAG.getMemIntrinsicNode(
5754       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5755       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5756       Store->getMemoryVT(), Store->getMemOperand());
5757 }
5758 
5759 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5760                                              SelectionDAG &DAG) const {
5761   SDLoc DL(Op);
5762   MVT VT = Op.getSimpleValueType();
5763 
5764   const auto *MemSD = cast<MemSDNode>(Op);
5765   EVT MemVT = MemSD->getMemoryVT();
5766   MachineMemOperand *MMO = MemSD->getMemOperand();
5767   SDValue Chain = MemSD->getChain();
5768   SDValue BasePtr = MemSD->getBasePtr();
5769 
5770   SDValue Mask, PassThru, VL;
5771   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5772     Mask = VPLoad->getMask();
5773     PassThru = DAG.getUNDEF(VT);
5774     VL = VPLoad->getVectorLength();
5775   } else {
5776     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5777     Mask = MLoad->getMask();
5778     PassThru = MLoad->getPassThru();
5779   }
5780 
5781   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5782 
5783   MVT XLenVT = Subtarget.getXLenVT();
5784 
5785   MVT ContainerVT = VT;
5786   if (VT.isFixedLengthVector()) {
5787     ContainerVT = getContainerForFixedLengthVector(VT);
5788     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5789     if (!IsUnmasked) {
5790       MVT MaskVT =
5791           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5792       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5793     }
5794   }
5795 
5796   if (!VL)
5797     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5798 
5799   unsigned IntID =
5800       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5801   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5802   if (IsUnmasked)
5803     Ops.push_back(DAG.getUNDEF(ContainerVT));
5804   else
5805     Ops.push_back(PassThru);
5806   Ops.push_back(BasePtr);
5807   if (!IsUnmasked)
5808     Ops.push_back(Mask);
5809   Ops.push_back(VL);
5810   if (!IsUnmasked)
5811     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5812 
5813   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5814 
5815   SDValue Result =
5816       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5817   Chain = Result.getValue(1);
5818 
5819   if (VT.isFixedLengthVector())
5820     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5821 
5822   return DAG.getMergeValues({Result, Chain}, DL);
5823 }
5824 
5825 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5826                                               SelectionDAG &DAG) const {
5827   SDLoc DL(Op);
5828 
5829   const auto *MemSD = cast<MemSDNode>(Op);
5830   EVT MemVT = MemSD->getMemoryVT();
5831   MachineMemOperand *MMO = MemSD->getMemOperand();
5832   SDValue Chain = MemSD->getChain();
5833   SDValue BasePtr = MemSD->getBasePtr();
5834   SDValue Val, Mask, VL;
5835 
5836   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5837     Val = VPStore->getValue();
5838     Mask = VPStore->getMask();
5839     VL = VPStore->getVectorLength();
5840   } else {
5841     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5842     Val = MStore->getValue();
5843     Mask = MStore->getMask();
5844   }
5845 
5846   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5847 
5848   MVT VT = Val.getSimpleValueType();
5849   MVT XLenVT = Subtarget.getXLenVT();
5850 
5851   MVT ContainerVT = VT;
5852   if (VT.isFixedLengthVector()) {
5853     ContainerVT = getContainerForFixedLengthVector(VT);
5854 
5855     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5856     if (!IsUnmasked) {
5857       MVT MaskVT =
5858           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5859       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5860     }
5861   }
5862 
5863   if (!VL)
5864     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5865 
5866   unsigned IntID =
5867       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5868   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5869   Ops.push_back(Val);
5870   Ops.push_back(BasePtr);
5871   if (!IsUnmasked)
5872     Ops.push_back(Mask);
5873   Ops.push_back(VL);
5874 
5875   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5876                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5877 }
5878 
5879 SDValue
5880 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5881                                                       SelectionDAG &DAG) const {
5882   MVT InVT = Op.getOperand(0).getSimpleValueType();
5883   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5884 
5885   MVT VT = Op.getSimpleValueType();
5886 
5887   SDValue Op1 =
5888       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5889   SDValue Op2 =
5890       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5891 
5892   SDLoc DL(Op);
5893   SDValue VL =
5894       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5895 
5896   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5897   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5898 
5899   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5900                             Op.getOperand(2), Mask, VL);
5901 
5902   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5903 }
5904 
5905 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5906     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5907   MVT VT = Op.getSimpleValueType();
5908 
5909   if (VT.getVectorElementType() == MVT::i1)
5910     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5911 
5912   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5913 }
5914 
5915 SDValue
5916 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5917                                                       SelectionDAG &DAG) const {
5918   unsigned Opc;
5919   switch (Op.getOpcode()) {
5920   default: llvm_unreachable("Unexpected opcode!");
5921   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5922   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5923   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5924   }
5925 
5926   return lowerToScalableOp(Op, DAG, Opc);
5927 }
5928 
5929 // Lower vector ABS to smax(X, sub(0, X)).
5930 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5931   SDLoc DL(Op);
5932   MVT VT = Op.getSimpleValueType();
5933   SDValue X = Op.getOperand(0);
5934 
5935   assert(VT.isFixedLengthVector() && "Unexpected type");
5936 
5937   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5938   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5939 
5940   SDValue Mask, VL;
5941   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5942 
5943   SDValue SplatZero = DAG.getNode(
5944       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5945       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5946   SDValue NegX =
5947       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5948   SDValue Max =
5949       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5950 
5951   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5952 }
5953 
5954 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5955     SDValue Op, SelectionDAG &DAG) const {
5956   SDLoc DL(Op);
5957   MVT VT = Op.getSimpleValueType();
5958   SDValue Mag = Op.getOperand(0);
5959   SDValue Sign = Op.getOperand(1);
5960   assert(Mag.getValueType() == Sign.getValueType() &&
5961          "Can only handle COPYSIGN with matching types.");
5962 
5963   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5964   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5965   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5966 
5967   SDValue Mask, VL;
5968   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5969 
5970   SDValue CopySign =
5971       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5972 
5973   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5974 }
5975 
5976 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5977     SDValue Op, SelectionDAG &DAG) const {
5978   MVT VT = Op.getSimpleValueType();
5979   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5980 
5981   MVT I1ContainerVT =
5982       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5983 
5984   SDValue CC =
5985       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5986   SDValue Op1 =
5987       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5988   SDValue Op2 =
5989       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5990 
5991   SDLoc DL(Op);
5992   SDValue Mask, VL;
5993   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5994 
5995   SDValue Select =
5996       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5997 
5998   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5999 }
6000 
6001 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6002                                                unsigned NewOpc,
6003                                                bool HasMask) const {
6004   MVT VT = Op.getSimpleValueType();
6005   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6006 
6007   // Create list of operands by converting existing ones to scalable types.
6008   SmallVector<SDValue, 6> Ops;
6009   for (const SDValue &V : Op->op_values()) {
6010     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6011 
6012     // Pass through non-vector operands.
6013     if (!V.getValueType().isVector()) {
6014       Ops.push_back(V);
6015       continue;
6016     }
6017 
6018     // "cast" fixed length vector to a scalable vector.
6019     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6020            "Only fixed length vectors are supported!");
6021     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6022   }
6023 
6024   SDLoc DL(Op);
6025   SDValue Mask, VL;
6026   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6027   if (HasMask)
6028     Ops.push_back(Mask);
6029   Ops.push_back(VL);
6030 
6031   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6032   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6033 }
6034 
6035 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6036 // * Operands of each node are assumed to be in the same order.
6037 // * The EVL operand is promoted from i32 to i64 on RV64.
6038 // * Fixed-length vectors are converted to their scalable-vector container
6039 //   types.
6040 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6041                                        unsigned RISCVISDOpc) const {
6042   SDLoc DL(Op);
6043   MVT VT = Op.getSimpleValueType();
6044   SmallVector<SDValue, 4> Ops;
6045 
6046   for (const auto &OpIdx : enumerate(Op->ops())) {
6047     SDValue V = OpIdx.value();
6048     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6049     // Pass through operands which aren't fixed-length vectors.
6050     if (!V.getValueType().isFixedLengthVector()) {
6051       Ops.push_back(V);
6052       continue;
6053     }
6054     // "cast" fixed length vector to a scalable vector.
6055     MVT OpVT = V.getSimpleValueType();
6056     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6057     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6058            "Only fixed length vectors are supported!");
6059     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6060   }
6061 
6062   if (!VT.isFixedLengthVector())
6063     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6064 
6065   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6066 
6067   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6068 
6069   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6070 }
6071 
6072 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6073                                               SelectionDAG &DAG) const {
6074   SDLoc DL(Op);
6075   MVT VT = Op.getSimpleValueType();
6076 
6077   SDValue Src = Op.getOperand(0);
6078   // NOTE: Mask is dropped.
6079   SDValue VL = Op.getOperand(2);
6080 
6081   MVT ContainerVT = VT;
6082   if (VT.isFixedLengthVector()) {
6083     ContainerVT = getContainerForFixedLengthVector(VT);
6084     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6085     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6086   }
6087 
6088   MVT XLenVT = Subtarget.getXLenVT();
6089   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6090   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6091                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6092 
6093   SDValue SplatValue =
6094       DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT);
6095   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6096                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6097 
6098   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6099                                Splat, ZeroSplat, VL);
6100   if (!VT.isFixedLengthVector())
6101     return Result;
6102   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6103 }
6104 
6105 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6106                                                 SelectionDAG &DAG) const {
6107   SDLoc DL(Op);
6108   MVT VT = Op.getSimpleValueType();
6109 
6110   SDValue Op1 = Op.getOperand(0);
6111   SDValue Op2 = Op.getOperand(1);
6112   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6113   // NOTE: Mask is dropped.
6114   SDValue VL = Op.getOperand(4);
6115 
6116   MVT ContainerVT = VT;
6117   if (VT.isFixedLengthVector()) {
6118     ContainerVT = getContainerForFixedLengthVector(VT);
6119     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6120     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6121   }
6122 
6123   SDValue Result;
6124   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6125 
6126   switch (Condition) {
6127   default:
6128     break;
6129   // X != Y  --> (X^Y)
6130   case ISD::SETNE:
6131     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6132     break;
6133   // X == Y  --> ~(X^Y)
6134   case ISD::SETEQ: {
6135     SDValue Temp =
6136         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6137     Result =
6138         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6139     break;
6140   }
6141   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6142   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6143   case ISD::SETGT:
6144   case ISD::SETULT: {
6145     SDValue Temp =
6146         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6147     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6148     break;
6149   }
6150   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6151   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6152   case ISD::SETLT:
6153   case ISD::SETUGT: {
6154     SDValue Temp =
6155         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6156     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6157     break;
6158   }
6159   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6160   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6161   case ISD::SETGE:
6162   case ISD::SETULE: {
6163     SDValue Temp =
6164         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6165     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6166     break;
6167   }
6168   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6169   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6170   case ISD::SETLE:
6171   case ISD::SETUGE: {
6172     SDValue Temp =
6173         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6174     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6175     break;
6176   }
6177   }
6178 
6179   if (!VT.isFixedLengthVector())
6180     return Result;
6181   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6182 }
6183 
6184 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6185 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6186                                                 unsigned RISCVISDOpc) const {
6187   SDLoc DL(Op);
6188 
6189   SDValue Src = Op.getOperand(0);
6190   SDValue Mask = Op.getOperand(1);
6191   SDValue VL = Op.getOperand(2);
6192 
6193   MVT DstVT = Op.getSimpleValueType();
6194   MVT SrcVT = Src.getSimpleValueType();
6195   if (DstVT.isFixedLengthVector()) {
6196     DstVT = getContainerForFixedLengthVector(DstVT);
6197     SrcVT = getContainerForFixedLengthVector(SrcVT);
6198     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6199     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6200     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6201   }
6202 
6203   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6204                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6205                                 ? RISCVISD::VSEXT_VL
6206                                 : RISCVISD::VZEXT_VL;
6207 
6208   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6209   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6210 
6211   SDValue Result;
6212   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6213     if (SrcVT.isInteger()) {
6214       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6215 
6216       // Do we need to do any pre-widening before converting?
6217       if (SrcEltSize == 1) {
6218         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6219         MVT XLenVT = Subtarget.getXLenVT();
6220         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6221         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6222                                         DAG.getUNDEF(IntVT), Zero, VL);
6223         SDValue One = DAG.getConstant(
6224             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6225         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6226                                        DAG.getUNDEF(IntVT), One, VL);
6227         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6228                           ZeroSplat, VL);
6229       } else if (DstEltSize > (2 * SrcEltSize)) {
6230         // Widen before converting.
6231         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6232                                      DstVT.getVectorElementCount());
6233         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6234       }
6235 
6236       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6237     } else {
6238       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6239              "Wrong input/output vector types");
6240 
6241       // Convert f16 to f32 then convert f32 to i64.
6242       if (DstEltSize > (2 * SrcEltSize)) {
6243         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6244         MVT InterimFVT =
6245             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6246         Src =
6247             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6248       }
6249 
6250       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6251     }
6252   } else { // Narrowing + Conversion
6253     if (SrcVT.isInteger()) {
6254       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6255       // First do a narrowing convert to an FP type half the size, then round
6256       // the FP type to a small FP type if needed.
6257 
6258       MVT InterimFVT = DstVT;
6259       if (SrcEltSize > (2 * DstEltSize)) {
6260         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6261         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6262         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6263       }
6264 
6265       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6266 
6267       if (InterimFVT != DstVT) {
6268         Src = Result;
6269         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6270       }
6271     } else {
6272       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6273              "Wrong input/output vector types");
6274       // First do a narrowing conversion to an integer half the size, then
6275       // truncate if needed.
6276 
6277       if (DstEltSize == 1) {
6278         // First convert to the same size integer, then convert to mask using
6279         // setcc.
6280         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6281         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6282                                           DstVT.getVectorElementCount());
6283         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6284 
6285         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6286         // otherwise the conversion was undefined.
6287         MVT XLenVT = Subtarget.getXLenVT();
6288         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6289         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6290                                 DAG.getUNDEF(InterimIVT), SplatZero);
6291         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6292                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6293       } else {
6294         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6295                                           DstVT.getVectorElementCount());
6296 
6297         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6298 
6299         while (InterimIVT != DstVT) {
6300           SrcEltSize /= 2;
6301           Src = Result;
6302           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6303                                         DstVT.getVectorElementCount());
6304           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6305                                Src, Mask, VL);
6306         }
6307       }
6308     }
6309   }
6310 
6311   MVT VT = Op.getSimpleValueType();
6312   if (!VT.isFixedLengthVector())
6313     return Result;
6314   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6315 }
6316 
6317 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6318                                             unsigned MaskOpc,
6319                                             unsigned VecOpc) const {
6320   MVT VT = Op.getSimpleValueType();
6321   if (VT.getVectorElementType() != MVT::i1)
6322     return lowerVPOp(Op, DAG, VecOpc);
6323 
6324   // It is safe to drop mask parameter as masked-off elements are undef.
6325   SDValue Op1 = Op->getOperand(0);
6326   SDValue Op2 = Op->getOperand(1);
6327   SDValue VL = Op->getOperand(3);
6328 
6329   MVT ContainerVT = VT;
6330   const bool IsFixed = VT.isFixedLengthVector();
6331   if (IsFixed) {
6332     ContainerVT = getContainerForFixedLengthVector(VT);
6333     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6334     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6335   }
6336 
6337   SDLoc DL(Op);
6338   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6339   if (!IsFixed)
6340     return Val;
6341   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6342 }
6343 
6344 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6345 // matched to a RVV indexed load. The RVV indexed load instructions only
6346 // support the "unsigned unscaled" addressing mode; indices are implicitly
6347 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6348 // signed or scaled indexing is extended to the XLEN value type and scaled
6349 // accordingly.
6350 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6351                                                SelectionDAG &DAG) const {
6352   SDLoc DL(Op);
6353   MVT VT = Op.getSimpleValueType();
6354 
6355   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6356   EVT MemVT = MemSD->getMemoryVT();
6357   MachineMemOperand *MMO = MemSD->getMemOperand();
6358   SDValue Chain = MemSD->getChain();
6359   SDValue BasePtr = MemSD->getBasePtr();
6360 
6361   ISD::LoadExtType LoadExtType;
6362   SDValue Index, Mask, PassThru, VL;
6363 
6364   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6365     Index = VPGN->getIndex();
6366     Mask = VPGN->getMask();
6367     PassThru = DAG.getUNDEF(VT);
6368     VL = VPGN->getVectorLength();
6369     // VP doesn't support extending loads.
6370     LoadExtType = ISD::NON_EXTLOAD;
6371   } else {
6372     // Else it must be a MGATHER.
6373     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6374     Index = MGN->getIndex();
6375     Mask = MGN->getMask();
6376     PassThru = MGN->getPassThru();
6377     LoadExtType = MGN->getExtensionType();
6378   }
6379 
6380   MVT IndexVT = Index.getSimpleValueType();
6381   MVT XLenVT = Subtarget.getXLenVT();
6382 
6383   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6384          "Unexpected VTs!");
6385   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6386   // Targets have to explicitly opt-in for extending vector loads.
6387   assert(LoadExtType == ISD::NON_EXTLOAD &&
6388          "Unexpected extending MGATHER/VP_GATHER");
6389   (void)LoadExtType;
6390 
6391   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6392   // the selection of the masked intrinsics doesn't do this for us.
6393   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6394 
6395   MVT ContainerVT = VT;
6396   if (VT.isFixedLengthVector()) {
6397     // We need to use the larger of the result and index type to determine the
6398     // scalable type to use so we don't increase LMUL for any operand/result.
6399     if (VT.bitsGE(IndexVT)) {
6400       ContainerVT = getContainerForFixedLengthVector(VT);
6401       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6402                                  ContainerVT.getVectorElementCount());
6403     } else {
6404       IndexVT = getContainerForFixedLengthVector(IndexVT);
6405       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6406                                      IndexVT.getVectorElementCount());
6407     }
6408 
6409     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6410 
6411     if (!IsUnmasked) {
6412       MVT MaskVT =
6413           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6414       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6415       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6416     }
6417   }
6418 
6419   if (!VL)
6420     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6421 
6422   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6423     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6424     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6425                                    VL);
6426     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6427                         TrueMask, VL);
6428   }
6429 
6430   unsigned IntID =
6431       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6432   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6433   if (IsUnmasked)
6434     Ops.push_back(DAG.getUNDEF(ContainerVT));
6435   else
6436     Ops.push_back(PassThru);
6437   Ops.push_back(BasePtr);
6438   Ops.push_back(Index);
6439   if (!IsUnmasked)
6440     Ops.push_back(Mask);
6441   Ops.push_back(VL);
6442   if (!IsUnmasked)
6443     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6444 
6445   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6446   SDValue Result =
6447       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6448   Chain = Result.getValue(1);
6449 
6450   if (VT.isFixedLengthVector())
6451     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6452 
6453   return DAG.getMergeValues({Result, Chain}, DL);
6454 }
6455 
6456 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6457 // matched to a RVV indexed store. The RVV indexed store instructions only
6458 // support the "unsigned unscaled" addressing mode; indices are implicitly
6459 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6460 // signed or scaled indexing is extended to the XLEN value type and scaled
6461 // accordingly.
6462 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6463                                                 SelectionDAG &DAG) const {
6464   SDLoc DL(Op);
6465   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6466   EVT MemVT = MemSD->getMemoryVT();
6467   MachineMemOperand *MMO = MemSD->getMemOperand();
6468   SDValue Chain = MemSD->getChain();
6469   SDValue BasePtr = MemSD->getBasePtr();
6470 
6471   bool IsTruncatingStore = false;
6472   SDValue Index, Mask, Val, VL;
6473 
6474   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6475     Index = VPSN->getIndex();
6476     Mask = VPSN->getMask();
6477     Val = VPSN->getValue();
6478     VL = VPSN->getVectorLength();
6479     // VP doesn't support truncating stores.
6480     IsTruncatingStore = false;
6481   } else {
6482     // Else it must be a MSCATTER.
6483     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6484     Index = MSN->getIndex();
6485     Mask = MSN->getMask();
6486     Val = MSN->getValue();
6487     IsTruncatingStore = MSN->isTruncatingStore();
6488   }
6489 
6490   MVT VT = Val.getSimpleValueType();
6491   MVT IndexVT = Index.getSimpleValueType();
6492   MVT XLenVT = Subtarget.getXLenVT();
6493 
6494   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6495          "Unexpected VTs!");
6496   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6497   // Targets have to explicitly opt-in for extending vector loads and
6498   // truncating vector stores.
6499   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6500   (void)IsTruncatingStore;
6501 
6502   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6503   // the selection of the masked intrinsics doesn't do this for us.
6504   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6505 
6506   MVT ContainerVT = VT;
6507   if (VT.isFixedLengthVector()) {
6508     // We need to use the larger of the value and index type to determine the
6509     // scalable type to use so we don't increase LMUL for any operand/result.
6510     if (VT.bitsGE(IndexVT)) {
6511       ContainerVT = getContainerForFixedLengthVector(VT);
6512       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6513                                  ContainerVT.getVectorElementCount());
6514     } else {
6515       IndexVT = getContainerForFixedLengthVector(IndexVT);
6516       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6517                                      IndexVT.getVectorElementCount());
6518     }
6519 
6520     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6521     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6522 
6523     if (!IsUnmasked) {
6524       MVT MaskVT =
6525           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6526       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6527     }
6528   }
6529 
6530   if (!VL)
6531     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6532 
6533   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6534     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6535     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6536                                    VL);
6537     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6538                         TrueMask, VL);
6539   }
6540 
6541   unsigned IntID =
6542       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6543   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6544   Ops.push_back(Val);
6545   Ops.push_back(BasePtr);
6546   Ops.push_back(Index);
6547   if (!IsUnmasked)
6548     Ops.push_back(Mask);
6549   Ops.push_back(VL);
6550 
6551   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6552                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6553 }
6554 
6555 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6556                                                SelectionDAG &DAG) const {
6557   const MVT XLenVT = Subtarget.getXLenVT();
6558   SDLoc DL(Op);
6559   SDValue Chain = Op->getOperand(0);
6560   SDValue SysRegNo = DAG.getTargetConstant(
6561       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6562   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6563   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6564 
6565   // Encoding used for rounding mode in RISCV differs from that used in
6566   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6567   // table, which consists of a sequence of 4-bit fields, each representing
6568   // corresponding FLT_ROUNDS mode.
6569   static const int Table =
6570       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6571       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6572       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6573       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6574       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6575 
6576   SDValue Shift =
6577       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6578   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6579                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6580   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6581                                DAG.getConstant(7, DL, XLenVT));
6582 
6583   return DAG.getMergeValues({Masked, Chain}, DL);
6584 }
6585 
6586 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6587                                                SelectionDAG &DAG) const {
6588   const MVT XLenVT = Subtarget.getXLenVT();
6589   SDLoc DL(Op);
6590   SDValue Chain = Op->getOperand(0);
6591   SDValue RMValue = Op->getOperand(1);
6592   SDValue SysRegNo = DAG.getTargetConstant(
6593       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6594 
6595   // Encoding used for rounding mode in RISCV differs from that used in
6596   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6597   // a table, which consists of a sequence of 4-bit fields, each representing
6598   // corresponding RISCV mode.
6599   static const unsigned Table =
6600       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6601       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6602       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6603       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6604       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6605 
6606   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6607                               DAG.getConstant(2, DL, XLenVT));
6608   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6609                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6610   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6611                         DAG.getConstant(0x7, DL, XLenVT));
6612   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6613                      RMValue);
6614 }
6615 
6616 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6617   switch (IntNo) {
6618   default:
6619     llvm_unreachable("Unexpected Intrinsic");
6620   case Intrinsic::riscv_bcompress:
6621     return RISCVISD::BCOMPRESSW;
6622   case Intrinsic::riscv_bdecompress:
6623     return RISCVISD::BDECOMPRESSW;
6624   case Intrinsic::riscv_bfp:
6625     return RISCVISD::BFPW;
6626   case Intrinsic::riscv_fsl:
6627     return RISCVISD::FSLW;
6628   case Intrinsic::riscv_fsr:
6629     return RISCVISD::FSRW;
6630   }
6631 }
6632 
6633 // Converts the given intrinsic to a i64 operation with any extension.
6634 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6635                                          unsigned IntNo) {
6636   SDLoc DL(N);
6637   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6638   // Deal with the Instruction Operands
6639   SmallVector<SDValue, 3> NewOps;
6640   for (SDValue Op : drop_begin(N->ops()))
6641     // Promote the operand to i64 type
6642     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6643   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6644   // ReplaceNodeResults requires we maintain the same type for the return value.
6645   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6646 }
6647 
6648 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6649 // form of the given Opcode.
6650 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6651   switch (Opcode) {
6652   default:
6653     llvm_unreachable("Unexpected opcode");
6654   case ISD::SHL:
6655     return RISCVISD::SLLW;
6656   case ISD::SRA:
6657     return RISCVISD::SRAW;
6658   case ISD::SRL:
6659     return RISCVISD::SRLW;
6660   case ISD::SDIV:
6661     return RISCVISD::DIVW;
6662   case ISD::UDIV:
6663     return RISCVISD::DIVUW;
6664   case ISD::UREM:
6665     return RISCVISD::REMUW;
6666   case ISD::ROTL:
6667     return RISCVISD::ROLW;
6668   case ISD::ROTR:
6669     return RISCVISD::RORW;
6670   }
6671 }
6672 
6673 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6674 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6675 // otherwise be promoted to i64, making it difficult to select the
6676 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6677 // type i8/i16/i32 is lost.
6678 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6679                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6680   SDLoc DL(N);
6681   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6682   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6683   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6684   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6685   // ReplaceNodeResults requires we maintain the same type for the return value.
6686   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6687 }
6688 
6689 // Converts the given 32-bit operation to a i64 operation with signed extension
6690 // semantic to reduce the signed extension instructions.
6691 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6692   SDLoc DL(N);
6693   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6694   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6695   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6696   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6697                                DAG.getValueType(MVT::i32));
6698   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6699 }
6700 
6701 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6702                                              SmallVectorImpl<SDValue> &Results,
6703                                              SelectionDAG &DAG) const {
6704   SDLoc DL(N);
6705   switch (N->getOpcode()) {
6706   default:
6707     llvm_unreachable("Don't know how to custom type legalize this operation!");
6708   case ISD::STRICT_FP_TO_SINT:
6709   case ISD::STRICT_FP_TO_UINT:
6710   case ISD::FP_TO_SINT:
6711   case ISD::FP_TO_UINT: {
6712     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6713            "Unexpected custom legalisation");
6714     bool IsStrict = N->isStrictFPOpcode();
6715     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6716                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6717     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6718     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6719         TargetLowering::TypeSoftenFloat) {
6720       if (!isTypeLegal(Op0.getValueType()))
6721         return;
6722       if (IsStrict) {
6723         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6724                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6725         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6726         SDValue Res = DAG.getNode(
6727             Opc, DL, VTs, N->getOperand(0), Op0,
6728             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6729         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6730         Results.push_back(Res.getValue(1));
6731         return;
6732       }
6733       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6734       SDValue Res =
6735           DAG.getNode(Opc, DL, MVT::i64, Op0,
6736                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6737       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6738       return;
6739     }
6740     // If the FP type needs to be softened, emit a library call using the 'si'
6741     // version. If we left it to default legalization we'd end up with 'di'. If
6742     // the FP type doesn't need to be softened just let generic type
6743     // legalization promote the result type.
6744     RTLIB::Libcall LC;
6745     if (IsSigned)
6746       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6747     else
6748       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6749     MakeLibCallOptions CallOptions;
6750     EVT OpVT = Op0.getValueType();
6751     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6752     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6753     SDValue Result;
6754     std::tie(Result, Chain) =
6755         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6756     Results.push_back(Result);
6757     if (IsStrict)
6758       Results.push_back(Chain);
6759     break;
6760   }
6761   case ISD::READCYCLECOUNTER: {
6762     assert(!Subtarget.is64Bit() &&
6763            "READCYCLECOUNTER only has custom type legalization on riscv32");
6764 
6765     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6766     SDValue RCW =
6767         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6768 
6769     Results.push_back(
6770         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6771     Results.push_back(RCW.getValue(2));
6772     break;
6773   }
6774   case ISD::MUL: {
6775     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6776     unsigned XLen = Subtarget.getXLen();
6777     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6778     if (Size > XLen) {
6779       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6780       SDValue LHS = N->getOperand(0);
6781       SDValue RHS = N->getOperand(1);
6782       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6783 
6784       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6785       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6786       // We need exactly one side to be unsigned.
6787       if (LHSIsU == RHSIsU)
6788         return;
6789 
6790       auto MakeMULPair = [&](SDValue S, SDValue U) {
6791         MVT XLenVT = Subtarget.getXLenVT();
6792         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6793         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6794         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6795         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6796         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6797       };
6798 
6799       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6800       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6801 
6802       // The other operand should be signed, but still prefer MULH when
6803       // possible.
6804       if (RHSIsU && LHSIsS && !RHSIsS)
6805         Results.push_back(MakeMULPair(LHS, RHS));
6806       else if (LHSIsU && RHSIsS && !LHSIsS)
6807         Results.push_back(MakeMULPair(RHS, LHS));
6808 
6809       return;
6810     }
6811     LLVM_FALLTHROUGH;
6812   }
6813   case ISD::ADD:
6814   case ISD::SUB:
6815     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6816            "Unexpected custom legalisation");
6817     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6818     break;
6819   case ISD::SHL:
6820   case ISD::SRA:
6821   case ISD::SRL:
6822     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6823            "Unexpected custom legalisation");
6824     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6825       // If we can use a BSET instruction, allow default promotion to apply.
6826       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6827           isOneConstant(N->getOperand(0)))
6828         break;
6829       Results.push_back(customLegalizeToWOp(N, DAG));
6830       break;
6831     }
6832 
6833     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6834     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6835     // shift amount.
6836     if (N->getOpcode() == ISD::SHL) {
6837       SDLoc DL(N);
6838       SDValue NewOp0 =
6839           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6840       SDValue NewOp1 =
6841           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6842       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6843       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6844                                    DAG.getValueType(MVT::i32));
6845       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6846     }
6847 
6848     break;
6849   case ISD::ROTL:
6850   case ISD::ROTR:
6851     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6852            "Unexpected custom legalisation");
6853     Results.push_back(customLegalizeToWOp(N, DAG));
6854     break;
6855   case ISD::CTTZ:
6856   case ISD::CTTZ_ZERO_UNDEF:
6857   case ISD::CTLZ:
6858   case ISD::CTLZ_ZERO_UNDEF: {
6859     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6860            "Unexpected custom legalisation");
6861 
6862     SDValue NewOp0 =
6863         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6864     bool IsCTZ =
6865         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6866     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6867     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6868     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6869     return;
6870   }
6871   case ISD::SDIV:
6872   case ISD::UDIV:
6873   case ISD::UREM: {
6874     MVT VT = N->getSimpleValueType(0);
6875     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6876            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6877            "Unexpected custom legalisation");
6878     // Don't promote division/remainder by constant since we should expand those
6879     // to multiply by magic constant.
6880     // FIXME: What if the expansion is disabled for minsize.
6881     if (N->getOperand(1).getOpcode() == ISD::Constant)
6882       return;
6883 
6884     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6885     // the upper 32 bits. For other types we need to sign or zero extend
6886     // based on the opcode.
6887     unsigned ExtOpc = ISD::ANY_EXTEND;
6888     if (VT != MVT::i32)
6889       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6890                                            : ISD::ZERO_EXTEND;
6891 
6892     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6893     break;
6894   }
6895   case ISD::UADDO:
6896   case ISD::USUBO: {
6897     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6898            "Unexpected custom legalisation");
6899     bool IsAdd = N->getOpcode() == ISD::UADDO;
6900     // Create an ADDW or SUBW.
6901     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6902     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6903     SDValue Res =
6904         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6905     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6906                       DAG.getValueType(MVT::i32));
6907 
6908     SDValue Overflow;
6909     if (IsAdd && isOneConstant(RHS)) {
6910       // Special case uaddo X, 1 overflowed if the addition result is 0.
6911       // FIXME: We can do this for any constant RHS by using (X + C) < C.
6912       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6913                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6914     } else {
6915       // Sign extend the LHS and perform an unsigned compare with the ADDW
6916       // result. Since the inputs are sign extended from i32, this is equivalent
6917       // to comparing the lower 32 bits.
6918       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6919       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6920                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6921     }
6922 
6923     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6924     Results.push_back(Overflow);
6925     return;
6926   }
6927   case ISD::UADDSAT:
6928   case ISD::USUBSAT: {
6929     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6930            "Unexpected custom legalisation");
6931     if (Subtarget.hasStdExtZbb()) {
6932       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6933       // sign extend allows overflow of the lower 32 bits to be detected on
6934       // the promoted size.
6935       SDValue LHS =
6936           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6937       SDValue RHS =
6938           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6939       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6940       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6941       return;
6942     }
6943 
6944     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6945     // promotion for UADDO/USUBO.
6946     Results.push_back(expandAddSubSat(N, DAG));
6947     return;
6948   }
6949   case ISD::ABS: {
6950     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6951            "Unexpected custom legalisation");
6952           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6953 
6954     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6955 
6956     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6957 
6958     // Freeze the source so we can increase it's use count.
6959     Src = DAG.getFreeze(Src);
6960 
6961     // Copy sign bit to all bits using the sraiw pattern.
6962     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6963                                    DAG.getValueType(MVT::i32));
6964     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6965                            DAG.getConstant(31, DL, MVT::i64));
6966 
6967     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6968     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6969 
6970     // NOTE: The result is only required to be anyextended, but sext is
6971     // consistent with type legalization of sub.
6972     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6973                          DAG.getValueType(MVT::i32));
6974     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6975     return;
6976   }
6977   case ISD::BITCAST: {
6978     EVT VT = N->getValueType(0);
6979     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6980     SDValue Op0 = N->getOperand(0);
6981     EVT Op0VT = Op0.getValueType();
6982     MVT XLenVT = Subtarget.getXLenVT();
6983     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6984       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6985       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6986     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6987                Subtarget.hasStdExtF()) {
6988       SDValue FPConv =
6989           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6990       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6991     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6992                isTypeLegal(Op0VT)) {
6993       // Custom-legalize bitcasts from fixed-length vector types to illegal
6994       // scalar types in order to improve codegen. Bitcast the vector to a
6995       // one-element vector type whose element type is the same as the result
6996       // type, and extract the first element.
6997       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6998       if (isTypeLegal(BVT)) {
6999         SDValue BVec = DAG.getBitcast(BVT, Op0);
7000         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7001                                       DAG.getConstant(0, DL, XLenVT)));
7002       }
7003     }
7004     break;
7005   }
7006   case RISCVISD::GREV:
7007   case RISCVISD::GORC:
7008   case RISCVISD::SHFL: {
7009     MVT VT = N->getSimpleValueType(0);
7010     MVT XLenVT = Subtarget.getXLenVT();
7011     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7012            "Unexpected custom legalisation");
7013     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7014     assert((Subtarget.hasStdExtZbp() ||
7015             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7016              N->getConstantOperandVal(1) == 7)) &&
7017            "Unexpected extension");
7018     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7019     SDValue NewOp1 =
7020         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7021     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7022     // ReplaceNodeResults requires we maintain the same type for the return
7023     // value.
7024     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7025     break;
7026   }
7027   case ISD::BSWAP:
7028   case ISD::BITREVERSE: {
7029     MVT VT = N->getSimpleValueType(0);
7030     MVT XLenVT = Subtarget.getXLenVT();
7031     assert((VT == MVT::i8 || VT == MVT::i16 ||
7032             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7033            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7034     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7035     unsigned Imm = VT.getSizeInBits() - 1;
7036     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7037     if (N->getOpcode() == ISD::BSWAP)
7038       Imm &= ~0x7U;
7039     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7040                                 DAG.getConstant(Imm, DL, XLenVT));
7041     // ReplaceNodeResults requires we maintain the same type for the return
7042     // value.
7043     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7044     break;
7045   }
7046   case ISD::FSHL:
7047   case ISD::FSHR: {
7048     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7049            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7050     SDValue NewOp0 =
7051         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7052     SDValue NewOp1 =
7053         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7054     SDValue NewShAmt =
7055         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7056     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7057     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7058     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7059                            DAG.getConstant(0x1f, DL, MVT::i64));
7060     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7061     // instruction use different orders. fshl will return its first operand for
7062     // shift of zero, fshr will return its second operand. fsl and fsr both
7063     // return rs1 so the ISD nodes need to have different operand orders.
7064     // Shift amount is in rs2.
7065     unsigned Opc = RISCVISD::FSLW;
7066     if (N->getOpcode() == ISD::FSHR) {
7067       std::swap(NewOp0, NewOp1);
7068       Opc = RISCVISD::FSRW;
7069     }
7070     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7071     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7072     break;
7073   }
7074   case ISD::EXTRACT_VECTOR_ELT: {
7075     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7076     // type is illegal (currently only vXi64 RV32).
7077     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7078     // transferred to the destination register. We issue two of these from the
7079     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7080     // first element.
7081     SDValue Vec = N->getOperand(0);
7082     SDValue Idx = N->getOperand(1);
7083 
7084     // The vector type hasn't been legalized yet so we can't issue target
7085     // specific nodes if it needs legalization.
7086     // FIXME: We would manually legalize if it's important.
7087     if (!isTypeLegal(Vec.getValueType()))
7088       return;
7089 
7090     MVT VecVT = Vec.getSimpleValueType();
7091 
7092     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7093            VecVT.getVectorElementType() == MVT::i64 &&
7094            "Unexpected EXTRACT_VECTOR_ELT legalization");
7095 
7096     // If this is a fixed vector, we need to convert it to a scalable vector.
7097     MVT ContainerVT = VecVT;
7098     if (VecVT.isFixedLengthVector()) {
7099       ContainerVT = getContainerForFixedLengthVector(VecVT);
7100       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7101     }
7102 
7103     MVT XLenVT = Subtarget.getXLenVT();
7104 
7105     // Use a VL of 1 to avoid processing more elements than we need.
7106     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7107     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7108     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7109 
7110     // Unless the index is known to be 0, we must slide the vector down to get
7111     // the desired element into index 0.
7112     if (!isNullConstant(Idx)) {
7113       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7114                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7115     }
7116 
7117     // Extract the lower XLEN bits of the correct vector element.
7118     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7119 
7120     // To extract the upper XLEN bits of the vector element, shift the first
7121     // element right by 32 bits and re-extract the lower XLEN bits.
7122     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7123                                      DAG.getUNDEF(ContainerVT),
7124                                      DAG.getConstant(32, DL, XLenVT), VL);
7125     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7126                                  ThirtyTwoV, Mask, VL);
7127 
7128     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7129 
7130     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7131     break;
7132   }
7133   case ISD::INTRINSIC_WO_CHAIN: {
7134     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7135     switch (IntNo) {
7136     default:
7137       llvm_unreachable(
7138           "Don't know how to custom type legalize this intrinsic!");
7139     case Intrinsic::riscv_grev:
7140     case Intrinsic::riscv_gorc: {
7141       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7142              "Unexpected custom legalisation");
7143       SDValue NewOp1 =
7144           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7145       SDValue NewOp2 =
7146           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7147       unsigned Opc =
7148           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7149       // If the control is a constant, promote the node by clearing any extra
7150       // bits bits in the control. isel will form greviw/gorciw if the result is
7151       // sign extended.
7152       if (isa<ConstantSDNode>(NewOp2)) {
7153         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7154                              DAG.getConstant(0x1f, DL, MVT::i64));
7155         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7156       }
7157       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7158       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7159       break;
7160     }
7161     case Intrinsic::riscv_bcompress:
7162     case Intrinsic::riscv_bdecompress:
7163     case Intrinsic::riscv_bfp:
7164     case Intrinsic::riscv_fsl:
7165     case Intrinsic::riscv_fsr: {
7166       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7167              "Unexpected custom legalisation");
7168       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7169       break;
7170     }
7171     case Intrinsic::riscv_orc_b: {
7172       // Lower to the GORCI encoding for orc.b with the operand extended.
7173       SDValue NewOp =
7174           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7175       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7176                                 DAG.getConstant(7, DL, MVT::i64));
7177       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7178       return;
7179     }
7180     case Intrinsic::riscv_shfl:
7181     case Intrinsic::riscv_unshfl: {
7182       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7183              "Unexpected custom legalisation");
7184       SDValue NewOp1 =
7185           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7186       SDValue NewOp2 =
7187           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7188       unsigned Opc =
7189           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7190       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7191       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7192       // will be shuffled the same way as the lower 32 bit half, but the two
7193       // halves won't cross.
7194       if (isa<ConstantSDNode>(NewOp2)) {
7195         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7196                              DAG.getConstant(0xf, DL, MVT::i64));
7197         Opc =
7198             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7199       }
7200       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7201       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7202       break;
7203     }
7204     case Intrinsic::riscv_vmv_x_s: {
7205       EVT VT = N->getValueType(0);
7206       MVT XLenVT = Subtarget.getXLenVT();
7207       if (VT.bitsLT(XLenVT)) {
7208         // Simple case just extract using vmv.x.s and truncate.
7209         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7210                                       Subtarget.getXLenVT(), N->getOperand(1));
7211         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7212         return;
7213       }
7214 
7215       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7216              "Unexpected custom legalization");
7217 
7218       // We need to do the move in two steps.
7219       SDValue Vec = N->getOperand(1);
7220       MVT VecVT = Vec.getSimpleValueType();
7221 
7222       // First extract the lower XLEN bits of the element.
7223       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7224 
7225       // To extract the upper XLEN bits of the vector element, shift the first
7226       // element right by 32 bits and re-extract the lower XLEN bits.
7227       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7228       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7229       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7230       SDValue ThirtyTwoV =
7231           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7232                       DAG.getConstant(32, DL, XLenVT), VL);
7233       SDValue LShr32 =
7234           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7235       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7236 
7237       Results.push_back(
7238           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7239       break;
7240     }
7241     }
7242     break;
7243   }
7244   case ISD::VECREDUCE_ADD:
7245   case ISD::VECREDUCE_AND:
7246   case ISD::VECREDUCE_OR:
7247   case ISD::VECREDUCE_XOR:
7248   case ISD::VECREDUCE_SMAX:
7249   case ISD::VECREDUCE_UMAX:
7250   case ISD::VECREDUCE_SMIN:
7251   case ISD::VECREDUCE_UMIN:
7252     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7253       Results.push_back(V);
7254     break;
7255   case ISD::VP_REDUCE_ADD:
7256   case ISD::VP_REDUCE_AND:
7257   case ISD::VP_REDUCE_OR:
7258   case ISD::VP_REDUCE_XOR:
7259   case ISD::VP_REDUCE_SMAX:
7260   case ISD::VP_REDUCE_UMAX:
7261   case ISD::VP_REDUCE_SMIN:
7262   case ISD::VP_REDUCE_UMIN:
7263     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7264       Results.push_back(V);
7265     break;
7266   case ISD::FLT_ROUNDS_: {
7267     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7268     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7269     Results.push_back(Res.getValue(0));
7270     Results.push_back(Res.getValue(1));
7271     break;
7272   }
7273   }
7274 }
7275 
7276 // A structure to hold one of the bit-manipulation patterns below. Together, a
7277 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7278 //   (or (and (shl x, 1), 0xAAAAAAAA),
7279 //       (and (srl x, 1), 0x55555555))
7280 struct RISCVBitmanipPat {
7281   SDValue Op;
7282   unsigned ShAmt;
7283   bool IsSHL;
7284 
7285   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7286     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7287   }
7288 };
7289 
7290 // Matches patterns of the form
7291 //   (and (shl x, C2), (C1 << C2))
7292 //   (and (srl x, C2), C1)
7293 //   (shl (and x, C1), C2)
7294 //   (srl (and x, (C1 << C2)), C2)
7295 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7296 // The expected masks for each shift amount are specified in BitmanipMasks where
7297 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7298 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7299 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7300 // XLen is 64.
7301 static Optional<RISCVBitmanipPat>
7302 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7303   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7304          "Unexpected number of masks");
7305   Optional<uint64_t> Mask;
7306   // Optionally consume a mask around the shift operation.
7307   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7308     Mask = Op.getConstantOperandVal(1);
7309     Op = Op.getOperand(0);
7310   }
7311   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7312     return None;
7313   bool IsSHL = Op.getOpcode() == ISD::SHL;
7314 
7315   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7316     return None;
7317   uint64_t ShAmt = Op.getConstantOperandVal(1);
7318 
7319   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7320   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7321     return None;
7322   // If we don't have enough masks for 64 bit, then we must be trying to
7323   // match SHFL so we're only allowed to shift 1/4 of the width.
7324   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7325     return None;
7326 
7327   SDValue Src = Op.getOperand(0);
7328 
7329   // The expected mask is shifted left when the AND is found around SHL
7330   // patterns.
7331   //   ((x >> 1) & 0x55555555)
7332   //   ((x << 1) & 0xAAAAAAAA)
7333   bool SHLExpMask = IsSHL;
7334 
7335   if (!Mask) {
7336     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7337     // the mask is all ones: consume that now.
7338     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7339       Mask = Src.getConstantOperandVal(1);
7340       Src = Src.getOperand(0);
7341       // The expected mask is now in fact shifted left for SRL, so reverse the
7342       // decision.
7343       //   ((x & 0xAAAAAAAA) >> 1)
7344       //   ((x & 0x55555555) << 1)
7345       SHLExpMask = !SHLExpMask;
7346     } else {
7347       // Use a default shifted mask of all-ones if there's no AND, truncated
7348       // down to the expected width. This simplifies the logic later on.
7349       Mask = maskTrailingOnes<uint64_t>(Width);
7350       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7351     }
7352   }
7353 
7354   unsigned MaskIdx = Log2_32(ShAmt);
7355   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7356 
7357   if (SHLExpMask)
7358     ExpMask <<= ShAmt;
7359 
7360   if (Mask != ExpMask)
7361     return None;
7362 
7363   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7364 }
7365 
7366 // Matches any of the following bit-manipulation patterns:
7367 //   (and (shl x, 1), (0x55555555 << 1))
7368 //   (and (srl x, 1), 0x55555555)
7369 //   (shl (and x, 0x55555555), 1)
7370 //   (srl (and x, (0x55555555 << 1)), 1)
7371 // where the shift amount and mask may vary thus:
7372 //   [1]  = 0x55555555 / 0xAAAAAAAA
7373 //   [2]  = 0x33333333 / 0xCCCCCCCC
7374 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7375 //   [8]  = 0x00FF00FF / 0xFF00FF00
7376 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7377 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7378 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7379   // These are the unshifted masks which we use to match bit-manipulation
7380   // patterns. They may be shifted left in certain circumstances.
7381   static const uint64_t BitmanipMasks[] = {
7382       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7383       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7384 
7385   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7386 }
7387 
7388 // Match the following pattern as a GREVI(W) operation
7389 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7390 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7391                                const RISCVSubtarget &Subtarget) {
7392   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7393   EVT VT = Op.getValueType();
7394 
7395   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7396     auto LHS = matchGREVIPat(Op.getOperand(0));
7397     auto RHS = matchGREVIPat(Op.getOperand(1));
7398     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7399       SDLoc DL(Op);
7400       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7401                          DAG.getConstant(LHS->ShAmt, DL, VT));
7402     }
7403   }
7404   return SDValue();
7405 }
7406 
7407 // Matches any the following pattern as a GORCI(W) operation
7408 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7409 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7410 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7411 // Note that with the variant of 3.,
7412 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7413 // the inner pattern will first be matched as GREVI and then the outer
7414 // pattern will be matched to GORC via the first rule above.
7415 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7416 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7417                                const RISCVSubtarget &Subtarget) {
7418   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7419   EVT VT = Op.getValueType();
7420 
7421   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7422     SDLoc DL(Op);
7423     SDValue Op0 = Op.getOperand(0);
7424     SDValue Op1 = Op.getOperand(1);
7425 
7426     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7427       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7428           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7429           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7430         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7431       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7432       if ((Reverse.getOpcode() == ISD::ROTL ||
7433            Reverse.getOpcode() == ISD::ROTR) &&
7434           Reverse.getOperand(0) == X &&
7435           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7436         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7437         if (RotAmt == (VT.getSizeInBits() / 2))
7438           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7439                              DAG.getConstant(RotAmt, DL, VT));
7440       }
7441       return SDValue();
7442     };
7443 
7444     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7445     if (SDValue V = MatchOROfReverse(Op0, Op1))
7446       return V;
7447     if (SDValue V = MatchOROfReverse(Op1, Op0))
7448       return V;
7449 
7450     // OR is commutable so canonicalize its OR operand to the left
7451     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7452       std::swap(Op0, Op1);
7453     if (Op0.getOpcode() != ISD::OR)
7454       return SDValue();
7455     SDValue OrOp0 = Op0.getOperand(0);
7456     SDValue OrOp1 = Op0.getOperand(1);
7457     auto LHS = matchGREVIPat(OrOp0);
7458     // OR is commutable so swap the operands and try again: x might have been
7459     // on the left
7460     if (!LHS) {
7461       std::swap(OrOp0, OrOp1);
7462       LHS = matchGREVIPat(OrOp0);
7463     }
7464     auto RHS = matchGREVIPat(Op1);
7465     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7466       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7467                          DAG.getConstant(LHS->ShAmt, DL, VT));
7468     }
7469   }
7470   return SDValue();
7471 }
7472 
7473 // Matches any of the following bit-manipulation patterns:
7474 //   (and (shl x, 1), (0x22222222 << 1))
7475 //   (and (srl x, 1), 0x22222222)
7476 //   (shl (and x, 0x22222222), 1)
7477 //   (srl (and x, (0x22222222 << 1)), 1)
7478 // where the shift amount and mask may vary thus:
7479 //   [1]  = 0x22222222 / 0x44444444
7480 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7481 //   [4]  = 0x00F000F0 / 0x0F000F00
7482 //   [8]  = 0x0000FF00 / 0x00FF0000
7483 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7484 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7485   // These are the unshifted masks which we use to match bit-manipulation
7486   // patterns. They may be shifted left in certain circumstances.
7487   static const uint64_t BitmanipMasks[] = {
7488       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7489       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7490 
7491   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7492 }
7493 
7494 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7495 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7496                                const RISCVSubtarget &Subtarget) {
7497   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7498   EVT VT = Op.getValueType();
7499 
7500   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7501     return SDValue();
7502 
7503   SDValue Op0 = Op.getOperand(0);
7504   SDValue Op1 = Op.getOperand(1);
7505 
7506   // Or is commutable so canonicalize the second OR to the LHS.
7507   if (Op0.getOpcode() != ISD::OR)
7508     std::swap(Op0, Op1);
7509   if (Op0.getOpcode() != ISD::OR)
7510     return SDValue();
7511 
7512   // We found an inner OR, so our operands are the operands of the inner OR
7513   // and the other operand of the outer OR.
7514   SDValue A = Op0.getOperand(0);
7515   SDValue B = Op0.getOperand(1);
7516   SDValue C = Op1;
7517 
7518   auto Match1 = matchSHFLPat(A);
7519   auto Match2 = matchSHFLPat(B);
7520 
7521   // If neither matched, we failed.
7522   if (!Match1 && !Match2)
7523     return SDValue();
7524 
7525   // We had at least one match. if one failed, try the remaining C operand.
7526   if (!Match1) {
7527     std::swap(A, C);
7528     Match1 = matchSHFLPat(A);
7529     if (!Match1)
7530       return SDValue();
7531   } else if (!Match2) {
7532     std::swap(B, C);
7533     Match2 = matchSHFLPat(B);
7534     if (!Match2)
7535       return SDValue();
7536   }
7537   assert(Match1 && Match2);
7538 
7539   // Make sure our matches pair up.
7540   if (!Match1->formsPairWith(*Match2))
7541     return SDValue();
7542 
7543   // All the remains is to make sure C is an AND with the same input, that masks
7544   // out the bits that are being shuffled.
7545   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7546       C.getOperand(0) != Match1->Op)
7547     return SDValue();
7548 
7549   uint64_t Mask = C.getConstantOperandVal(1);
7550 
7551   static const uint64_t BitmanipMasks[] = {
7552       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7553       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7554   };
7555 
7556   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7557   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7558   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7559 
7560   if (Mask != ExpMask)
7561     return SDValue();
7562 
7563   SDLoc DL(Op);
7564   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7565                      DAG.getConstant(Match1->ShAmt, DL, VT));
7566 }
7567 
7568 // Optimize (add (shl x, c0), (shl y, c1)) ->
7569 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7570 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7571                                   const RISCVSubtarget &Subtarget) {
7572   // Perform this optimization only in the zba extension.
7573   if (!Subtarget.hasStdExtZba())
7574     return SDValue();
7575 
7576   // Skip for vector types and larger types.
7577   EVT VT = N->getValueType(0);
7578   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7579     return SDValue();
7580 
7581   // The two operand nodes must be SHL and have no other use.
7582   SDValue N0 = N->getOperand(0);
7583   SDValue N1 = N->getOperand(1);
7584   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7585       !N0->hasOneUse() || !N1->hasOneUse())
7586     return SDValue();
7587 
7588   // Check c0 and c1.
7589   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7590   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7591   if (!N0C || !N1C)
7592     return SDValue();
7593   int64_t C0 = N0C->getSExtValue();
7594   int64_t C1 = N1C->getSExtValue();
7595   if (C0 <= 0 || C1 <= 0)
7596     return SDValue();
7597 
7598   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7599   int64_t Bits = std::min(C0, C1);
7600   int64_t Diff = std::abs(C0 - C1);
7601   if (Diff != 1 && Diff != 2 && Diff != 3)
7602     return SDValue();
7603 
7604   // Build nodes.
7605   SDLoc DL(N);
7606   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7607   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7608   SDValue NA0 =
7609       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7610   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7611   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7612 }
7613 
7614 // Combine
7615 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7616 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7617 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7618 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7619 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7620 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7621 // The grev patterns represents BSWAP.
7622 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7623 // off the grev.
7624 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7625                                           const RISCVSubtarget &Subtarget) {
7626   bool IsWInstruction =
7627       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7628   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7629           IsWInstruction) &&
7630          "Unexpected opcode!");
7631   SDValue Src = N->getOperand(0);
7632   EVT VT = N->getValueType(0);
7633   SDLoc DL(N);
7634 
7635   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7636     return SDValue();
7637 
7638   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7639       !isa<ConstantSDNode>(Src.getOperand(1)))
7640     return SDValue();
7641 
7642   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7643   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7644 
7645   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7646   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7647   unsigned ShAmt1 = N->getConstantOperandVal(1);
7648   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7649   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7650     return SDValue();
7651 
7652   Src = Src.getOperand(0);
7653 
7654   // Toggle bit the MSB of the shift.
7655   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7656   if (CombinedShAmt == 0)
7657     return Src;
7658 
7659   SDValue Res = DAG.getNode(
7660       RISCVISD::GREV, DL, VT, Src,
7661       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7662   if (!IsWInstruction)
7663     return Res;
7664 
7665   // Sign extend the result to match the behavior of the rotate. This will be
7666   // selected to GREVIW in isel.
7667   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7668                      DAG.getValueType(MVT::i32));
7669 }
7670 
7671 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7672 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7673 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7674 // not undo itself, but they are redundant.
7675 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7676   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7677   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7678   SDValue Src = N->getOperand(0);
7679 
7680   if (Src.getOpcode() != N->getOpcode())
7681     return SDValue();
7682 
7683   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7684       !isa<ConstantSDNode>(Src.getOperand(1)))
7685     return SDValue();
7686 
7687   unsigned ShAmt1 = N->getConstantOperandVal(1);
7688   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7689   Src = Src.getOperand(0);
7690 
7691   unsigned CombinedShAmt;
7692   if (IsGORC)
7693     CombinedShAmt = ShAmt1 | ShAmt2;
7694   else
7695     CombinedShAmt = ShAmt1 ^ ShAmt2;
7696 
7697   if (CombinedShAmt == 0)
7698     return Src;
7699 
7700   SDLoc DL(N);
7701   return DAG.getNode(
7702       N->getOpcode(), DL, N->getValueType(0), Src,
7703       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7704 }
7705 
7706 // Combine a constant select operand into its use:
7707 //
7708 // (and (select cond, -1, c), x)
7709 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7710 // (or  (select cond, 0, c), x)
7711 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7712 // (xor (select cond, 0, c), x)
7713 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7714 // (add (select cond, 0, c), x)
7715 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7716 // (sub x, (select cond, 0, c))
7717 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7718 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7719                                    SelectionDAG &DAG, bool AllOnes) {
7720   EVT VT = N->getValueType(0);
7721 
7722   // Skip vectors.
7723   if (VT.isVector())
7724     return SDValue();
7725 
7726   if ((Slct.getOpcode() != ISD::SELECT &&
7727        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7728       !Slct.hasOneUse())
7729     return SDValue();
7730 
7731   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7732     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7733   };
7734 
7735   bool SwapSelectOps;
7736   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7737   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7738   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7739   SDValue NonConstantVal;
7740   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7741     SwapSelectOps = false;
7742     NonConstantVal = FalseVal;
7743   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7744     SwapSelectOps = true;
7745     NonConstantVal = TrueVal;
7746   } else
7747     return SDValue();
7748 
7749   // Slct is now know to be the desired identity constant when CC is true.
7750   TrueVal = OtherOp;
7751   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7752   // Unless SwapSelectOps says the condition should be false.
7753   if (SwapSelectOps)
7754     std::swap(TrueVal, FalseVal);
7755 
7756   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7757     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7758                        {Slct.getOperand(0), Slct.getOperand(1),
7759                         Slct.getOperand(2), TrueVal, FalseVal});
7760 
7761   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7762                      {Slct.getOperand(0), TrueVal, FalseVal});
7763 }
7764 
7765 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7766 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7767                                               bool AllOnes) {
7768   SDValue N0 = N->getOperand(0);
7769   SDValue N1 = N->getOperand(1);
7770   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7771     return Result;
7772   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7773     return Result;
7774   return SDValue();
7775 }
7776 
7777 // Transform (add (mul x, c0), c1) ->
7778 //           (add (mul (add x, c1/c0), c0), c1%c0).
7779 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7780 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7781 // to an infinite loop in DAGCombine if transformed.
7782 // Or transform (add (mul x, c0), c1) ->
7783 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7784 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7785 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7786 // lead to an infinite loop in DAGCombine if transformed.
7787 // Or transform (add (mul x, c0), c1) ->
7788 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7789 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7790 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7791 // lead to an infinite loop in DAGCombine if transformed.
7792 // Or transform (add (mul x, c0), c1) ->
7793 //              (mul (add x, c1/c0), c0).
7794 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7795 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7796                                      const RISCVSubtarget &Subtarget) {
7797   // Skip for vector types and larger types.
7798   EVT VT = N->getValueType(0);
7799   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7800     return SDValue();
7801   // The first operand node must be a MUL and has no other use.
7802   SDValue N0 = N->getOperand(0);
7803   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7804     return SDValue();
7805   // Check if c0 and c1 match above conditions.
7806   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7807   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7808   if (!N0C || !N1C)
7809     return SDValue();
7810   // If N0C has multiple uses it's possible one of the cases in
7811   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7812   // in an infinite loop.
7813   if (!N0C->hasOneUse())
7814     return SDValue();
7815   int64_t C0 = N0C->getSExtValue();
7816   int64_t C1 = N1C->getSExtValue();
7817   int64_t CA, CB;
7818   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7819     return SDValue();
7820   // Search for proper CA (non-zero) and CB that both are simm12.
7821   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7822       !isInt<12>(C0 * (C1 / C0))) {
7823     CA = C1 / C0;
7824     CB = C1 % C0;
7825   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7826              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7827     CA = C1 / C0 + 1;
7828     CB = C1 % C0 - C0;
7829   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7830              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7831     CA = C1 / C0 - 1;
7832     CB = C1 % C0 + C0;
7833   } else
7834     return SDValue();
7835   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7836   SDLoc DL(N);
7837   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7838                              DAG.getConstant(CA, DL, VT));
7839   SDValue New1 =
7840       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7841   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7842 }
7843 
7844 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7845                                  const RISCVSubtarget &Subtarget) {
7846   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7847     return V;
7848   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7849     return V;
7850   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7851   //      (select lhs, rhs, cc, x, (add x, y))
7852   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7853 }
7854 
7855 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7856   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7857   //      (select lhs, rhs, cc, x, (sub x, y))
7858   SDValue N0 = N->getOperand(0);
7859   SDValue N1 = N->getOperand(1);
7860   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7861 }
7862 
7863 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7864   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7865   //      (select lhs, rhs, cc, x, (and x, y))
7866   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7867 }
7868 
7869 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7870                                 const RISCVSubtarget &Subtarget) {
7871   if (Subtarget.hasStdExtZbp()) {
7872     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7873       return GREV;
7874     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7875       return GORC;
7876     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7877       return SHFL;
7878   }
7879 
7880   // fold (or (select cond, 0, y), x) ->
7881   //      (select cond, x, (or x, y))
7882   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7883 }
7884 
7885 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7886   SDValue N0 = N->getOperand(0);
7887   SDValue N1 = N->getOperand(1);
7888 
7889   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
7890   // NOTE: Assumes ROL being legal means ROLW is legal.
7891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7892   if (N0.getOpcode() == RISCVISD::SLLW &&
7893       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
7894       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
7895     SDLoc DL(N);
7896     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
7897                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
7898   }
7899 
7900   // fold (xor (select cond, 0, y), x) ->
7901   //      (select cond, x, (xor x, y))
7902   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7903 }
7904 
7905 static SDValue
7906 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7907                                 const RISCVSubtarget &Subtarget) {
7908   SDValue Src = N->getOperand(0);
7909   EVT VT = N->getValueType(0);
7910 
7911   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7912   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7913       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7914     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7915                        Src.getOperand(0));
7916 
7917   // Fold (i64 (sext_inreg (abs X), i32)) ->
7918   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7919   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7920   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7921   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7922   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7923   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7924   // may get combined into an earlier operation so we need to use
7925   // ComputeNumSignBits.
7926   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7927   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7928   // we can't assume that X has 33 sign bits. We must check.
7929   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7930       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7931       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7932       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7933     SDLoc DL(N);
7934     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7935     SDValue Neg =
7936         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7937     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7938                       DAG.getValueType(MVT::i32));
7939     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7940   }
7941 
7942   return SDValue();
7943 }
7944 
7945 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7946 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7947 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7948                                              bool Commute = false) {
7949   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7950           N->getOpcode() == RISCVISD::SUB_VL) &&
7951          "Unexpected opcode");
7952   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7953   SDValue Op0 = N->getOperand(0);
7954   SDValue Op1 = N->getOperand(1);
7955   if (Commute)
7956     std::swap(Op0, Op1);
7957 
7958   MVT VT = N->getSimpleValueType(0);
7959 
7960   // Determine the narrow size for a widening add/sub.
7961   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7962   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7963                                   VT.getVectorElementCount());
7964 
7965   SDValue Mask = N->getOperand(2);
7966   SDValue VL = N->getOperand(3);
7967 
7968   SDLoc DL(N);
7969 
7970   // If the RHS is a sext or zext, we can form a widening op.
7971   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7972        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7973       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7974     unsigned ExtOpc = Op1.getOpcode();
7975     Op1 = Op1.getOperand(0);
7976     // Re-introduce narrower extends if needed.
7977     if (Op1.getValueType() != NarrowVT)
7978       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7979 
7980     unsigned WOpc;
7981     if (ExtOpc == RISCVISD::VSEXT_VL)
7982       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7983     else
7984       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7985 
7986     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7987   }
7988 
7989   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7990   // sext/zext?
7991 
7992   return SDValue();
7993 }
7994 
7995 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7996 // vwsub(u).vv/vx.
7997 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7998   SDValue Op0 = N->getOperand(0);
7999   SDValue Op1 = N->getOperand(1);
8000   SDValue Mask = N->getOperand(2);
8001   SDValue VL = N->getOperand(3);
8002 
8003   MVT VT = N->getSimpleValueType(0);
8004   MVT NarrowVT = Op1.getSimpleValueType();
8005   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8006 
8007   unsigned VOpc;
8008   switch (N->getOpcode()) {
8009   default: llvm_unreachable("Unexpected opcode");
8010   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8011   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8012   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8013   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8014   }
8015 
8016   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8017                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8018 
8019   SDLoc DL(N);
8020 
8021   // If the LHS is a sext or zext, we can narrow this op to the same size as
8022   // the RHS.
8023   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8024        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8025       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8026     unsigned ExtOpc = Op0.getOpcode();
8027     Op0 = Op0.getOperand(0);
8028     // Re-introduce narrower extends if needed.
8029     if (Op0.getValueType() != NarrowVT)
8030       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8031     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8032   }
8033 
8034   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8035                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8036 
8037   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8038   // to commute and use a vwadd(u).vx instead.
8039   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8040       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8041     Op0 = Op0.getOperand(1);
8042 
8043     // See if have enough sign bits or zero bits in the scalar to use a
8044     // widening add/sub by splatting to smaller element size.
8045     unsigned EltBits = VT.getScalarSizeInBits();
8046     unsigned ScalarBits = Op0.getValueSizeInBits();
8047     // Make sure we're getting all element bits from the scalar register.
8048     // FIXME: Support implicit sign extension of vmv.v.x?
8049     if (ScalarBits < EltBits)
8050       return SDValue();
8051 
8052     if (IsSigned) {
8053       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8054         return SDValue();
8055     } else {
8056       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8057       if (!DAG.MaskedValueIsZero(Op0, Mask))
8058         return SDValue();
8059     }
8060 
8061     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8062                       DAG.getUNDEF(NarrowVT), Op0, VL);
8063     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8064   }
8065 
8066   return SDValue();
8067 }
8068 
8069 // Try to form VWMUL, VWMULU or VWMULSU.
8070 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8071 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8072                                        bool Commute) {
8073   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8074   SDValue Op0 = N->getOperand(0);
8075   SDValue Op1 = N->getOperand(1);
8076   if (Commute)
8077     std::swap(Op0, Op1);
8078 
8079   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8080   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8081   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8082   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8083     return SDValue();
8084 
8085   SDValue Mask = N->getOperand(2);
8086   SDValue VL = N->getOperand(3);
8087 
8088   // Make sure the mask and VL match.
8089   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8090     return SDValue();
8091 
8092   MVT VT = N->getSimpleValueType(0);
8093 
8094   // Determine the narrow size for a widening multiply.
8095   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8096   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8097                                   VT.getVectorElementCount());
8098 
8099   SDLoc DL(N);
8100 
8101   // See if the other operand is the same opcode.
8102   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8103     if (!Op1.hasOneUse())
8104       return SDValue();
8105 
8106     // Make sure the mask and VL match.
8107     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8108       return SDValue();
8109 
8110     Op1 = Op1.getOperand(0);
8111   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8112     // The operand is a splat of a scalar.
8113 
8114     // The pasthru must be undef for tail agnostic
8115     if (!Op1.getOperand(0).isUndef())
8116       return SDValue();
8117     // The VL must be the same.
8118     if (Op1.getOperand(2) != VL)
8119       return SDValue();
8120 
8121     // Get the scalar value.
8122     Op1 = Op1.getOperand(1);
8123 
8124     // See if have enough sign bits or zero bits in the scalar to use a
8125     // widening multiply by splatting to smaller element size.
8126     unsigned EltBits = VT.getScalarSizeInBits();
8127     unsigned ScalarBits = Op1.getValueSizeInBits();
8128     // Make sure we're getting all element bits from the scalar register.
8129     // FIXME: Support implicit sign extension of vmv.v.x?
8130     if (ScalarBits < EltBits)
8131       return SDValue();
8132 
8133     // If the LHS is a sign extend, try to use vwmul.
8134     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8135       // Can use vwmul.
8136     } else {
8137       // Otherwise try to use vwmulu or vwmulsu.
8138       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8139       if (DAG.MaskedValueIsZero(Op1, Mask))
8140         IsVWMULSU = IsSignExt;
8141       else
8142         return SDValue();
8143     }
8144 
8145     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8146                       DAG.getUNDEF(NarrowVT), Op1, VL);
8147   } else
8148     return SDValue();
8149 
8150   Op0 = Op0.getOperand(0);
8151 
8152   // Re-introduce narrower extends if needed.
8153   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8154   if (Op0.getValueType() != NarrowVT)
8155     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8156   // vwmulsu requires second operand to be zero extended.
8157   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8158   if (Op1.getValueType() != NarrowVT)
8159     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8160 
8161   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8162   if (!IsVWMULSU)
8163     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8164   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8165 }
8166 
8167 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8168   switch (Op.getOpcode()) {
8169   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8170   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8171   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8172   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8173   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8174   }
8175 
8176   return RISCVFPRndMode::Invalid;
8177 }
8178 
8179 // Fold
8180 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8181 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8182 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8183 //   (fp_to_int (fceil X))      -> fcvt X, rup
8184 //   (fp_to_int (fround X))     -> fcvt X, rmm
8185 static SDValue performFP_TO_INTCombine(SDNode *N,
8186                                        TargetLowering::DAGCombinerInfo &DCI,
8187                                        const RISCVSubtarget &Subtarget) {
8188   SelectionDAG &DAG = DCI.DAG;
8189   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8190   MVT XLenVT = Subtarget.getXLenVT();
8191 
8192   // Only handle XLen or i32 types. Other types narrower than XLen will
8193   // eventually be legalized to XLenVT.
8194   EVT VT = N->getValueType(0);
8195   if (VT != MVT::i32 && VT != XLenVT)
8196     return SDValue();
8197 
8198   SDValue Src = N->getOperand(0);
8199 
8200   // Ensure the FP type is also legal.
8201   if (!TLI.isTypeLegal(Src.getValueType()))
8202     return SDValue();
8203 
8204   // Don't do this for f16 with Zfhmin and not Zfh.
8205   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8206     return SDValue();
8207 
8208   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8209   if (FRM == RISCVFPRndMode::Invalid)
8210     return SDValue();
8211 
8212   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8213 
8214   unsigned Opc;
8215   if (VT == XLenVT)
8216     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8217   else
8218     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8219 
8220   SDLoc DL(N);
8221   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8222                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8223   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8224 }
8225 
8226 // Fold
8227 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8228 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8229 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8230 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8231 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8232 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8233                                        TargetLowering::DAGCombinerInfo &DCI,
8234                                        const RISCVSubtarget &Subtarget) {
8235   SelectionDAG &DAG = DCI.DAG;
8236   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8237   MVT XLenVT = Subtarget.getXLenVT();
8238 
8239   // Only handle XLen types. Other types narrower than XLen will eventually be
8240   // legalized to XLenVT.
8241   EVT DstVT = N->getValueType(0);
8242   if (DstVT != XLenVT)
8243     return SDValue();
8244 
8245   SDValue Src = N->getOperand(0);
8246 
8247   // Ensure the FP type is also legal.
8248   if (!TLI.isTypeLegal(Src.getValueType()))
8249     return SDValue();
8250 
8251   // Don't do this for f16 with Zfhmin and not Zfh.
8252   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8253     return SDValue();
8254 
8255   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8256 
8257   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8258   if (FRM == RISCVFPRndMode::Invalid)
8259     return SDValue();
8260 
8261   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8262 
8263   unsigned Opc;
8264   if (SatVT == DstVT)
8265     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8266   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8267     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8268   else
8269     return SDValue();
8270   // FIXME: Support other SatVTs by clamping before or after the conversion.
8271 
8272   Src = Src.getOperand(0);
8273 
8274   SDLoc DL(N);
8275   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8276                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8277 
8278   // RISCV FP-to-int conversions saturate to the destination register size, but
8279   // don't produce 0 for nan.
8280   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8281   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8282 }
8283 
8284 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8285 // smaller than XLenVT.
8286 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8287                                         const RISCVSubtarget &Subtarget) {
8288   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8289 
8290   SDValue Src = N->getOperand(0);
8291   if (Src.getOpcode() != ISD::BSWAP)
8292     return SDValue();
8293 
8294   EVT VT = N->getValueType(0);
8295   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8296       !isPowerOf2_32(VT.getSizeInBits()))
8297     return SDValue();
8298 
8299   SDLoc DL(N);
8300   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8301                      DAG.getConstant(7, DL, VT));
8302 }
8303 
8304 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8305                                                DAGCombinerInfo &DCI) const {
8306   SelectionDAG &DAG = DCI.DAG;
8307 
8308   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8309   // bits are demanded. N will be added to the Worklist if it was not deleted.
8310   // Caller should return SDValue(N, 0) if this returns true.
8311   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8312     SDValue Op = N->getOperand(OpNo);
8313     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8314     if (!SimplifyDemandedBits(Op, Mask, DCI))
8315       return false;
8316 
8317     if (N->getOpcode() != ISD::DELETED_NODE)
8318       DCI.AddToWorklist(N);
8319     return true;
8320   };
8321 
8322   switch (N->getOpcode()) {
8323   default:
8324     break;
8325   case RISCVISD::SplitF64: {
8326     SDValue Op0 = N->getOperand(0);
8327     // If the input to SplitF64 is just BuildPairF64 then the operation is
8328     // redundant. Instead, use BuildPairF64's operands directly.
8329     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8330       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8331 
8332     if (Op0->isUndef()) {
8333       SDValue Lo = DAG.getUNDEF(MVT::i32);
8334       SDValue Hi = DAG.getUNDEF(MVT::i32);
8335       return DCI.CombineTo(N, Lo, Hi);
8336     }
8337 
8338     SDLoc DL(N);
8339 
8340     // It's cheaper to materialise two 32-bit integers than to load a double
8341     // from the constant pool and transfer it to integer registers through the
8342     // stack.
8343     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8344       APInt V = C->getValueAPF().bitcastToAPInt();
8345       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8346       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8347       return DCI.CombineTo(N, Lo, Hi);
8348     }
8349 
8350     // This is a target-specific version of a DAGCombine performed in
8351     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8352     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8353     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8354     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8355         !Op0.getNode()->hasOneUse())
8356       break;
8357     SDValue NewSplitF64 =
8358         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8359                     Op0.getOperand(0));
8360     SDValue Lo = NewSplitF64.getValue(0);
8361     SDValue Hi = NewSplitF64.getValue(1);
8362     APInt SignBit = APInt::getSignMask(32);
8363     if (Op0.getOpcode() == ISD::FNEG) {
8364       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8365                                   DAG.getConstant(SignBit, DL, MVT::i32));
8366       return DCI.CombineTo(N, Lo, NewHi);
8367     }
8368     assert(Op0.getOpcode() == ISD::FABS);
8369     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8370                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8371     return DCI.CombineTo(N, Lo, NewHi);
8372   }
8373   case RISCVISD::SLLW:
8374   case RISCVISD::SRAW:
8375   case RISCVISD::SRLW: {
8376     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8377     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8378         SimplifyDemandedLowBitsHelper(1, 5))
8379       return SDValue(N, 0);
8380 
8381     break;
8382   }
8383   case ISD::ROTR:
8384   case ISD::ROTL:
8385   case RISCVISD::RORW:
8386   case RISCVISD::ROLW: {
8387     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8388       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8389       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8390           SimplifyDemandedLowBitsHelper(1, 5))
8391         return SDValue(N, 0);
8392     }
8393 
8394     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8395   }
8396   case RISCVISD::CLZW:
8397   case RISCVISD::CTZW: {
8398     // Only the lower 32 bits of the first operand are read
8399     if (SimplifyDemandedLowBitsHelper(0, 32))
8400       return SDValue(N, 0);
8401     break;
8402   }
8403   case RISCVISD::GREV:
8404   case RISCVISD::GORC: {
8405     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8406     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8407     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8408     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8409       return SDValue(N, 0);
8410 
8411     return combineGREVI_GORCI(N, DAG);
8412   }
8413   case RISCVISD::GREVW:
8414   case RISCVISD::GORCW: {
8415     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8416     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8417         SimplifyDemandedLowBitsHelper(1, 5))
8418       return SDValue(N, 0);
8419 
8420     break;
8421   }
8422   case RISCVISD::SHFL:
8423   case RISCVISD::UNSHFL: {
8424     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8425     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8426     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8427     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8428       return SDValue(N, 0);
8429 
8430     break;
8431   }
8432   case RISCVISD::SHFLW:
8433   case RISCVISD::UNSHFLW: {
8434     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8435     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8436         SimplifyDemandedLowBitsHelper(1, 4))
8437       return SDValue(N, 0);
8438 
8439     break;
8440   }
8441   case RISCVISD::BCOMPRESSW:
8442   case RISCVISD::BDECOMPRESSW: {
8443     // Only the lower 32 bits of LHS and RHS are read.
8444     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8445         SimplifyDemandedLowBitsHelper(1, 32))
8446       return SDValue(N, 0);
8447 
8448     break;
8449   }
8450   case RISCVISD::FSR:
8451   case RISCVISD::FSL:
8452   case RISCVISD::FSRW:
8453   case RISCVISD::FSLW: {
8454     bool IsWInstruction =
8455         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8456     unsigned BitWidth =
8457         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8458     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8459     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8460     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8461       return SDValue(N, 0);
8462 
8463     break;
8464   }
8465   case RISCVISD::FMV_X_ANYEXTH:
8466   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8467     SDLoc DL(N);
8468     SDValue Op0 = N->getOperand(0);
8469     MVT VT = N->getSimpleValueType(0);
8470     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8471     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8472     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8473     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8474          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8475         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8476          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8477       assert(Op0.getOperand(0).getValueType() == VT &&
8478              "Unexpected value type!");
8479       return Op0.getOperand(0);
8480     }
8481 
8482     // This is a target-specific version of a DAGCombine performed in
8483     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8484     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8485     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8486     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8487         !Op0.getNode()->hasOneUse())
8488       break;
8489     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8490     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8491     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8492     if (Op0.getOpcode() == ISD::FNEG)
8493       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8494                          DAG.getConstant(SignBit, DL, VT));
8495 
8496     assert(Op0.getOpcode() == ISD::FABS);
8497     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8498                        DAG.getConstant(~SignBit, DL, VT));
8499   }
8500   case ISD::ADD:
8501     return performADDCombine(N, DAG, Subtarget);
8502   case ISD::SUB:
8503     return performSUBCombine(N, DAG);
8504   case ISD::AND:
8505     return performANDCombine(N, DAG);
8506   case ISD::OR:
8507     return performORCombine(N, DAG, Subtarget);
8508   case ISD::XOR:
8509     return performXORCombine(N, DAG);
8510   case ISD::SIGN_EXTEND_INREG:
8511     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8512   case ISD::ZERO_EXTEND:
8513     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8514     // type legalization. This is safe because fp_to_uint produces poison if
8515     // it overflows.
8516     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8517       SDValue Src = N->getOperand(0);
8518       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8519           isTypeLegal(Src.getOperand(0).getValueType()))
8520         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8521                            Src.getOperand(0));
8522       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8523           isTypeLegal(Src.getOperand(1).getValueType())) {
8524         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8525         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8526                                   Src.getOperand(0), Src.getOperand(1));
8527         DCI.CombineTo(N, Res);
8528         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8529         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8530         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8531       }
8532     }
8533     return SDValue();
8534   case RISCVISD::SELECT_CC: {
8535     // Transform
8536     SDValue LHS = N->getOperand(0);
8537     SDValue RHS = N->getOperand(1);
8538     SDValue TrueV = N->getOperand(3);
8539     SDValue FalseV = N->getOperand(4);
8540 
8541     // If the True and False values are the same, we don't need a select_cc.
8542     if (TrueV == FalseV)
8543       return TrueV;
8544 
8545     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8546     if (!ISD::isIntEqualitySetCC(CCVal))
8547       break;
8548 
8549     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8550     //      (select_cc X, Y, lt, trueV, falseV)
8551     // Sometimes the setcc is introduced after select_cc has been formed.
8552     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8553         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8554       // If we're looking for eq 0 instead of ne 0, we need to invert the
8555       // condition.
8556       bool Invert = CCVal == ISD::SETEQ;
8557       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8558       if (Invert)
8559         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8560 
8561       SDLoc DL(N);
8562       RHS = LHS.getOperand(1);
8563       LHS = LHS.getOperand(0);
8564       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8565 
8566       SDValue TargetCC = DAG.getCondCode(CCVal);
8567       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8568                          {LHS, RHS, TargetCC, TrueV, FalseV});
8569     }
8570 
8571     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8572     //      (select_cc X, Y, eq/ne, trueV, falseV)
8573     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8574       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8575                          {LHS.getOperand(0), LHS.getOperand(1),
8576                           N->getOperand(2), TrueV, FalseV});
8577     // (select_cc X, 1, setne, trueV, falseV) ->
8578     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8579     // This can occur when legalizing some floating point comparisons.
8580     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8581     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8582       SDLoc DL(N);
8583       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8584       SDValue TargetCC = DAG.getCondCode(CCVal);
8585       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8586       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8587                          {LHS, RHS, TargetCC, TrueV, FalseV});
8588     }
8589 
8590     break;
8591   }
8592   case RISCVISD::BR_CC: {
8593     SDValue LHS = N->getOperand(1);
8594     SDValue RHS = N->getOperand(2);
8595     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8596     if (!ISD::isIntEqualitySetCC(CCVal))
8597       break;
8598 
8599     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8600     //      (br_cc X, Y, lt, dest)
8601     // Sometimes the setcc is introduced after br_cc has been formed.
8602     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8603         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8604       // If we're looking for eq 0 instead of ne 0, we need to invert the
8605       // condition.
8606       bool Invert = CCVal == ISD::SETEQ;
8607       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8608       if (Invert)
8609         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8610 
8611       SDLoc DL(N);
8612       RHS = LHS.getOperand(1);
8613       LHS = LHS.getOperand(0);
8614       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8615 
8616       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8617                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8618                          N->getOperand(4));
8619     }
8620 
8621     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8622     //      (br_cc X, Y, eq/ne, trueV, falseV)
8623     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8624       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8625                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8626                          N->getOperand(3), N->getOperand(4));
8627 
8628     // (br_cc X, 1, setne, br_cc) ->
8629     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8630     // This can occur when legalizing some floating point comparisons.
8631     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8632     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8633       SDLoc DL(N);
8634       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8635       SDValue TargetCC = DAG.getCondCode(CCVal);
8636       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8637       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8638                          N->getOperand(0), LHS, RHS, TargetCC,
8639                          N->getOperand(4));
8640     }
8641     break;
8642   }
8643   case ISD::BITREVERSE:
8644     return performBITREVERSECombine(N, DAG, Subtarget);
8645   case ISD::FP_TO_SINT:
8646   case ISD::FP_TO_UINT:
8647     return performFP_TO_INTCombine(N, DCI, Subtarget);
8648   case ISD::FP_TO_SINT_SAT:
8649   case ISD::FP_TO_UINT_SAT:
8650     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8651   case ISD::FCOPYSIGN: {
8652     EVT VT = N->getValueType(0);
8653     if (!VT.isVector())
8654       break;
8655     // There is a form of VFSGNJ which injects the negated sign of its second
8656     // operand. Try and bubble any FNEG up after the extend/round to produce
8657     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8658     // TRUNC=1.
8659     SDValue In2 = N->getOperand(1);
8660     // Avoid cases where the extend/round has multiple uses, as duplicating
8661     // those is typically more expensive than removing a fneg.
8662     if (!In2.hasOneUse())
8663       break;
8664     if (In2.getOpcode() != ISD::FP_EXTEND &&
8665         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8666       break;
8667     In2 = In2.getOperand(0);
8668     if (In2.getOpcode() != ISD::FNEG)
8669       break;
8670     SDLoc DL(N);
8671     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8672     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8673                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8674   }
8675   case ISD::MGATHER:
8676   case ISD::MSCATTER:
8677   case ISD::VP_GATHER:
8678   case ISD::VP_SCATTER: {
8679     if (!DCI.isBeforeLegalize())
8680       break;
8681     SDValue Index, ScaleOp;
8682     bool IsIndexScaled = false;
8683     bool IsIndexSigned = false;
8684     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8685       Index = VPGSN->getIndex();
8686       ScaleOp = VPGSN->getScale();
8687       IsIndexScaled = VPGSN->isIndexScaled();
8688       IsIndexSigned = VPGSN->isIndexSigned();
8689     } else {
8690       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8691       Index = MGSN->getIndex();
8692       ScaleOp = MGSN->getScale();
8693       IsIndexScaled = MGSN->isIndexScaled();
8694       IsIndexSigned = MGSN->isIndexSigned();
8695     }
8696     EVT IndexVT = Index.getValueType();
8697     MVT XLenVT = Subtarget.getXLenVT();
8698     // RISCV indexed loads only support the "unsigned unscaled" addressing
8699     // mode, so anything else must be manually legalized.
8700     bool NeedsIdxLegalization =
8701         IsIndexScaled ||
8702         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8703     if (!NeedsIdxLegalization)
8704       break;
8705 
8706     SDLoc DL(N);
8707 
8708     // Any index legalization should first promote to XLenVT, so we don't lose
8709     // bits when scaling. This may create an illegal index type so we let
8710     // LLVM's legalization take care of the splitting.
8711     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8712     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8713       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8714       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8715                           DL, IndexVT, Index);
8716     }
8717 
8718     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8719     if (IsIndexScaled && Scale != 1) {
8720       // Manually scale the indices by the element size.
8721       // TODO: Sanitize the scale operand here?
8722       // TODO: For VP nodes, should we use VP_SHL here?
8723       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8724       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8725       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8726     }
8727 
8728     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8729     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8730       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8731                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8732                               VPGN->getScale(), VPGN->getMask(),
8733                               VPGN->getVectorLength()},
8734                              VPGN->getMemOperand(), NewIndexTy);
8735     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8736       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8737                               {VPSN->getChain(), VPSN->getValue(),
8738                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8739                                VPSN->getMask(), VPSN->getVectorLength()},
8740                               VPSN->getMemOperand(), NewIndexTy);
8741     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8742       return DAG.getMaskedGather(
8743           N->getVTList(), MGN->getMemoryVT(), DL,
8744           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8745            MGN->getBasePtr(), Index, MGN->getScale()},
8746           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8747     const auto *MSN = cast<MaskedScatterSDNode>(N);
8748     return DAG.getMaskedScatter(
8749         N->getVTList(), MSN->getMemoryVT(), DL,
8750         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8751          Index, MSN->getScale()},
8752         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8753   }
8754   case RISCVISD::SRA_VL:
8755   case RISCVISD::SRL_VL:
8756   case RISCVISD::SHL_VL: {
8757     SDValue ShAmt = N->getOperand(1);
8758     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8759       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8760       SDLoc DL(N);
8761       SDValue VL = N->getOperand(3);
8762       EVT VT = N->getValueType(0);
8763       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8764                           ShAmt.getOperand(1), VL);
8765       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8766                          N->getOperand(2), N->getOperand(3));
8767     }
8768     break;
8769   }
8770   case ISD::SRA:
8771   case ISD::SRL:
8772   case ISD::SHL: {
8773     SDValue ShAmt = N->getOperand(1);
8774     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8775       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8776       SDLoc DL(N);
8777       EVT VT = N->getValueType(0);
8778       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8779                           ShAmt.getOperand(1),
8780                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8781       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8782     }
8783     break;
8784   }
8785   case RISCVISD::ADD_VL:
8786     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8787       return V;
8788     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8789   case RISCVISD::SUB_VL:
8790     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8791   case RISCVISD::VWADD_W_VL:
8792   case RISCVISD::VWADDU_W_VL:
8793   case RISCVISD::VWSUB_W_VL:
8794   case RISCVISD::VWSUBU_W_VL:
8795     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8796   case RISCVISD::MUL_VL:
8797     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8798       return V;
8799     // Mul is commutative.
8800     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8801   case ISD::STORE: {
8802     auto *Store = cast<StoreSDNode>(N);
8803     SDValue Val = Store->getValue();
8804     // Combine store of vmv.x.s to vse with VL of 1.
8805     // FIXME: Support FP.
8806     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8807       SDValue Src = Val.getOperand(0);
8808       EVT VecVT = Src.getValueType();
8809       EVT MemVT = Store->getMemoryVT();
8810       // The memory VT and the element type must match.
8811       if (VecVT.getVectorElementType() == MemVT) {
8812         SDLoc DL(N);
8813         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8814         return DAG.getStoreVP(
8815             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8816             DAG.getConstant(1, DL, MaskVT),
8817             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8818             Store->getMemOperand(), Store->getAddressingMode(),
8819             Store->isTruncatingStore(), /*IsCompress*/ false);
8820       }
8821     }
8822 
8823     break;
8824   }
8825   case ISD::SPLAT_VECTOR: {
8826     EVT VT = N->getValueType(0);
8827     // Only perform this combine on legal MVT types.
8828     if (!isTypeLegal(VT))
8829       break;
8830     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8831                                          DAG, Subtarget))
8832       return Gather;
8833     break;
8834   }
8835   case RISCVISD::VMV_V_X_VL: {
8836     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8837     // scalar input.
8838     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8839     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8840     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8841       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8842         return SDValue(N, 0);
8843 
8844     break;
8845   }
8846   case ISD::INTRINSIC_WO_CHAIN: {
8847     unsigned IntNo = N->getConstantOperandVal(0);
8848     switch (IntNo) {
8849       // By default we do not combine any intrinsic.
8850     default:
8851       return SDValue();
8852     case Intrinsic::riscv_vcpop:
8853     case Intrinsic::riscv_vcpop_mask:
8854     case Intrinsic::riscv_vfirst:
8855     case Intrinsic::riscv_vfirst_mask: {
8856       SDValue VL = N->getOperand(2);
8857       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8858           IntNo == Intrinsic::riscv_vfirst_mask)
8859         VL = N->getOperand(3);
8860       if (!isNullConstant(VL))
8861         return SDValue();
8862       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8863       SDLoc DL(N);
8864       EVT VT = N->getValueType(0);
8865       if (IntNo == Intrinsic::riscv_vfirst ||
8866           IntNo == Intrinsic::riscv_vfirst_mask)
8867         return DAG.getConstant(-1, DL, VT);
8868       return DAG.getConstant(0, DL, VT);
8869     }
8870     }
8871   }
8872   }
8873 
8874   return SDValue();
8875 }
8876 
8877 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8878     const SDNode *N, CombineLevel Level) const {
8879   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8880   // materialised in fewer instructions than `(OP _, c1)`:
8881   //
8882   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8883   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8884   SDValue N0 = N->getOperand(0);
8885   EVT Ty = N0.getValueType();
8886   if (Ty.isScalarInteger() &&
8887       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8888     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8889     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8890     if (C1 && C2) {
8891       const APInt &C1Int = C1->getAPIntValue();
8892       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8893 
8894       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8895       // and the combine should happen, to potentially allow further combines
8896       // later.
8897       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8898           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8899         return true;
8900 
8901       // We can materialise `c1` in an add immediate, so it's "free", and the
8902       // combine should be prevented.
8903       if (C1Int.getMinSignedBits() <= 64 &&
8904           isLegalAddImmediate(C1Int.getSExtValue()))
8905         return false;
8906 
8907       // Neither constant will fit into an immediate, so find materialisation
8908       // costs.
8909       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8910                                               Subtarget.getFeatureBits(),
8911                                               /*CompressionCost*/true);
8912       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8913           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8914           /*CompressionCost*/true);
8915 
8916       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8917       // combine should be prevented.
8918       if (C1Cost < ShiftedC1Cost)
8919         return false;
8920     }
8921   }
8922   return true;
8923 }
8924 
8925 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8926     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8927     TargetLoweringOpt &TLO) const {
8928   // Delay this optimization as late as possible.
8929   if (!TLO.LegalOps)
8930     return false;
8931 
8932   EVT VT = Op.getValueType();
8933   if (VT.isVector())
8934     return false;
8935 
8936   // Only handle AND for now.
8937   if (Op.getOpcode() != ISD::AND)
8938     return false;
8939 
8940   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8941   if (!C)
8942     return false;
8943 
8944   const APInt &Mask = C->getAPIntValue();
8945 
8946   // Clear all non-demanded bits initially.
8947   APInt ShrunkMask = Mask & DemandedBits;
8948 
8949   // Try to make a smaller immediate by setting undemanded bits.
8950 
8951   APInt ExpandedMask = Mask | ~DemandedBits;
8952 
8953   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8954     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8955   };
8956   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8957     if (NewMask == Mask)
8958       return true;
8959     SDLoc DL(Op);
8960     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8961     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8962     return TLO.CombineTo(Op, NewOp);
8963   };
8964 
8965   // If the shrunk mask fits in sign extended 12 bits, let the target
8966   // independent code apply it.
8967   if (ShrunkMask.isSignedIntN(12))
8968     return false;
8969 
8970   // Preserve (and X, 0xffff) when zext.h is supported.
8971   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8972     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8973     if (IsLegalMask(NewMask))
8974       return UseMask(NewMask);
8975   }
8976 
8977   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8978   if (VT == MVT::i64) {
8979     APInt NewMask = APInt(64, 0xffffffff);
8980     if (IsLegalMask(NewMask))
8981       return UseMask(NewMask);
8982   }
8983 
8984   // For the remaining optimizations, we need to be able to make a negative
8985   // number through a combination of mask and undemanded bits.
8986   if (!ExpandedMask.isNegative())
8987     return false;
8988 
8989   // What is the fewest number of bits we need to represent the negative number.
8990   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8991 
8992   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8993   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8994   APInt NewMask = ShrunkMask;
8995   if (MinSignedBits <= 12)
8996     NewMask.setBitsFrom(11);
8997   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8998     NewMask.setBitsFrom(31);
8999   else
9000     return false;
9001 
9002   // Check that our new mask is a subset of the demanded mask.
9003   assert(IsLegalMask(NewMask));
9004   return UseMask(NewMask);
9005 }
9006 
9007 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9008   static const uint64_t GREVMasks[] = {
9009       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9010       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9011 
9012   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9013     unsigned Shift = 1 << Stage;
9014     if (ShAmt & Shift) {
9015       uint64_t Mask = GREVMasks[Stage];
9016       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9017       if (IsGORC)
9018         Res |= x;
9019       x = Res;
9020     }
9021   }
9022 
9023   return x;
9024 }
9025 
9026 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9027                                                         KnownBits &Known,
9028                                                         const APInt &DemandedElts,
9029                                                         const SelectionDAG &DAG,
9030                                                         unsigned Depth) const {
9031   unsigned BitWidth = Known.getBitWidth();
9032   unsigned Opc = Op.getOpcode();
9033   assert((Opc >= ISD::BUILTIN_OP_END ||
9034           Opc == ISD::INTRINSIC_WO_CHAIN ||
9035           Opc == ISD::INTRINSIC_W_CHAIN ||
9036           Opc == ISD::INTRINSIC_VOID) &&
9037          "Should use MaskedValueIsZero if you don't know whether Op"
9038          " is a target node!");
9039 
9040   Known.resetAll();
9041   switch (Opc) {
9042   default: break;
9043   case RISCVISD::SELECT_CC: {
9044     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9045     // If we don't know any bits, early out.
9046     if (Known.isUnknown())
9047       break;
9048     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9049 
9050     // Only known if known in both the LHS and RHS.
9051     Known = KnownBits::commonBits(Known, Known2);
9052     break;
9053   }
9054   case RISCVISD::REMUW: {
9055     KnownBits Known2;
9056     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9057     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9058     // We only care about the lower 32 bits.
9059     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9060     // Restore the original width by sign extending.
9061     Known = Known.sext(BitWidth);
9062     break;
9063   }
9064   case RISCVISD::DIVUW: {
9065     KnownBits Known2;
9066     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9067     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9068     // We only care about the lower 32 bits.
9069     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9070     // Restore the original width by sign extending.
9071     Known = Known.sext(BitWidth);
9072     break;
9073   }
9074   case RISCVISD::CTZW: {
9075     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9076     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9077     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9078     Known.Zero.setBitsFrom(LowBits);
9079     break;
9080   }
9081   case RISCVISD::CLZW: {
9082     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9083     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9084     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9085     Known.Zero.setBitsFrom(LowBits);
9086     break;
9087   }
9088   case RISCVISD::GREV:
9089   case RISCVISD::GORC: {
9090     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9091       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9092       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9093       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9094       // To compute zeros, we need to invert the value and invert it back after.
9095       Known.Zero =
9096           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9097       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9098     }
9099     break;
9100   }
9101   case RISCVISD::READ_VLENB: {
9102     // If we know the minimum VLen from Zvl extensions, we can use that to
9103     // determine the trailing zeros of VLENB.
9104     // FIXME: Limit to 128 bit vectors until we have more testing.
9105     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9106     if (MinVLenB > 0)
9107       Known.Zero.setLowBits(Log2_32(MinVLenB));
9108     // We assume VLENB is no more than 65536 / 8 bytes.
9109     Known.Zero.setBitsFrom(14);
9110     break;
9111   }
9112   case ISD::INTRINSIC_W_CHAIN:
9113   case ISD::INTRINSIC_WO_CHAIN: {
9114     unsigned IntNo =
9115         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9116     switch (IntNo) {
9117     default:
9118       // We can't do anything for most intrinsics.
9119       break;
9120     case Intrinsic::riscv_vsetvli:
9121     case Intrinsic::riscv_vsetvlimax:
9122     case Intrinsic::riscv_vsetvli_opt:
9123     case Intrinsic::riscv_vsetvlimax_opt:
9124       // Assume that VL output is positive and would fit in an int32_t.
9125       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9126       if (BitWidth >= 32)
9127         Known.Zero.setBitsFrom(31);
9128       break;
9129     }
9130     break;
9131   }
9132   }
9133 }
9134 
9135 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9136     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9137     unsigned Depth) const {
9138   switch (Op.getOpcode()) {
9139   default:
9140     break;
9141   case RISCVISD::SELECT_CC: {
9142     unsigned Tmp =
9143         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9144     if (Tmp == 1) return 1;  // Early out.
9145     unsigned Tmp2 =
9146         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9147     return std::min(Tmp, Tmp2);
9148   }
9149   case RISCVISD::SLLW:
9150   case RISCVISD::SRAW:
9151   case RISCVISD::SRLW:
9152   case RISCVISD::DIVW:
9153   case RISCVISD::DIVUW:
9154   case RISCVISD::REMUW:
9155   case RISCVISD::ROLW:
9156   case RISCVISD::RORW:
9157   case RISCVISD::GREVW:
9158   case RISCVISD::GORCW:
9159   case RISCVISD::FSLW:
9160   case RISCVISD::FSRW:
9161   case RISCVISD::SHFLW:
9162   case RISCVISD::UNSHFLW:
9163   case RISCVISD::BCOMPRESSW:
9164   case RISCVISD::BDECOMPRESSW:
9165   case RISCVISD::BFPW:
9166   case RISCVISD::FCVT_W_RV64:
9167   case RISCVISD::FCVT_WU_RV64:
9168   case RISCVISD::STRICT_FCVT_W_RV64:
9169   case RISCVISD::STRICT_FCVT_WU_RV64:
9170     // TODO: As the result is sign-extended, this is conservatively correct. A
9171     // more precise answer could be calculated for SRAW depending on known
9172     // bits in the shift amount.
9173     return 33;
9174   case RISCVISD::SHFL:
9175   case RISCVISD::UNSHFL: {
9176     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9177     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9178     // will stay within the upper 32 bits. If there were more than 32 sign bits
9179     // before there will be at least 33 sign bits after.
9180     if (Op.getValueType() == MVT::i64 &&
9181         isa<ConstantSDNode>(Op.getOperand(1)) &&
9182         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9183       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9184       if (Tmp > 32)
9185         return 33;
9186     }
9187     break;
9188   }
9189   case RISCVISD::VMV_X_S: {
9190     // The number of sign bits of the scalar result is computed by obtaining the
9191     // element type of the input vector operand, subtracting its width from the
9192     // XLEN, and then adding one (sign bit within the element type). If the
9193     // element type is wider than XLen, the least-significant XLEN bits are
9194     // taken.
9195     unsigned XLen = Subtarget.getXLen();
9196     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9197     if (EltBits <= XLen)
9198       return XLen - EltBits + 1;
9199     break;
9200   }
9201   }
9202 
9203   return 1;
9204 }
9205 
9206 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9207                                                   MachineBasicBlock *BB) {
9208   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9209 
9210   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9211   // Should the count have wrapped while it was being read, we need to try
9212   // again.
9213   // ...
9214   // read:
9215   // rdcycleh x3 # load high word of cycle
9216   // rdcycle  x2 # load low word of cycle
9217   // rdcycleh x4 # load high word of cycle
9218   // bne x3, x4, read # check if high word reads match, otherwise try again
9219   // ...
9220 
9221   MachineFunction &MF = *BB->getParent();
9222   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9223   MachineFunction::iterator It = ++BB->getIterator();
9224 
9225   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9226   MF.insert(It, LoopMBB);
9227 
9228   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9229   MF.insert(It, DoneMBB);
9230 
9231   // Transfer the remainder of BB and its successor edges to DoneMBB.
9232   DoneMBB->splice(DoneMBB->begin(), BB,
9233                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9234   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9235 
9236   BB->addSuccessor(LoopMBB);
9237 
9238   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9239   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9240   Register LoReg = MI.getOperand(0).getReg();
9241   Register HiReg = MI.getOperand(1).getReg();
9242   DebugLoc DL = MI.getDebugLoc();
9243 
9244   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9245   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9246       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9247       .addReg(RISCV::X0);
9248   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9249       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9250       .addReg(RISCV::X0);
9251   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9252       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9253       .addReg(RISCV::X0);
9254 
9255   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9256       .addReg(HiReg)
9257       .addReg(ReadAgainReg)
9258       .addMBB(LoopMBB);
9259 
9260   LoopMBB->addSuccessor(LoopMBB);
9261   LoopMBB->addSuccessor(DoneMBB);
9262 
9263   MI.eraseFromParent();
9264 
9265   return DoneMBB;
9266 }
9267 
9268 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9269                                              MachineBasicBlock *BB) {
9270   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9271 
9272   MachineFunction &MF = *BB->getParent();
9273   DebugLoc DL = MI.getDebugLoc();
9274   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9275   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9276   Register LoReg = MI.getOperand(0).getReg();
9277   Register HiReg = MI.getOperand(1).getReg();
9278   Register SrcReg = MI.getOperand(2).getReg();
9279   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9280   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9281 
9282   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9283                           RI);
9284   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9285   MachineMemOperand *MMOLo =
9286       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9287   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9288       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9289   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9290       .addFrameIndex(FI)
9291       .addImm(0)
9292       .addMemOperand(MMOLo);
9293   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9294       .addFrameIndex(FI)
9295       .addImm(4)
9296       .addMemOperand(MMOHi);
9297   MI.eraseFromParent(); // The pseudo instruction is gone now.
9298   return BB;
9299 }
9300 
9301 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9302                                                  MachineBasicBlock *BB) {
9303   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9304          "Unexpected instruction");
9305 
9306   MachineFunction &MF = *BB->getParent();
9307   DebugLoc DL = MI.getDebugLoc();
9308   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9309   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9310   Register DstReg = MI.getOperand(0).getReg();
9311   Register LoReg = MI.getOperand(1).getReg();
9312   Register HiReg = MI.getOperand(2).getReg();
9313   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9314   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9315 
9316   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9317   MachineMemOperand *MMOLo =
9318       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9319   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9320       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9321   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9322       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9323       .addFrameIndex(FI)
9324       .addImm(0)
9325       .addMemOperand(MMOLo);
9326   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9327       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9328       .addFrameIndex(FI)
9329       .addImm(4)
9330       .addMemOperand(MMOHi);
9331   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9332   MI.eraseFromParent(); // The pseudo instruction is gone now.
9333   return BB;
9334 }
9335 
9336 static bool isSelectPseudo(MachineInstr &MI) {
9337   switch (MI.getOpcode()) {
9338   default:
9339     return false;
9340   case RISCV::Select_GPR_Using_CC_GPR:
9341   case RISCV::Select_FPR16_Using_CC_GPR:
9342   case RISCV::Select_FPR32_Using_CC_GPR:
9343   case RISCV::Select_FPR64_Using_CC_GPR:
9344     return true;
9345   }
9346 }
9347 
9348 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9349                                         unsigned RelOpcode, unsigned EqOpcode,
9350                                         const RISCVSubtarget &Subtarget) {
9351   DebugLoc DL = MI.getDebugLoc();
9352   Register DstReg = MI.getOperand(0).getReg();
9353   Register Src1Reg = MI.getOperand(1).getReg();
9354   Register Src2Reg = MI.getOperand(2).getReg();
9355   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9356   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9357   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9358 
9359   // Save the current FFLAGS.
9360   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9361 
9362   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9363                  .addReg(Src1Reg)
9364                  .addReg(Src2Reg);
9365   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9366     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9367 
9368   // Restore the FFLAGS.
9369   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9370       .addReg(SavedFFlags, RegState::Kill);
9371 
9372   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9373   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9374                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9375                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9376   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9377     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9378 
9379   // Erase the pseudoinstruction.
9380   MI.eraseFromParent();
9381   return BB;
9382 }
9383 
9384 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9385                                            MachineBasicBlock *BB,
9386                                            const RISCVSubtarget &Subtarget) {
9387   // To "insert" Select_* instructions, we actually have to insert the triangle
9388   // control-flow pattern.  The incoming instructions know the destination vreg
9389   // to set, the condition code register to branch on, the true/false values to
9390   // select between, and the condcode to use to select the appropriate branch.
9391   //
9392   // We produce the following control flow:
9393   //     HeadMBB
9394   //     |  \
9395   //     |  IfFalseMBB
9396   //     | /
9397   //    TailMBB
9398   //
9399   // When we find a sequence of selects we attempt to optimize their emission
9400   // by sharing the control flow. Currently we only handle cases where we have
9401   // multiple selects with the exact same condition (same LHS, RHS and CC).
9402   // The selects may be interleaved with other instructions if the other
9403   // instructions meet some requirements we deem safe:
9404   // - They are debug instructions. Otherwise,
9405   // - They do not have side-effects, do not access memory and their inputs do
9406   //   not depend on the results of the select pseudo-instructions.
9407   // The TrueV/FalseV operands of the selects cannot depend on the result of
9408   // previous selects in the sequence.
9409   // These conditions could be further relaxed. See the X86 target for a
9410   // related approach and more information.
9411   Register LHS = MI.getOperand(1).getReg();
9412   Register RHS = MI.getOperand(2).getReg();
9413   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9414 
9415   SmallVector<MachineInstr *, 4> SelectDebugValues;
9416   SmallSet<Register, 4> SelectDests;
9417   SelectDests.insert(MI.getOperand(0).getReg());
9418 
9419   MachineInstr *LastSelectPseudo = &MI;
9420 
9421   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9422        SequenceMBBI != E; ++SequenceMBBI) {
9423     if (SequenceMBBI->isDebugInstr())
9424       continue;
9425     else if (isSelectPseudo(*SequenceMBBI)) {
9426       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9427           SequenceMBBI->getOperand(2).getReg() != RHS ||
9428           SequenceMBBI->getOperand(3).getImm() != CC ||
9429           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9430           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9431         break;
9432       LastSelectPseudo = &*SequenceMBBI;
9433       SequenceMBBI->collectDebugValues(SelectDebugValues);
9434       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9435     } else {
9436       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9437           SequenceMBBI->mayLoadOrStore())
9438         break;
9439       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9440             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9441           }))
9442         break;
9443     }
9444   }
9445 
9446   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9447   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9448   DebugLoc DL = MI.getDebugLoc();
9449   MachineFunction::iterator I = ++BB->getIterator();
9450 
9451   MachineBasicBlock *HeadMBB = BB;
9452   MachineFunction *F = BB->getParent();
9453   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9454   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9455 
9456   F->insert(I, IfFalseMBB);
9457   F->insert(I, TailMBB);
9458 
9459   // Transfer debug instructions associated with the selects to TailMBB.
9460   for (MachineInstr *DebugInstr : SelectDebugValues) {
9461     TailMBB->push_back(DebugInstr->removeFromParent());
9462   }
9463 
9464   // Move all instructions after the sequence to TailMBB.
9465   TailMBB->splice(TailMBB->end(), HeadMBB,
9466                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9467   // Update machine-CFG edges by transferring all successors of the current
9468   // block to the new block which will contain the Phi nodes for the selects.
9469   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9470   // Set the successors for HeadMBB.
9471   HeadMBB->addSuccessor(IfFalseMBB);
9472   HeadMBB->addSuccessor(TailMBB);
9473 
9474   // Insert appropriate branch.
9475   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9476     .addReg(LHS)
9477     .addReg(RHS)
9478     .addMBB(TailMBB);
9479 
9480   // IfFalseMBB just falls through to TailMBB.
9481   IfFalseMBB->addSuccessor(TailMBB);
9482 
9483   // Create PHIs for all of the select pseudo-instructions.
9484   auto SelectMBBI = MI.getIterator();
9485   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9486   auto InsertionPoint = TailMBB->begin();
9487   while (SelectMBBI != SelectEnd) {
9488     auto Next = std::next(SelectMBBI);
9489     if (isSelectPseudo(*SelectMBBI)) {
9490       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9491       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9492               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9493           .addReg(SelectMBBI->getOperand(4).getReg())
9494           .addMBB(HeadMBB)
9495           .addReg(SelectMBBI->getOperand(5).getReg())
9496           .addMBB(IfFalseMBB);
9497       SelectMBBI->eraseFromParent();
9498     }
9499     SelectMBBI = Next;
9500   }
9501 
9502   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9503   return TailMBB;
9504 }
9505 
9506 MachineBasicBlock *
9507 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9508                                                  MachineBasicBlock *BB) const {
9509   switch (MI.getOpcode()) {
9510   default:
9511     llvm_unreachable("Unexpected instr type to insert");
9512   case RISCV::ReadCycleWide:
9513     assert(!Subtarget.is64Bit() &&
9514            "ReadCycleWrite is only to be used on riscv32");
9515     return emitReadCycleWidePseudo(MI, BB);
9516   case RISCV::Select_GPR_Using_CC_GPR:
9517   case RISCV::Select_FPR16_Using_CC_GPR:
9518   case RISCV::Select_FPR32_Using_CC_GPR:
9519   case RISCV::Select_FPR64_Using_CC_GPR:
9520     return emitSelectPseudo(MI, BB, Subtarget);
9521   case RISCV::BuildPairF64Pseudo:
9522     return emitBuildPairF64Pseudo(MI, BB);
9523   case RISCV::SplitF64Pseudo:
9524     return emitSplitF64Pseudo(MI, BB);
9525   case RISCV::PseudoQuietFLE_H:
9526     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9527   case RISCV::PseudoQuietFLT_H:
9528     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9529   case RISCV::PseudoQuietFLE_S:
9530     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9531   case RISCV::PseudoQuietFLT_S:
9532     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9533   case RISCV::PseudoQuietFLE_D:
9534     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9535   case RISCV::PseudoQuietFLT_D:
9536     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9537   }
9538 }
9539 
9540 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9541                                                         SDNode *Node) const {
9542   // Add FRM dependency to any instructions with dynamic rounding mode.
9543   unsigned Opc = MI.getOpcode();
9544   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9545   if (Idx < 0)
9546     return;
9547   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9548     return;
9549   // If the instruction already reads FRM, don't add another read.
9550   if (MI.readsRegister(RISCV::FRM))
9551     return;
9552   MI.addOperand(
9553       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9554 }
9555 
9556 // Calling Convention Implementation.
9557 // The expectations for frontend ABI lowering vary from target to target.
9558 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9559 // details, but this is a longer term goal. For now, we simply try to keep the
9560 // role of the frontend as simple and well-defined as possible. The rules can
9561 // be summarised as:
9562 // * Never split up large scalar arguments. We handle them here.
9563 // * If a hardfloat calling convention is being used, and the struct may be
9564 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9565 // available, then pass as two separate arguments. If either the GPRs or FPRs
9566 // are exhausted, then pass according to the rule below.
9567 // * If a struct could never be passed in registers or directly in a stack
9568 // slot (as it is larger than 2*XLEN and the floating point rules don't
9569 // apply), then pass it using a pointer with the byval attribute.
9570 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9571 // word-sized array or a 2*XLEN scalar (depending on alignment).
9572 // * The frontend can determine whether a struct is returned by reference or
9573 // not based on its size and fields. If it will be returned by reference, the
9574 // frontend must modify the prototype so a pointer with the sret annotation is
9575 // passed as the first argument. This is not necessary for large scalar
9576 // returns.
9577 // * Struct return values and varargs should be coerced to structs containing
9578 // register-size fields in the same situations they would be for fixed
9579 // arguments.
9580 
9581 static const MCPhysReg ArgGPRs[] = {
9582   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9583   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9584 };
9585 static const MCPhysReg ArgFPR16s[] = {
9586   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9587   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9588 };
9589 static const MCPhysReg ArgFPR32s[] = {
9590   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9591   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9592 };
9593 static const MCPhysReg ArgFPR64s[] = {
9594   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9595   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9596 };
9597 // This is an interim calling convention and it may be changed in the future.
9598 static const MCPhysReg ArgVRs[] = {
9599     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9600     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9601     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9602 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9603                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9604                                      RISCV::V20M2, RISCV::V22M2};
9605 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9606                                      RISCV::V20M4};
9607 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9608 
9609 // Pass a 2*XLEN argument that has been split into two XLEN values through
9610 // registers or the stack as necessary.
9611 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9612                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9613                                 MVT ValVT2, MVT LocVT2,
9614                                 ISD::ArgFlagsTy ArgFlags2) {
9615   unsigned XLenInBytes = XLen / 8;
9616   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9617     // At least one half can be passed via register.
9618     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9619                                      VA1.getLocVT(), CCValAssign::Full));
9620   } else {
9621     // Both halves must be passed on the stack, with proper alignment.
9622     Align StackAlign =
9623         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9624     State.addLoc(
9625         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9626                             State.AllocateStack(XLenInBytes, StackAlign),
9627                             VA1.getLocVT(), CCValAssign::Full));
9628     State.addLoc(CCValAssign::getMem(
9629         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9630         LocVT2, CCValAssign::Full));
9631     return false;
9632   }
9633 
9634   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9635     // The second half can also be passed via register.
9636     State.addLoc(
9637         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9638   } else {
9639     // The second half is passed via the stack, without additional alignment.
9640     State.addLoc(CCValAssign::getMem(
9641         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9642         LocVT2, CCValAssign::Full));
9643   }
9644 
9645   return false;
9646 }
9647 
9648 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9649                                Optional<unsigned> FirstMaskArgument,
9650                                CCState &State, const RISCVTargetLowering &TLI) {
9651   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9652   if (RC == &RISCV::VRRegClass) {
9653     // Assign the first mask argument to V0.
9654     // This is an interim calling convention and it may be changed in the
9655     // future.
9656     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9657       return State.AllocateReg(RISCV::V0);
9658     return State.AllocateReg(ArgVRs);
9659   }
9660   if (RC == &RISCV::VRM2RegClass)
9661     return State.AllocateReg(ArgVRM2s);
9662   if (RC == &RISCV::VRM4RegClass)
9663     return State.AllocateReg(ArgVRM4s);
9664   if (RC == &RISCV::VRM8RegClass)
9665     return State.AllocateReg(ArgVRM8s);
9666   llvm_unreachable("Unhandled register class for ValueType");
9667 }
9668 
9669 // Implements the RISC-V calling convention. Returns true upon failure.
9670 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9671                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9672                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9673                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9674                      Optional<unsigned> FirstMaskArgument) {
9675   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9676   assert(XLen == 32 || XLen == 64);
9677   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9678 
9679   // Any return value split in to more than two values can't be returned
9680   // directly. Vectors are returned via the available vector registers.
9681   if (!LocVT.isVector() && IsRet && ValNo > 1)
9682     return true;
9683 
9684   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9685   // variadic argument, or if no F16/F32 argument registers are available.
9686   bool UseGPRForF16_F32 = true;
9687   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9688   // variadic argument, or if no F64 argument registers are available.
9689   bool UseGPRForF64 = true;
9690 
9691   switch (ABI) {
9692   default:
9693     llvm_unreachable("Unexpected ABI");
9694   case RISCVABI::ABI_ILP32:
9695   case RISCVABI::ABI_LP64:
9696     break;
9697   case RISCVABI::ABI_ILP32F:
9698   case RISCVABI::ABI_LP64F:
9699     UseGPRForF16_F32 = !IsFixed;
9700     break;
9701   case RISCVABI::ABI_ILP32D:
9702   case RISCVABI::ABI_LP64D:
9703     UseGPRForF16_F32 = !IsFixed;
9704     UseGPRForF64 = !IsFixed;
9705     break;
9706   }
9707 
9708   // FPR16, FPR32, and FPR64 alias each other.
9709   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9710     UseGPRForF16_F32 = true;
9711     UseGPRForF64 = true;
9712   }
9713 
9714   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9715   // similar local variables rather than directly checking against the target
9716   // ABI.
9717 
9718   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9719     LocVT = XLenVT;
9720     LocInfo = CCValAssign::BCvt;
9721   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9722     LocVT = MVT::i64;
9723     LocInfo = CCValAssign::BCvt;
9724   }
9725 
9726   // If this is a variadic argument, the RISC-V calling convention requires
9727   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9728   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9729   // be used regardless of whether the original argument was split during
9730   // legalisation or not. The argument will not be passed by registers if the
9731   // original type is larger than 2*XLEN, so the register alignment rule does
9732   // not apply.
9733   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9734   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9735       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9736     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9737     // Skip 'odd' register if necessary.
9738     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9739       State.AllocateReg(ArgGPRs);
9740   }
9741 
9742   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9743   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9744       State.getPendingArgFlags();
9745 
9746   assert(PendingLocs.size() == PendingArgFlags.size() &&
9747          "PendingLocs and PendingArgFlags out of sync");
9748 
9749   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9750   // registers are exhausted.
9751   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9752     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9753            "Can't lower f64 if it is split");
9754     // Depending on available argument GPRS, f64 may be passed in a pair of
9755     // GPRs, split between a GPR and the stack, or passed completely on the
9756     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9757     // cases.
9758     Register Reg = State.AllocateReg(ArgGPRs);
9759     LocVT = MVT::i32;
9760     if (!Reg) {
9761       unsigned StackOffset = State.AllocateStack(8, Align(8));
9762       State.addLoc(
9763           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9764       return false;
9765     }
9766     if (!State.AllocateReg(ArgGPRs))
9767       State.AllocateStack(4, Align(4));
9768     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9769     return false;
9770   }
9771 
9772   // Fixed-length vectors are located in the corresponding scalable-vector
9773   // container types.
9774   if (ValVT.isFixedLengthVector())
9775     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9776 
9777   // Split arguments might be passed indirectly, so keep track of the pending
9778   // values. Split vectors are passed via a mix of registers and indirectly, so
9779   // treat them as we would any other argument.
9780   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9781     LocVT = XLenVT;
9782     LocInfo = CCValAssign::Indirect;
9783     PendingLocs.push_back(
9784         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9785     PendingArgFlags.push_back(ArgFlags);
9786     if (!ArgFlags.isSplitEnd()) {
9787       return false;
9788     }
9789   }
9790 
9791   // If the split argument only had two elements, it should be passed directly
9792   // in registers or on the stack.
9793   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9794       PendingLocs.size() <= 2) {
9795     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9796     // Apply the normal calling convention rules to the first half of the
9797     // split argument.
9798     CCValAssign VA = PendingLocs[0];
9799     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9800     PendingLocs.clear();
9801     PendingArgFlags.clear();
9802     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9803                                ArgFlags);
9804   }
9805 
9806   // Allocate to a register if possible, or else a stack slot.
9807   Register Reg;
9808   unsigned StoreSizeBytes = XLen / 8;
9809   Align StackAlign = Align(XLen / 8);
9810 
9811   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9812     Reg = State.AllocateReg(ArgFPR16s);
9813   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9814     Reg = State.AllocateReg(ArgFPR32s);
9815   else if (ValVT == MVT::f64 && !UseGPRForF64)
9816     Reg = State.AllocateReg(ArgFPR64s);
9817   else if (ValVT.isVector()) {
9818     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9819     if (!Reg) {
9820       // For return values, the vector must be passed fully via registers or
9821       // via the stack.
9822       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9823       // but we're using all of them.
9824       if (IsRet)
9825         return true;
9826       // Try using a GPR to pass the address
9827       if ((Reg = State.AllocateReg(ArgGPRs))) {
9828         LocVT = XLenVT;
9829         LocInfo = CCValAssign::Indirect;
9830       } else if (ValVT.isScalableVector()) {
9831         LocVT = XLenVT;
9832         LocInfo = CCValAssign::Indirect;
9833       } else {
9834         // Pass fixed-length vectors on the stack.
9835         LocVT = ValVT;
9836         StoreSizeBytes = ValVT.getStoreSize();
9837         // Align vectors to their element sizes, being careful for vXi1
9838         // vectors.
9839         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9840       }
9841     }
9842   } else {
9843     Reg = State.AllocateReg(ArgGPRs);
9844   }
9845 
9846   unsigned StackOffset =
9847       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9848 
9849   // If we reach this point and PendingLocs is non-empty, we must be at the
9850   // end of a split argument that must be passed indirectly.
9851   if (!PendingLocs.empty()) {
9852     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9853     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9854 
9855     for (auto &It : PendingLocs) {
9856       if (Reg)
9857         It.convertToReg(Reg);
9858       else
9859         It.convertToMem(StackOffset);
9860       State.addLoc(It);
9861     }
9862     PendingLocs.clear();
9863     PendingArgFlags.clear();
9864     return false;
9865   }
9866 
9867   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9868           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9869          "Expected an XLenVT or vector types at this stage");
9870 
9871   if (Reg) {
9872     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9873     return false;
9874   }
9875 
9876   // When a floating-point value is passed on the stack, no bit-conversion is
9877   // needed.
9878   if (ValVT.isFloatingPoint()) {
9879     LocVT = ValVT;
9880     LocInfo = CCValAssign::Full;
9881   }
9882   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9883   return false;
9884 }
9885 
9886 template <typename ArgTy>
9887 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9888   for (const auto &ArgIdx : enumerate(Args)) {
9889     MVT ArgVT = ArgIdx.value().VT;
9890     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9891       return ArgIdx.index();
9892   }
9893   return None;
9894 }
9895 
9896 void RISCVTargetLowering::analyzeInputArgs(
9897     MachineFunction &MF, CCState &CCInfo,
9898     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9899     RISCVCCAssignFn Fn) const {
9900   unsigned NumArgs = Ins.size();
9901   FunctionType *FType = MF.getFunction().getFunctionType();
9902 
9903   Optional<unsigned> FirstMaskArgument;
9904   if (Subtarget.hasVInstructions())
9905     FirstMaskArgument = preAssignMask(Ins);
9906 
9907   for (unsigned i = 0; i != NumArgs; ++i) {
9908     MVT ArgVT = Ins[i].VT;
9909     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9910 
9911     Type *ArgTy = nullptr;
9912     if (IsRet)
9913       ArgTy = FType->getReturnType();
9914     else if (Ins[i].isOrigArg())
9915       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9916 
9917     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9918     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9919            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9920            FirstMaskArgument)) {
9921       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9922                         << EVT(ArgVT).getEVTString() << '\n');
9923       llvm_unreachable(nullptr);
9924     }
9925   }
9926 }
9927 
9928 void RISCVTargetLowering::analyzeOutputArgs(
9929     MachineFunction &MF, CCState &CCInfo,
9930     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9931     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9932   unsigned NumArgs = Outs.size();
9933 
9934   Optional<unsigned> FirstMaskArgument;
9935   if (Subtarget.hasVInstructions())
9936     FirstMaskArgument = preAssignMask(Outs);
9937 
9938   for (unsigned i = 0; i != NumArgs; i++) {
9939     MVT ArgVT = Outs[i].VT;
9940     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9941     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9942 
9943     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9944     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9945            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9946            FirstMaskArgument)) {
9947       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9948                         << EVT(ArgVT).getEVTString() << "\n");
9949       llvm_unreachable(nullptr);
9950     }
9951   }
9952 }
9953 
9954 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9955 // values.
9956 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9957                                    const CCValAssign &VA, const SDLoc &DL,
9958                                    const RISCVSubtarget &Subtarget) {
9959   switch (VA.getLocInfo()) {
9960   default:
9961     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9962   case CCValAssign::Full:
9963     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9964       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9965     break;
9966   case CCValAssign::BCvt:
9967     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9968       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9969     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9970       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9971     else
9972       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9973     break;
9974   }
9975   return Val;
9976 }
9977 
9978 // The caller is responsible for loading the full value if the argument is
9979 // passed with CCValAssign::Indirect.
9980 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9981                                 const CCValAssign &VA, const SDLoc &DL,
9982                                 const RISCVTargetLowering &TLI) {
9983   MachineFunction &MF = DAG.getMachineFunction();
9984   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9985   EVT LocVT = VA.getLocVT();
9986   SDValue Val;
9987   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9988   Register VReg = RegInfo.createVirtualRegister(RC);
9989   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9990   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9991 
9992   if (VA.getLocInfo() == CCValAssign::Indirect)
9993     return Val;
9994 
9995   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9996 }
9997 
9998 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9999                                    const CCValAssign &VA, const SDLoc &DL,
10000                                    const RISCVSubtarget &Subtarget) {
10001   EVT LocVT = VA.getLocVT();
10002 
10003   switch (VA.getLocInfo()) {
10004   default:
10005     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10006   case CCValAssign::Full:
10007     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10008       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10009     break;
10010   case CCValAssign::BCvt:
10011     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10012       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10013     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10014       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10015     else
10016       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10017     break;
10018   }
10019   return Val;
10020 }
10021 
10022 // The caller is responsible for loading the full value if the argument is
10023 // passed with CCValAssign::Indirect.
10024 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10025                                 const CCValAssign &VA, const SDLoc &DL) {
10026   MachineFunction &MF = DAG.getMachineFunction();
10027   MachineFrameInfo &MFI = MF.getFrameInfo();
10028   EVT LocVT = VA.getLocVT();
10029   EVT ValVT = VA.getValVT();
10030   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10031   if (ValVT.isScalableVector()) {
10032     // When the value is a scalable vector, we save the pointer which points to
10033     // the scalable vector value in the stack. The ValVT will be the pointer
10034     // type, instead of the scalable vector type.
10035     ValVT = LocVT;
10036   }
10037   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10038                                  /*IsImmutable=*/true);
10039   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10040   SDValue Val;
10041 
10042   ISD::LoadExtType ExtType;
10043   switch (VA.getLocInfo()) {
10044   default:
10045     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10046   case CCValAssign::Full:
10047   case CCValAssign::Indirect:
10048   case CCValAssign::BCvt:
10049     ExtType = ISD::NON_EXTLOAD;
10050     break;
10051   }
10052   Val = DAG.getExtLoad(
10053       ExtType, DL, LocVT, Chain, FIN,
10054       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10055   return Val;
10056 }
10057 
10058 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10059                                        const CCValAssign &VA, const SDLoc &DL) {
10060   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10061          "Unexpected VA");
10062   MachineFunction &MF = DAG.getMachineFunction();
10063   MachineFrameInfo &MFI = MF.getFrameInfo();
10064   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10065 
10066   if (VA.isMemLoc()) {
10067     // f64 is passed on the stack.
10068     int FI =
10069         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10070     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10071     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10072                        MachinePointerInfo::getFixedStack(MF, FI));
10073   }
10074 
10075   assert(VA.isRegLoc() && "Expected register VA assignment");
10076 
10077   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10078   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10079   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10080   SDValue Hi;
10081   if (VA.getLocReg() == RISCV::X17) {
10082     // Second half of f64 is passed on the stack.
10083     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10084     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10085     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10086                      MachinePointerInfo::getFixedStack(MF, FI));
10087   } else {
10088     // Second half of f64 is passed in another GPR.
10089     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10090     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10091     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10092   }
10093   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10094 }
10095 
10096 // FastCC has less than 1% performance improvement for some particular
10097 // benchmark. But theoretically, it may has benenfit for some cases.
10098 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10099                             unsigned ValNo, MVT ValVT, MVT LocVT,
10100                             CCValAssign::LocInfo LocInfo,
10101                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10102                             bool IsFixed, bool IsRet, Type *OrigTy,
10103                             const RISCVTargetLowering &TLI,
10104                             Optional<unsigned> FirstMaskArgument) {
10105 
10106   // X5 and X6 might be used for save-restore libcall.
10107   static const MCPhysReg GPRList[] = {
10108       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10109       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10110       RISCV::X29, RISCV::X30, RISCV::X31};
10111 
10112   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10113     if (unsigned Reg = State.AllocateReg(GPRList)) {
10114       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10115       return false;
10116     }
10117   }
10118 
10119   if (LocVT == MVT::f16) {
10120     static const MCPhysReg FPR16List[] = {
10121         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10122         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10123         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10124         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10125     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10126       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10127       return false;
10128     }
10129   }
10130 
10131   if (LocVT == MVT::f32) {
10132     static const MCPhysReg FPR32List[] = {
10133         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10134         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10135         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10136         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10137     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10138       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10139       return false;
10140     }
10141   }
10142 
10143   if (LocVT == MVT::f64) {
10144     static const MCPhysReg FPR64List[] = {
10145         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10146         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10147         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10148         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10149     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10150       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10151       return false;
10152     }
10153   }
10154 
10155   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10156     unsigned Offset4 = State.AllocateStack(4, Align(4));
10157     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10158     return false;
10159   }
10160 
10161   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10162     unsigned Offset5 = State.AllocateStack(8, Align(8));
10163     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10164     return false;
10165   }
10166 
10167   if (LocVT.isVector()) {
10168     if (unsigned Reg =
10169             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10170       // Fixed-length vectors are located in the corresponding scalable-vector
10171       // container types.
10172       if (ValVT.isFixedLengthVector())
10173         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10174       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10175     } else {
10176       // Try and pass the address via a "fast" GPR.
10177       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10178         LocInfo = CCValAssign::Indirect;
10179         LocVT = TLI.getSubtarget().getXLenVT();
10180         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10181       } else if (ValVT.isFixedLengthVector()) {
10182         auto StackAlign =
10183             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10184         unsigned StackOffset =
10185             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10186         State.addLoc(
10187             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10188       } else {
10189         // Can't pass scalable vectors on the stack.
10190         return true;
10191       }
10192     }
10193 
10194     return false;
10195   }
10196 
10197   return true; // CC didn't match.
10198 }
10199 
10200 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10201                          CCValAssign::LocInfo LocInfo,
10202                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10203 
10204   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10205     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10206     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10207     static const MCPhysReg GPRList[] = {
10208         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10209         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10210     if (unsigned Reg = State.AllocateReg(GPRList)) {
10211       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10212       return false;
10213     }
10214   }
10215 
10216   if (LocVT == MVT::f32) {
10217     // Pass in STG registers: F1, ..., F6
10218     //                        fs0 ... fs5
10219     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10220                                           RISCV::F18_F, RISCV::F19_F,
10221                                           RISCV::F20_F, RISCV::F21_F};
10222     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10223       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10224       return false;
10225     }
10226   }
10227 
10228   if (LocVT == MVT::f64) {
10229     // Pass in STG registers: D1, ..., D6
10230     //                        fs6 ... fs11
10231     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10232                                           RISCV::F24_D, RISCV::F25_D,
10233                                           RISCV::F26_D, RISCV::F27_D};
10234     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10235       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10236       return false;
10237     }
10238   }
10239 
10240   report_fatal_error("No registers left in GHC calling convention");
10241   return true;
10242 }
10243 
10244 // Transform physical registers into virtual registers.
10245 SDValue RISCVTargetLowering::LowerFormalArguments(
10246     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10247     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10248     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10249 
10250   MachineFunction &MF = DAG.getMachineFunction();
10251 
10252   switch (CallConv) {
10253   default:
10254     report_fatal_error("Unsupported calling convention");
10255   case CallingConv::C:
10256   case CallingConv::Fast:
10257     break;
10258   case CallingConv::GHC:
10259     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10260         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10261       report_fatal_error(
10262         "GHC calling convention requires the F and D instruction set extensions");
10263   }
10264 
10265   const Function &Func = MF.getFunction();
10266   if (Func.hasFnAttribute("interrupt")) {
10267     if (!Func.arg_empty())
10268       report_fatal_error(
10269         "Functions with the interrupt attribute cannot have arguments!");
10270 
10271     StringRef Kind =
10272       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10273 
10274     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10275       report_fatal_error(
10276         "Function interrupt attribute argument not supported!");
10277   }
10278 
10279   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10280   MVT XLenVT = Subtarget.getXLenVT();
10281   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10282   // Used with vargs to acumulate store chains.
10283   std::vector<SDValue> OutChains;
10284 
10285   // Assign locations to all of the incoming arguments.
10286   SmallVector<CCValAssign, 16> ArgLocs;
10287   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10288 
10289   if (CallConv == CallingConv::GHC)
10290     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10291   else
10292     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10293                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10294                                                    : CC_RISCV);
10295 
10296   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10297     CCValAssign &VA = ArgLocs[i];
10298     SDValue ArgValue;
10299     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10300     // case.
10301     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10302       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10303     else if (VA.isRegLoc())
10304       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10305     else
10306       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10307 
10308     if (VA.getLocInfo() == CCValAssign::Indirect) {
10309       // If the original argument was split and passed by reference (e.g. i128
10310       // on RV32), we need to load all parts of it here (using the same
10311       // address). Vectors may be partly split to registers and partly to the
10312       // stack, in which case the base address is partly offset and subsequent
10313       // stores are relative to that.
10314       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10315                                    MachinePointerInfo()));
10316       unsigned ArgIndex = Ins[i].OrigArgIndex;
10317       unsigned ArgPartOffset = Ins[i].PartOffset;
10318       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10319       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10320         CCValAssign &PartVA = ArgLocs[i + 1];
10321         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10322         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10323         if (PartVA.getValVT().isScalableVector())
10324           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10325         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10326         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10327                                      MachinePointerInfo()));
10328         ++i;
10329       }
10330       continue;
10331     }
10332     InVals.push_back(ArgValue);
10333   }
10334 
10335   if (IsVarArg) {
10336     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10337     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10338     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10339     MachineFrameInfo &MFI = MF.getFrameInfo();
10340     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10341     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10342 
10343     // Offset of the first variable argument from stack pointer, and size of
10344     // the vararg save area. For now, the varargs save area is either zero or
10345     // large enough to hold a0-a7.
10346     int VaArgOffset, VarArgsSaveSize;
10347 
10348     // If all registers are allocated, then all varargs must be passed on the
10349     // stack and we don't need to save any argregs.
10350     if (ArgRegs.size() == Idx) {
10351       VaArgOffset = CCInfo.getNextStackOffset();
10352       VarArgsSaveSize = 0;
10353     } else {
10354       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10355       VaArgOffset = -VarArgsSaveSize;
10356     }
10357 
10358     // Record the frame index of the first variable argument
10359     // which is a value necessary to VASTART.
10360     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10361     RVFI->setVarArgsFrameIndex(FI);
10362 
10363     // If saving an odd number of registers then create an extra stack slot to
10364     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10365     // offsets to even-numbered registered remain 2*XLEN-aligned.
10366     if (Idx % 2) {
10367       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10368       VarArgsSaveSize += XLenInBytes;
10369     }
10370 
10371     // Copy the integer registers that may have been used for passing varargs
10372     // to the vararg save area.
10373     for (unsigned I = Idx; I < ArgRegs.size();
10374          ++I, VaArgOffset += XLenInBytes) {
10375       const Register Reg = RegInfo.createVirtualRegister(RC);
10376       RegInfo.addLiveIn(ArgRegs[I], Reg);
10377       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10378       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10379       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10380       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10381                                    MachinePointerInfo::getFixedStack(MF, FI));
10382       cast<StoreSDNode>(Store.getNode())
10383           ->getMemOperand()
10384           ->setValue((Value *)nullptr);
10385       OutChains.push_back(Store);
10386     }
10387     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10388   }
10389 
10390   // All stores are grouped in one node to allow the matching between
10391   // the size of Ins and InVals. This only happens for vararg functions.
10392   if (!OutChains.empty()) {
10393     OutChains.push_back(Chain);
10394     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10395   }
10396 
10397   return Chain;
10398 }
10399 
10400 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10401 /// for tail call optimization.
10402 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10403 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10404     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10405     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10406 
10407   auto &Callee = CLI.Callee;
10408   auto CalleeCC = CLI.CallConv;
10409   auto &Outs = CLI.Outs;
10410   auto &Caller = MF.getFunction();
10411   auto CallerCC = Caller.getCallingConv();
10412 
10413   // Exception-handling functions need a special set of instructions to
10414   // indicate a return to the hardware. Tail-calling another function would
10415   // probably break this.
10416   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10417   // should be expanded as new function attributes are introduced.
10418   if (Caller.hasFnAttribute("interrupt"))
10419     return false;
10420 
10421   // Do not tail call opt if the stack is used to pass parameters.
10422   if (CCInfo.getNextStackOffset() != 0)
10423     return false;
10424 
10425   // Do not tail call opt if any parameters need to be passed indirectly.
10426   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10427   // passed indirectly. So the address of the value will be passed in a
10428   // register, or if not available, then the address is put on the stack. In
10429   // order to pass indirectly, space on the stack often needs to be allocated
10430   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10431   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10432   // are passed CCValAssign::Indirect.
10433   for (auto &VA : ArgLocs)
10434     if (VA.getLocInfo() == CCValAssign::Indirect)
10435       return false;
10436 
10437   // Do not tail call opt if either caller or callee uses struct return
10438   // semantics.
10439   auto IsCallerStructRet = Caller.hasStructRetAttr();
10440   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10441   if (IsCallerStructRet || IsCalleeStructRet)
10442     return false;
10443 
10444   // Externally-defined functions with weak linkage should not be
10445   // tail-called. The behaviour of branch instructions in this situation (as
10446   // used for tail calls) is implementation-defined, so we cannot rely on the
10447   // linker replacing the tail call with a return.
10448   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10449     const GlobalValue *GV = G->getGlobal();
10450     if (GV->hasExternalWeakLinkage())
10451       return false;
10452   }
10453 
10454   // The callee has to preserve all registers the caller needs to preserve.
10455   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10456   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10457   if (CalleeCC != CallerCC) {
10458     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10459     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10460       return false;
10461   }
10462 
10463   // Byval parameters hand the function a pointer directly into the stack area
10464   // we want to reuse during a tail call. Working around this *is* possible
10465   // but less efficient and uglier in LowerCall.
10466   for (auto &Arg : Outs)
10467     if (Arg.Flags.isByVal())
10468       return false;
10469 
10470   return true;
10471 }
10472 
10473 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10474   return DAG.getDataLayout().getPrefTypeAlign(
10475       VT.getTypeForEVT(*DAG.getContext()));
10476 }
10477 
10478 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10479 // and output parameter nodes.
10480 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10481                                        SmallVectorImpl<SDValue> &InVals) const {
10482   SelectionDAG &DAG = CLI.DAG;
10483   SDLoc &DL = CLI.DL;
10484   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10485   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10486   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10487   SDValue Chain = CLI.Chain;
10488   SDValue Callee = CLI.Callee;
10489   bool &IsTailCall = CLI.IsTailCall;
10490   CallingConv::ID CallConv = CLI.CallConv;
10491   bool IsVarArg = CLI.IsVarArg;
10492   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10493   MVT XLenVT = Subtarget.getXLenVT();
10494 
10495   MachineFunction &MF = DAG.getMachineFunction();
10496 
10497   // Analyze the operands of the call, assigning locations to each operand.
10498   SmallVector<CCValAssign, 16> ArgLocs;
10499   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10500 
10501   if (CallConv == CallingConv::GHC)
10502     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10503   else
10504     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10505                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10506                                                     : CC_RISCV);
10507 
10508   // Check if it's really possible to do a tail call.
10509   if (IsTailCall)
10510     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10511 
10512   if (IsTailCall)
10513     ++NumTailCalls;
10514   else if (CLI.CB && CLI.CB->isMustTailCall())
10515     report_fatal_error("failed to perform tail call elimination on a call "
10516                        "site marked musttail");
10517 
10518   // Get a count of how many bytes are to be pushed on the stack.
10519   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10520 
10521   // Create local copies for byval args
10522   SmallVector<SDValue, 8> ByValArgs;
10523   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10524     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10525     if (!Flags.isByVal())
10526       continue;
10527 
10528     SDValue Arg = OutVals[i];
10529     unsigned Size = Flags.getByValSize();
10530     Align Alignment = Flags.getNonZeroByValAlign();
10531 
10532     int FI =
10533         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10534     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10535     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10536 
10537     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10538                           /*IsVolatile=*/false,
10539                           /*AlwaysInline=*/false, IsTailCall,
10540                           MachinePointerInfo(), MachinePointerInfo());
10541     ByValArgs.push_back(FIPtr);
10542   }
10543 
10544   if (!IsTailCall)
10545     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10546 
10547   // Copy argument values to their designated locations.
10548   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10549   SmallVector<SDValue, 8> MemOpChains;
10550   SDValue StackPtr;
10551   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10552     CCValAssign &VA = ArgLocs[i];
10553     SDValue ArgValue = OutVals[i];
10554     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10555 
10556     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10557     bool IsF64OnRV32DSoftABI =
10558         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10559     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10560       SDValue SplitF64 = DAG.getNode(
10561           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10562       SDValue Lo = SplitF64.getValue(0);
10563       SDValue Hi = SplitF64.getValue(1);
10564 
10565       Register RegLo = VA.getLocReg();
10566       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10567 
10568       if (RegLo == RISCV::X17) {
10569         // Second half of f64 is passed on the stack.
10570         // Work out the address of the stack slot.
10571         if (!StackPtr.getNode())
10572           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10573         // Emit the store.
10574         MemOpChains.push_back(
10575             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10576       } else {
10577         // Second half of f64 is passed in another GPR.
10578         assert(RegLo < RISCV::X31 && "Invalid register pair");
10579         Register RegHigh = RegLo + 1;
10580         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10581       }
10582       continue;
10583     }
10584 
10585     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10586     // as any other MemLoc.
10587 
10588     // Promote the value if needed.
10589     // For now, only handle fully promoted and indirect arguments.
10590     if (VA.getLocInfo() == CCValAssign::Indirect) {
10591       // Store the argument in a stack slot and pass its address.
10592       Align StackAlign =
10593           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10594                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10595       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10596       // If the original argument was split (e.g. i128), we need
10597       // to store the required parts of it here (and pass just one address).
10598       // Vectors may be partly split to registers and partly to the stack, in
10599       // which case the base address is partly offset and subsequent stores are
10600       // relative to that.
10601       unsigned ArgIndex = Outs[i].OrigArgIndex;
10602       unsigned ArgPartOffset = Outs[i].PartOffset;
10603       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10604       // Calculate the total size to store. We don't have access to what we're
10605       // actually storing other than performing the loop and collecting the
10606       // info.
10607       SmallVector<std::pair<SDValue, SDValue>> Parts;
10608       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10609         SDValue PartValue = OutVals[i + 1];
10610         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10611         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10612         EVT PartVT = PartValue.getValueType();
10613         if (PartVT.isScalableVector())
10614           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10615         StoredSize += PartVT.getStoreSize();
10616         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10617         Parts.push_back(std::make_pair(PartValue, Offset));
10618         ++i;
10619       }
10620       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10621       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10622       MemOpChains.push_back(
10623           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10624                        MachinePointerInfo::getFixedStack(MF, FI)));
10625       for (const auto &Part : Parts) {
10626         SDValue PartValue = Part.first;
10627         SDValue PartOffset = Part.second;
10628         SDValue Address =
10629             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10630         MemOpChains.push_back(
10631             DAG.getStore(Chain, DL, PartValue, Address,
10632                          MachinePointerInfo::getFixedStack(MF, FI)));
10633       }
10634       ArgValue = SpillSlot;
10635     } else {
10636       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10637     }
10638 
10639     // Use local copy if it is a byval arg.
10640     if (Flags.isByVal())
10641       ArgValue = ByValArgs[j++];
10642 
10643     if (VA.isRegLoc()) {
10644       // Queue up the argument copies and emit them at the end.
10645       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10646     } else {
10647       assert(VA.isMemLoc() && "Argument not register or memory");
10648       assert(!IsTailCall && "Tail call not allowed if stack is used "
10649                             "for passing parameters");
10650 
10651       // Work out the address of the stack slot.
10652       if (!StackPtr.getNode())
10653         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10654       SDValue Address =
10655           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10656                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10657 
10658       // Emit the store.
10659       MemOpChains.push_back(
10660           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10661     }
10662   }
10663 
10664   // Join the stores, which are independent of one another.
10665   if (!MemOpChains.empty())
10666     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10667 
10668   SDValue Glue;
10669 
10670   // Build a sequence of copy-to-reg nodes, chained and glued together.
10671   for (auto &Reg : RegsToPass) {
10672     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10673     Glue = Chain.getValue(1);
10674   }
10675 
10676   // Validate that none of the argument registers have been marked as
10677   // reserved, if so report an error. Do the same for the return address if this
10678   // is not a tailcall.
10679   validateCCReservedRegs(RegsToPass, MF);
10680   if (!IsTailCall &&
10681       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10682     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10683         MF.getFunction(),
10684         "Return address register required, but has been reserved."});
10685 
10686   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10687   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10688   // split it and then direct call can be matched by PseudoCALL.
10689   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10690     const GlobalValue *GV = S->getGlobal();
10691 
10692     unsigned OpFlags = RISCVII::MO_CALL;
10693     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10694       OpFlags = RISCVII::MO_PLT;
10695 
10696     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10697   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10698     unsigned OpFlags = RISCVII::MO_CALL;
10699 
10700     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10701                                                  nullptr))
10702       OpFlags = RISCVII::MO_PLT;
10703 
10704     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10705   }
10706 
10707   // The first call operand is the chain and the second is the target address.
10708   SmallVector<SDValue, 8> Ops;
10709   Ops.push_back(Chain);
10710   Ops.push_back(Callee);
10711 
10712   // Add argument registers to the end of the list so that they are
10713   // known live into the call.
10714   for (auto &Reg : RegsToPass)
10715     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10716 
10717   if (!IsTailCall) {
10718     // Add a register mask operand representing the call-preserved registers.
10719     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10720     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10721     assert(Mask && "Missing call preserved mask for calling convention");
10722     Ops.push_back(DAG.getRegisterMask(Mask));
10723   }
10724 
10725   // Glue the call to the argument copies, if any.
10726   if (Glue.getNode())
10727     Ops.push_back(Glue);
10728 
10729   // Emit the call.
10730   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10731 
10732   if (IsTailCall) {
10733     MF.getFrameInfo().setHasTailCall();
10734     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10735   }
10736 
10737   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10738   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10739   Glue = Chain.getValue(1);
10740 
10741   // Mark the end of the call, which is glued to the call itself.
10742   Chain = DAG.getCALLSEQ_END(Chain,
10743                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10744                              DAG.getConstant(0, DL, PtrVT, true),
10745                              Glue, DL);
10746   Glue = Chain.getValue(1);
10747 
10748   // Assign locations to each value returned by this call.
10749   SmallVector<CCValAssign, 16> RVLocs;
10750   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10751   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10752 
10753   // Copy all of the result registers out of their specified physreg.
10754   for (auto &VA : RVLocs) {
10755     // Copy the value out
10756     SDValue RetValue =
10757         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10758     // Glue the RetValue to the end of the call sequence
10759     Chain = RetValue.getValue(1);
10760     Glue = RetValue.getValue(2);
10761 
10762     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10763       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10764       SDValue RetValue2 =
10765           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10766       Chain = RetValue2.getValue(1);
10767       Glue = RetValue2.getValue(2);
10768       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10769                              RetValue2);
10770     }
10771 
10772     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10773 
10774     InVals.push_back(RetValue);
10775   }
10776 
10777   return Chain;
10778 }
10779 
10780 bool RISCVTargetLowering::CanLowerReturn(
10781     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10782     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10783   SmallVector<CCValAssign, 16> RVLocs;
10784   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10785 
10786   Optional<unsigned> FirstMaskArgument;
10787   if (Subtarget.hasVInstructions())
10788     FirstMaskArgument = preAssignMask(Outs);
10789 
10790   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10791     MVT VT = Outs[i].VT;
10792     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10793     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10794     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10795                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10796                  *this, FirstMaskArgument))
10797       return false;
10798   }
10799   return true;
10800 }
10801 
10802 SDValue
10803 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10804                                  bool IsVarArg,
10805                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10806                                  const SmallVectorImpl<SDValue> &OutVals,
10807                                  const SDLoc &DL, SelectionDAG &DAG) const {
10808   const MachineFunction &MF = DAG.getMachineFunction();
10809   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10810 
10811   // Stores the assignment of the return value to a location.
10812   SmallVector<CCValAssign, 16> RVLocs;
10813 
10814   // Info about the registers and stack slot.
10815   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10816                  *DAG.getContext());
10817 
10818   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10819                     nullptr, CC_RISCV);
10820 
10821   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10822     report_fatal_error("GHC functions return void only");
10823 
10824   SDValue Glue;
10825   SmallVector<SDValue, 4> RetOps(1, Chain);
10826 
10827   // Copy the result values into the output registers.
10828   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10829     SDValue Val = OutVals[i];
10830     CCValAssign &VA = RVLocs[i];
10831     assert(VA.isRegLoc() && "Can only return in registers!");
10832 
10833     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10834       // Handle returning f64 on RV32D with a soft float ABI.
10835       assert(VA.isRegLoc() && "Expected return via registers");
10836       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10837                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10838       SDValue Lo = SplitF64.getValue(0);
10839       SDValue Hi = SplitF64.getValue(1);
10840       Register RegLo = VA.getLocReg();
10841       assert(RegLo < RISCV::X31 && "Invalid register pair");
10842       Register RegHi = RegLo + 1;
10843 
10844       if (STI.isRegisterReservedByUser(RegLo) ||
10845           STI.isRegisterReservedByUser(RegHi))
10846         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10847             MF.getFunction(),
10848             "Return value register required, but has been reserved."});
10849 
10850       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10851       Glue = Chain.getValue(1);
10852       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10853       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10854       Glue = Chain.getValue(1);
10855       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10856     } else {
10857       // Handle a 'normal' return.
10858       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10859       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10860 
10861       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10862         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10863             MF.getFunction(),
10864             "Return value register required, but has been reserved."});
10865 
10866       // Guarantee that all emitted copies are stuck together.
10867       Glue = Chain.getValue(1);
10868       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10869     }
10870   }
10871 
10872   RetOps[0] = Chain; // Update chain.
10873 
10874   // Add the glue node if we have it.
10875   if (Glue.getNode()) {
10876     RetOps.push_back(Glue);
10877   }
10878 
10879   unsigned RetOpc = RISCVISD::RET_FLAG;
10880   // Interrupt service routines use different return instructions.
10881   const Function &Func = DAG.getMachineFunction().getFunction();
10882   if (Func.hasFnAttribute("interrupt")) {
10883     if (!Func.getReturnType()->isVoidTy())
10884       report_fatal_error(
10885           "Functions with the interrupt attribute must have void return type!");
10886 
10887     MachineFunction &MF = DAG.getMachineFunction();
10888     StringRef Kind =
10889       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10890 
10891     if (Kind == "user")
10892       RetOpc = RISCVISD::URET_FLAG;
10893     else if (Kind == "supervisor")
10894       RetOpc = RISCVISD::SRET_FLAG;
10895     else
10896       RetOpc = RISCVISD::MRET_FLAG;
10897   }
10898 
10899   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10900 }
10901 
10902 void RISCVTargetLowering::validateCCReservedRegs(
10903     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10904     MachineFunction &MF) const {
10905   const Function &F = MF.getFunction();
10906   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10907 
10908   if (llvm::any_of(Regs, [&STI](auto Reg) {
10909         return STI.isRegisterReservedByUser(Reg.first);
10910       }))
10911     F.getContext().diagnose(DiagnosticInfoUnsupported{
10912         F, "Argument register required, but has been reserved."});
10913 }
10914 
10915 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10916   return CI->isTailCall();
10917 }
10918 
10919 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10920 #define NODE_NAME_CASE(NODE)                                                   \
10921   case RISCVISD::NODE:                                                         \
10922     return "RISCVISD::" #NODE;
10923   // clang-format off
10924   switch ((RISCVISD::NodeType)Opcode) {
10925   case RISCVISD::FIRST_NUMBER:
10926     break;
10927   NODE_NAME_CASE(RET_FLAG)
10928   NODE_NAME_CASE(URET_FLAG)
10929   NODE_NAME_CASE(SRET_FLAG)
10930   NODE_NAME_CASE(MRET_FLAG)
10931   NODE_NAME_CASE(CALL)
10932   NODE_NAME_CASE(SELECT_CC)
10933   NODE_NAME_CASE(BR_CC)
10934   NODE_NAME_CASE(BuildPairF64)
10935   NODE_NAME_CASE(SplitF64)
10936   NODE_NAME_CASE(TAIL)
10937   NODE_NAME_CASE(MULHSU)
10938   NODE_NAME_CASE(SLLW)
10939   NODE_NAME_CASE(SRAW)
10940   NODE_NAME_CASE(SRLW)
10941   NODE_NAME_CASE(DIVW)
10942   NODE_NAME_CASE(DIVUW)
10943   NODE_NAME_CASE(REMUW)
10944   NODE_NAME_CASE(ROLW)
10945   NODE_NAME_CASE(RORW)
10946   NODE_NAME_CASE(CLZW)
10947   NODE_NAME_CASE(CTZW)
10948   NODE_NAME_CASE(FSLW)
10949   NODE_NAME_CASE(FSRW)
10950   NODE_NAME_CASE(FSL)
10951   NODE_NAME_CASE(FSR)
10952   NODE_NAME_CASE(FMV_H_X)
10953   NODE_NAME_CASE(FMV_X_ANYEXTH)
10954   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10955   NODE_NAME_CASE(FMV_W_X_RV64)
10956   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10957   NODE_NAME_CASE(FCVT_X)
10958   NODE_NAME_CASE(FCVT_XU)
10959   NODE_NAME_CASE(FCVT_W_RV64)
10960   NODE_NAME_CASE(FCVT_WU_RV64)
10961   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10962   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10963   NODE_NAME_CASE(READ_CYCLE_WIDE)
10964   NODE_NAME_CASE(GREV)
10965   NODE_NAME_CASE(GREVW)
10966   NODE_NAME_CASE(GORC)
10967   NODE_NAME_CASE(GORCW)
10968   NODE_NAME_CASE(SHFL)
10969   NODE_NAME_CASE(SHFLW)
10970   NODE_NAME_CASE(UNSHFL)
10971   NODE_NAME_CASE(UNSHFLW)
10972   NODE_NAME_CASE(BFP)
10973   NODE_NAME_CASE(BFPW)
10974   NODE_NAME_CASE(BCOMPRESS)
10975   NODE_NAME_CASE(BCOMPRESSW)
10976   NODE_NAME_CASE(BDECOMPRESS)
10977   NODE_NAME_CASE(BDECOMPRESSW)
10978   NODE_NAME_CASE(VMV_V_X_VL)
10979   NODE_NAME_CASE(VFMV_V_F_VL)
10980   NODE_NAME_CASE(VMV_X_S)
10981   NODE_NAME_CASE(VMV_S_X_VL)
10982   NODE_NAME_CASE(VFMV_S_F_VL)
10983   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10984   NODE_NAME_CASE(READ_VLENB)
10985   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10986   NODE_NAME_CASE(VSLIDEUP_VL)
10987   NODE_NAME_CASE(VSLIDE1UP_VL)
10988   NODE_NAME_CASE(VSLIDEDOWN_VL)
10989   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10990   NODE_NAME_CASE(VID_VL)
10991   NODE_NAME_CASE(VFNCVT_ROD_VL)
10992   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10993   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10994   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10995   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10996   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10997   NODE_NAME_CASE(VECREDUCE_AND_VL)
10998   NODE_NAME_CASE(VECREDUCE_OR_VL)
10999   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11000   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11001   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11002   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11003   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11004   NODE_NAME_CASE(ADD_VL)
11005   NODE_NAME_CASE(AND_VL)
11006   NODE_NAME_CASE(MUL_VL)
11007   NODE_NAME_CASE(OR_VL)
11008   NODE_NAME_CASE(SDIV_VL)
11009   NODE_NAME_CASE(SHL_VL)
11010   NODE_NAME_CASE(SREM_VL)
11011   NODE_NAME_CASE(SRA_VL)
11012   NODE_NAME_CASE(SRL_VL)
11013   NODE_NAME_CASE(SUB_VL)
11014   NODE_NAME_CASE(UDIV_VL)
11015   NODE_NAME_CASE(UREM_VL)
11016   NODE_NAME_CASE(XOR_VL)
11017   NODE_NAME_CASE(SADDSAT_VL)
11018   NODE_NAME_CASE(UADDSAT_VL)
11019   NODE_NAME_CASE(SSUBSAT_VL)
11020   NODE_NAME_CASE(USUBSAT_VL)
11021   NODE_NAME_CASE(FADD_VL)
11022   NODE_NAME_CASE(FSUB_VL)
11023   NODE_NAME_CASE(FMUL_VL)
11024   NODE_NAME_CASE(FDIV_VL)
11025   NODE_NAME_CASE(FNEG_VL)
11026   NODE_NAME_CASE(FABS_VL)
11027   NODE_NAME_CASE(FSQRT_VL)
11028   NODE_NAME_CASE(FMA_VL)
11029   NODE_NAME_CASE(FCOPYSIGN_VL)
11030   NODE_NAME_CASE(SMIN_VL)
11031   NODE_NAME_CASE(SMAX_VL)
11032   NODE_NAME_CASE(UMIN_VL)
11033   NODE_NAME_CASE(UMAX_VL)
11034   NODE_NAME_CASE(FMINNUM_VL)
11035   NODE_NAME_CASE(FMAXNUM_VL)
11036   NODE_NAME_CASE(MULHS_VL)
11037   NODE_NAME_CASE(MULHU_VL)
11038   NODE_NAME_CASE(FP_TO_SINT_VL)
11039   NODE_NAME_CASE(FP_TO_UINT_VL)
11040   NODE_NAME_CASE(SINT_TO_FP_VL)
11041   NODE_NAME_CASE(UINT_TO_FP_VL)
11042   NODE_NAME_CASE(FP_EXTEND_VL)
11043   NODE_NAME_CASE(FP_ROUND_VL)
11044   NODE_NAME_CASE(VWMUL_VL)
11045   NODE_NAME_CASE(VWMULU_VL)
11046   NODE_NAME_CASE(VWMULSU_VL)
11047   NODE_NAME_CASE(VWADD_VL)
11048   NODE_NAME_CASE(VWADDU_VL)
11049   NODE_NAME_CASE(VWSUB_VL)
11050   NODE_NAME_CASE(VWSUBU_VL)
11051   NODE_NAME_CASE(VWADD_W_VL)
11052   NODE_NAME_CASE(VWADDU_W_VL)
11053   NODE_NAME_CASE(VWSUB_W_VL)
11054   NODE_NAME_CASE(VWSUBU_W_VL)
11055   NODE_NAME_CASE(SETCC_VL)
11056   NODE_NAME_CASE(VSELECT_VL)
11057   NODE_NAME_CASE(VP_MERGE_VL)
11058   NODE_NAME_CASE(VMAND_VL)
11059   NODE_NAME_CASE(VMOR_VL)
11060   NODE_NAME_CASE(VMXOR_VL)
11061   NODE_NAME_CASE(VMCLR_VL)
11062   NODE_NAME_CASE(VMSET_VL)
11063   NODE_NAME_CASE(VRGATHER_VX_VL)
11064   NODE_NAME_CASE(VRGATHER_VV_VL)
11065   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11066   NODE_NAME_CASE(VSEXT_VL)
11067   NODE_NAME_CASE(VZEXT_VL)
11068   NODE_NAME_CASE(VCPOP_VL)
11069   NODE_NAME_CASE(READ_CSR)
11070   NODE_NAME_CASE(WRITE_CSR)
11071   NODE_NAME_CASE(SWAP_CSR)
11072   }
11073   // clang-format on
11074   return nullptr;
11075 #undef NODE_NAME_CASE
11076 }
11077 
11078 /// getConstraintType - Given a constraint letter, return the type of
11079 /// constraint it is for this target.
11080 RISCVTargetLowering::ConstraintType
11081 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11082   if (Constraint.size() == 1) {
11083     switch (Constraint[0]) {
11084     default:
11085       break;
11086     case 'f':
11087       return C_RegisterClass;
11088     case 'I':
11089     case 'J':
11090     case 'K':
11091       return C_Immediate;
11092     case 'A':
11093       return C_Memory;
11094     case 'S': // A symbolic address
11095       return C_Other;
11096     }
11097   } else {
11098     if (Constraint == "vr" || Constraint == "vm")
11099       return C_RegisterClass;
11100   }
11101   return TargetLowering::getConstraintType(Constraint);
11102 }
11103 
11104 std::pair<unsigned, const TargetRegisterClass *>
11105 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11106                                                   StringRef Constraint,
11107                                                   MVT VT) const {
11108   // First, see if this is a constraint that directly corresponds to a
11109   // RISCV register class.
11110   if (Constraint.size() == 1) {
11111     switch (Constraint[0]) {
11112     case 'r':
11113       // TODO: Support fixed vectors up to XLen for P extension?
11114       if (VT.isVector())
11115         break;
11116       return std::make_pair(0U, &RISCV::GPRRegClass);
11117     case 'f':
11118       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11119         return std::make_pair(0U, &RISCV::FPR16RegClass);
11120       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11121         return std::make_pair(0U, &RISCV::FPR32RegClass);
11122       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11123         return std::make_pair(0U, &RISCV::FPR64RegClass);
11124       break;
11125     default:
11126       break;
11127     }
11128   } else if (Constraint == "vr") {
11129     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11130                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11131       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11132         return std::make_pair(0U, RC);
11133     }
11134   } else if (Constraint == "vm") {
11135     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11136       return std::make_pair(0U, &RISCV::VMV0RegClass);
11137   }
11138 
11139   // Clang will correctly decode the usage of register name aliases into their
11140   // official names. However, other frontends like `rustc` do not. This allows
11141   // users of these frontends to use the ABI names for registers in LLVM-style
11142   // register constraints.
11143   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11144                                .Case("{zero}", RISCV::X0)
11145                                .Case("{ra}", RISCV::X1)
11146                                .Case("{sp}", RISCV::X2)
11147                                .Case("{gp}", RISCV::X3)
11148                                .Case("{tp}", RISCV::X4)
11149                                .Case("{t0}", RISCV::X5)
11150                                .Case("{t1}", RISCV::X6)
11151                                .Case("{t2}", RISCV::X7)
11152                                .Cases("{s0}", "{fp}", RISCV::X8)
11153                                .Case("{s1}", RISCV::X9)
11154                                .Case("{a0}", RISCV::X10)
11155                                .Case("{a1}", RISCV::X11)
11156                                .Case("{a2}", RISCV::X12)
11157                                .Case("{a3}", RISCV::X13)
11158                                .Case("{a4}", RISCV::X14)
11159                                .Case("{a5}", RISCV::X15)
11160                                .Case("{a6}", RISCV::X16)
11161                                .Case("{a7}", RISCV::X17)
11162                                .Case("{s2}", RISCV::X18)
11163                                .Case("{s3}", RISCV::X19)
11164                                .Case("{s4}", RISCV::X20)
11165                                .Case("{s5}", RISCV::X21)
11166                                .Case("{s6}", RISCV::X22)
11167                                .Case("{s7}", RISCV::X23)
11168                                .Case("{s8}", RISCV::X24)
11169                                .Case("{s9}", RISCV::X25)
11170                                .Case("{s10}", RISCV::X26)
11171                                .Case("{s11}", RISCV::X27)
11172                                .Case("{t3}", RISCV::X28)
11173                                .Case("{t4}", RISCV::X29)
11174                                .Case("{t5}", RISCV::X30)
11175                                .Case("{t6}", RISCV::X31)
11176                                .Default(RISCV::NoRegister);
11177   if (XRegFromAlias != RISCV::NoRegister)
11178     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11179 
11180   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11181   // TableGen record rather than the AsmName to choose registers for InlineAsm
11182   // constraints, plus we want to match those names to the widest floating point
11183   // register type available, manually select floating point registers here.
11184   //
11185   // The second case is the ABI name of the register, so that frontends can also
11186   // use the ABI names in register constraint lists.
11187   if (Subtarget.hasStdExtF()) {
11188     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11189                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11190                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11191                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11192                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11193                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11194                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11195                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11196                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11197                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11198                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11199                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11200                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11201                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11202                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11203                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11204                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11205                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11206                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11207                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11208                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11209                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11210                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11211                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11212                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11213                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11214                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11215                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11216                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11217                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11218                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11219                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11220                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11221                         .Default(RISCV::NoRegister);
11222     if (FReg != RISCV::NoRegister) {
11223       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11224       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11225         unsigned RegNo = FReg - RISCV::F0_F;
11226         unsigned DReg = RISCV::F0_D + RegNo;
11227         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11228       }
11229       if (VT == MVT::f32 || VT == MVT::Other)
11230         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11231       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11232         unsigned RegNo = FReg - RISCV::F0_F;
11233         unsigned HReg = RISCV::F0_H + RegNo;
11234         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11235       }
11236     }
11237   }
11238 
11239   if (Subtarget.hasVInstructions()) {
11240     Register VReg = StringSwitch<Register>(Constraint.lower())
11241                         .Case("{v0}", RISCV::V0)
11242                         .Case("{v1}", RISCV::V1)
11243                         .Case("{v2}", RISCV::V2)
11244                         .Case("{v3}", RISCV::V3)
11245                         .Case("{v4}", RISCV::V4)
11246                         .Case("{v5}", RISCV::V5)
11247                         .Case("{v6}", RISCV::V6)
11248                         .Case("{v7}", RISCV::V7)
11249                         .Case("{v8}", RISCV::V8)
11250                         .Case("{v9}", RISCV::V9)
11251                         .Case("{v10}", RISCV::V10)
11252                         .Case("{v11}", RISCV::V11)
11253                         .Case("{v12}", RISCV::V12)
11254                         .Case("{v13}", RISCV::V13)
11255                         .Case("{v14}", RISCV::V14)
11256                         .Case("{v15}", RISCV::V15)
11257                         .Case("{v16}", RISCV::V16)
11258                         .Case("{v17}", RISCV::V17)
11259                         .Case("{v18}", RISCV::V18)
11260                         .Case("{v19}", RISCV::V19)
11261                         .Case("{v20}", RISCV::V20)
11262                         .Case("{v21}", RISCV::V21)
11263                         .Case("{v22}", RISCV::V22)
11264                         .Case("{v23}", RISCV::V23)
11265                         .Case("{v24}", RISCV::V24)
11266                         .Case("{v25}", RISCV::V25)
11267                         .Case("{v26}", RISCV::V26)
11268                         .Case("{v27}", RISCV::V27)
11269                         .Case("{v28}", RISCV::V28)
11270                         .Case("{v29}", RISCV::V29)
11271                         .Case("{v30}", RISCV::V30)
11272                         .Case("{v31}", RISCV::V31)
11273                         .Default(RISCV::NoRegister);
11274     if (VReg != RISCV::NoRegister) {
11275       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11276         return std::make_pair(VReg, &RISCV::VMRegClass);
11277       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11278         return std::make_pair(VReg, &RISCV::VRRegClass);
11279       for (const auto *RC :
11280            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11281         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11282           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11283           return std::make_pair(VReg, RC);
11284         }
11285       }
11286     }
11287   }
11288 
11289   std::pair<Register, const TargetRegisterClass *> Res =
11290       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11291 
11292   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11293   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11294   // Subtarget into account.
11295   if (Res.second == &RISCV::GPRF16RegClass ||
11296       Res.second == &RISCV::GPRF32RegClass ||
11297       Res.second == &RISCV::GPRF64RegClass)
11298     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11299 
11300   return Res;
11301 }
11302 
11303 unsigned
11304 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11305   // Currently only support length 1 constraints.
11306   if (ConstraintCode.size() == 1) {
11307     switch (ConstraintCode[0]) {
11308     case 'A':
11309       return InlineAsm::Constraint_A;
11310     default:
11311       break;
11312     }
11313   }
11314 
11315   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11316 }
11317 
11318 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11319     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11320     SelectionDAG &DAG) const {
11321   // Currently only support length 1 constraints.
11322   if (Constraint.length() == 1) {
11323     switch (Constraint[0]) {
11324     case 'I':
11325       // Validate & create a 12-bit signed immediate operand.
11326       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11327         uint64_t CVal = C->getSExtValue();
11328         if (isInt<12>(CVal))
11329           Ops.push_back(
11330               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11331       }
11332       return;
11333     case 'J':
11334       // Validate & create an integer zero operand.
11335       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11336         if (C->getZExtValue() == 0)
11337           Ops.push_back(
11338               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11339       return;
11340     case 'K':
11341       // Validate & create a 5-bit unsigned immediate operand.
11342       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11343         uint64_t CVal = C->getZExtValue();
11344         if (isUInt<5>(CVal))
11345           Ops.push_back(
11346               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11347       }
11348       return;
11349     case 'S':
11350       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11351         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11352                                                  GA->getValueType(0)));
11353       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11354         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11355                                                 BA->getValueType(0)));
11356       }
11357       return;
11358     default:
11359       break;
11360     }
11361   }
11362   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11363 }
11364 
11365 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11366                                                    Instruction *Inst,
11367                                                    AtomicOrdering Ord) const {
11368   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11369     return Builder.CreateFence(Ord);
11370   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11371     return Builder.CreateFence(AtomicOrdering::Release);
11372   return nullptr;
11373 }
11374 
11375 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11376                                                     Instruction *Inst,
11377                                                     AtomicOrdering Ord) const {
11378   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11379     return Builder.CreateFence(AtomicOrdering::Acquire);
11380   return nullptr;
11381 }
11382 
11383 TargetLowering::AtomicExpansionKind
11384 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11385   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11386   // point operations can't be used in an lr/sc sequence without breaking the
11387   // forward-progress guarantee.
11388   if (AI->isFloatingPointOperation())
11389     return AtomicExpansionKind::CmpXChg;
11390 
11391   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11392   if (Size == 8 || Size == 16)
11393     return AtomicExpansionKind::MaskedIntrinsic;
11394   return AtomicExpansionKind::None;
11395 }
11396 
11397 static Intrinsic::ID
11398 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11399   if (XLen == 32) {
11400     switch (BinOp) {
11401     default:
11402       llvm_unreachable("Unexpected AtomicRMW BinOp");
11403     case AtomicRMWInst::Xchg:
11404       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11405     case AtomicRMWInst::Add:
11406       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11407     case AtomicRMWInst::Sub:
11408       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11409     case AtomicRMWInst::Nand:
11410       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11411     case AtomicRMWInst::Max:
11412       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11413     case AtomicRMWInst::Min:
11414       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11415     case AtomicRMWInst::UMax:
11416       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11417     case AtomicRMWInst::UMin:
11418       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11419     }
11420   }
11421 
11422   if (XLen == 64) {
11423     switch (BinOp) {
11424     default:
11425       llvm_unreachable("Unexpected AtomicRMW BinOp");
11426     case AtomicRMWInst::Xchg:
11427       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11428     case AtomicRMWInst::Add:
11429       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11430     case AtomicRMWInst::Sub:
11431       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11432     case AtomicRMWInst::Nand:
11433       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11434     case AtomicRMWInst::Max:
11435       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11436     case AtomicRMWInst::Min:
11437       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11438     case AtomicRMWInst::UMax:
11439       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11440     case AtomicRMWInst::UMin:
11441       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11442     }
11443   }
11444 
11445   llvm_unreachable("Unexpected XLen\n");
11446 }
11447 
11448 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11449     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11450     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11451   unsigned XLen = Subtarget.getXLen();
11452   Value *Ordering =
11453       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11454   Type *Tys[] = {AlignedAddr->getType()};
11455   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11456       AI->getModule(),
11457       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11458 
11459   if (XLen == 64) {
11460     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11461     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11462     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11463   }
11464 
11465   Value *Result;
11466 
11467   // Must pass the shift amount needed to sign extend the loaded value prior
11468   // to performing a signed comparison for min/max. ShiftAmt is the number of
11469   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11470   // is the number of bits to left+right shift the value in order to
11471   // sign-extend.
11472   if (AI->getOperation() == AtomicRMWInst::Min ||
11473       AI->getOperation() == AtomicRMWInst::Max) {
11474     const DataLayout &DL = AI->getModule()->getDataLayout();
11475     unsigned ValWidth =
11476         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11477     Value *SextShamt =
11478         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11479     Result = Builder.CreateCall(LrwOpScwLoop,
11480                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11481   } else {
11482     Result =
11483         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11484   }
11485 
11486   if (XLen == 64)
11487     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11488   return Result;
11489 }
11490 
11491 TargetLowering::AtomicExpansionKind
11492 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11493     AtomicCmpXchgInst *CI) const {
11494   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11495   if (Size == 8 || Size == 16)
11496     return AtomicExpansionKind::MaskedIntrinsic;
11497   return AtomicExpansionKind::None;
11498 }
11499 
11500 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11501     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11502     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11503   unsigned XLen = Subtarget.getXLen();
11504   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11505   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11506   if (XLen == 64) {
11507     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11508     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11509     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11510     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11511   }
11512   Type *Tys[] = {AlignedAddr->getType()};
11513   Function *MaskedCmpXchg =
11514       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11515   Value *Result = Builder.CreateCall(
11516       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11517   if (XLen == 64)
11518     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11519   return Result;
11520 }
11521 
11522 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11523   return false;
11524 }
11525 
11526 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11527                                                EVT VT) const {
11528   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11529     return false;
11530 
11531   switch (FPVT.getSimpleVT().SimpleTy) {
11532   case MVT::f16:
11533     return Subtarget.hasStdExtZfh();
11534   case MVT::f32:
11535     return Subtarget.hasStdExtF();
11536   case MVT::f64:
11537     return Subtarget.hasStdExtD();
11538   default:
11539     return false;
11540   }
11541 }
11542 
11543 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11544   // If we are using the small code model, we can reduce size of jump table
11545   // entry to 4 bytes.
11546   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11547       getTargetMachine().getCodeModel() == CodeModel::Small) {
11548     return MachineJumpTableInfo::EK_Custom32;
11549   }
11550   return TargetLowering::getJumpTableEncoding();
11551 }
11552 
11553 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11554     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11555     unsigned uid, MCContext &Ctx) const {
11556   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11557          getTargetMachine().getCodeModel() == CodeModel::Small);
11558   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11559 }
11560 
11561 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11562                                                      EVT VT) const {
11563   VT = VT.getScalarType();
11564 
11565   if (!VT.isSimple())
11566     return false;
11567 
11568   switch (VT.getSimpleVT().SimpleTy) {
11569   case MVT::f16:
11570     return Subtarget.hasStdExtZfh();
11571   case MVT::f32:
11572     return Subtarget.hasStdExtF();
11573   case MVT::f64:
11574     return Subtarget.hasStdExtD();
11575   default:
11576     break;
11577   }
11578 
11579   return false;
11580 }
11581 
11582 Register RISCVTargetLowering::getExceptionPointerRegister(
11583     const Constant *PersonalityFn) const {
11584   return RISCV::X10;
11585 }
11586 
11587 Register RISCVTargetLowering::getExceptionSelectorRegister(
11588     const Constant *PersonalityFn) const {
11589   return RISCV::X11;
11590 }
11591 
11592 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11593   // Return false to suppress the unnecessary extensions if the LibCall
11594   // arguments or return value is f32 type for LP64 ABI.
11595   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11596   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11597     return false;
11598 
11599   return true;
11600 }
11601 
11602 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11603   if (Subtarget.is64Bit() && Type == MVT::i32)
11604     return true;
11605 
11606   return IsSigned;
11607 }
11608 
11609 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11610                                                  SDValue C) const {
11611   // Check integral scalar types.
11612   if (VT.isScalarInteger()) {
11613     // Omit the optimization if the sub target has the M extension and the data
11614     // size exceeds XLen.
11615     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11616       return false;
11617     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11618       // Break the MUL to a SLLI and an ADD/SUB.
11619       const APInt &Imm = ConstNode->getAPIntValue();
11620       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11621           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11622         return true;
11623       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11624       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11625           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11626            (Imm - 8).isPowerOf2()))
11627         return true;
11628       // Omit the following optimization if the sub target has the M extension
11629       // and the data size >= XLen.
11630       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11631         return false;
11632       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11633       // a pair of LUI/ADDI.
11634       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11635         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11636         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11637             (1 - ImmS).isPowerOf2())
11638         return true;
11639       }
11640     }
11641   }
11642 
11643   return false;
11644 }
11645 
11646 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11647                                                       SDValue ConstNode) const {
11648   // Let the DAGCombiner decide for vectors.
11649   EVT VT = AddNode.getValueType();
11650   if (VT.isVector())
11651     return true;
11652 
11653   // Let the DAGCombiner decide for larger types.
11654   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11655     return true;
11656 
11657   // It is worse if c1 is simm12 while c1*c2 is not.
11658   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11659   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11660   const APInt &C1 = C1Node->getAPIntValue();
11661   const APInt &C2 = C2Node->getAPIntValue();
11662   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11663     return false;
11664 
11665   // Default to true and let the DAGCombiner decide.
11666   return true;
11667 }
11668 
11669 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11670     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11671     bool *Fast) const {
11672   if (!VT.isVector())
11673     return false;
11674 
11675   EVT ElemVT = VT.getVectorElementType();
11676   if (Alignment >= ElemVT.getStoreSize()) {
11677     if (Fast)
11678       *Fast = true;
11679     return true;
11680   }
11681 
11682   return false;
11683 }
11684 
11685 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11686     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11687     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11688   bool IsABIRegCopy = CC.hasValue();
11689   EVT ValueVT = Val.getValueType();
11690   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11691     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11692     // and cast to f32.
11693     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11694     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11695     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11696                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11697     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11698     Parts[0] = Val;
11699     return true;
11700   }
11701 
11702   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11703     LLVMContext &Context = *DAG.getContext();
11704     EVT ValueEltVT = ValueVT.getVectorElementType();
11705     EVT PartEltVT = PartVT.getVectorElementType();
11706     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11707     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11708     if (PartVTBitSize % ValueVTBitSize == 0) {
11709       assert(PartVTBitSize >= ValueVTBitSize);
11710       // If the element types are different, bitcast to the same element type of
11711       // PartVT first.
11712       // Give an example here, we want copy a <vscale x 1 x i8> value to
11713       // <vscale x 4 x i16>.
11714       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11715       // subvector, then we can bitcast to <vscale x 4 x i16>.
11716       if (ValueEltVT != PartEltVT) {
11717         if (PartVTBitSize > ValueVTBitSize) {
11718           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11719           assert(Count != 0 && "The number of element should not be zero.");
11720           EVT SameEltTypeVT =
11721               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11722           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11723                             DAG.getUNDEF(SameEltTypeVT), Val,
11724                             DAG.getVectorIdxConstant(0, DL));
11725         }
11726         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11727       } else {
11728         Val =
11729             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11730                         Val, DAG.getVectorIdxConstant(0, DL));
11731       }
11732       Parts[0] = Val;
11733       return true;
11734     }
11735   }
11736   return false;
11737 }
11738 
11739 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11740     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11741     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11742   bool IsABIRegCopy = CC.hasValue();
11743   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11744     SDValue Val = Parts[0];
11745 
11746     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11747     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11748     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11749     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11750     return Val;
11751   }
11752 
11753   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11754     LLVMContext &Context = *DAG.getContext();
11755     SDValue Val = Parts[0];
11756     EVT ValueEltVT = ValueVT.getVectorElementType();
11757     EVT PartEltVT = PartVT.getVectorElementType();
11758     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11759     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11760     if (PartVTBitSize % ValueVTBitSize == 0) {
11761       assert(PartVTBitSize >= ValueVTBitSize);
11762       EVT SameEltTypeVT = ValueVT;
11763       // If the element types are different, convert it to the same element type
11764       // of PartVT.
11765       // Give an example here, we want copy a <vscale x 1 x i8> value from
11766       // <vscale x 4 x i16>.
11767       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11768       // then we can extract <vscale x 1 x i8>.
11769       if (ValueEltVT != PartEltVT) {
11770         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11771         assert(Count != 0 && "The number of element should not be zero.");
11772         SameEltTypeVT =
11773             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11774         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11775       }
11776       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11777                         DAG.getVectorIdxConstant(0, DL));
11778       return Val;
11779     }
11780   }
11781   return SDValue();
11782 }
11783 
11784 SDValue
11785 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11786                                    SelectionDAG &DAG,
11787                                    SmallVectorImpl<SDNode *> &Created) const {
11788   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11789   if (isIntDivCheap(N->getValueType(0), Attr))
11790     return SDValue(N, 0); // Lower SDIV as SDIV
11791 
11792   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11793          "Unexpected divisor!");
11794 
11795   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11796   if (!Subtarget.hasStdExtZbt())
11797     return SDValue();
11798 
11799   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11800   // Besides, more critical path instructions will be generated when dividing
11801   // by 2. So we keep using the original DAGs for these cases.
11802   unsigned Lg2 = Divisor.countTrailingZeros();
11803   if (Lg2 == 1 || Lg2 >= 12)
11804     return SDValue();
11805 
11806   // fold (sdiv X, pow2)
11807   EVT VT = N->getValueType(0);
11808   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11809     return SDValue();
11810 
11811   SDLoc DL(N);
11812   SDValue N0 = N->getOperand(0);
11813   SDValue Zero = DAG.getConstant(0, DL, VT);
11814   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11815 
11816   // Add (N0 < 0) ? Pow2 - 1 : 0;
11817   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11818   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11819   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11820 
11821   Created.push_back(Cmp.getNode());
11822   Created.push_back(Add.getNode());
11823   Created.push_back(Sel.getNode());
11824 
11825   // Divide by pow2.
11826   SDValue SRA =
11827       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11828 
11829   // If we're dividing by a positive value, we're done.  Otherwise, we must
11830   // negate the result.
11831   if (Divisor.isNonNegative())
11832     return SRA;
11833 
11834   Created.push_back(SRA.getNode());
11835   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11836 }
11837 
11838 #define GET_REGISTER_MATCHER
11839 #include "RISCVGenAsmMatcher.inc"
11840 
11841 Register
11842 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11843                                        const MachineFunction &MF) const {
11844   Register Reg = MatchRegisterAltName(RegName);
11845   if (Reg == RISCV::NoRegister)
11846     Reg = MatchRegisterName(RegName);
11847   if (Reg == RISCV::NoRegister)
11848     report_fatal_error(
11849         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11850   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11851   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11852     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11853                              StringRef(RegName) + "\"."));
11854   return Reg;
11855 }
11856 
11857 namespace llvm {
11858 namespace RISCVVIntrinsicsTable {
11859 
11860 #define GET_RISCVVIntrinsicsTable_IMPL
11861 #include "RISCVGenSearchableTables.inc"
11862 
11863 } // namespace RISCVVIntrinsicsTable
11864 
11865 } // namespace llvm
11866