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       // Disable the smallest fractional LMUL types if ELEN is less than
116       // RVVBitsPerBlock.
117       unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN();
118       if (VT.getVectorMinNumElements() < MinElts)
119         return;
120 
121       unsigned Size = VT.getSizeInBits().getKnownMinValue();
122       const TargetRegisterClass *RC;
123       if (Size <= RISCV::RVVBitsPerBlock)
124         RC = &RISCV::VRRegClass;
125       else if (Size == 2 * RISCV::RVVBitsPerBlock)
126         RC = &RISCV::VRM2RegClass;
127       else if (Size == 4 * RISCV::RVVBitsPerBlock)
128         RC = &RISCV::VRM4RegClass;
129       else if (Size == 8 * RISCV::RVVBitsPerBlock)
130         RC = &RISCV::VRM8RegClass;
131       else
132         llvm_unreachable("Unexpected size");
133 
134       addRegisterClass(VT, RC);
135     };
136 
137     for (MVT VT : BoolVecVTs)
138       addRegClassForRVV(VT);
139     for (MVT VT : IntVecVTs) {
140       if (VT.getVectorElementType() == MVT::i64 &&
141           !Subtarget.hasVInstructionsI64())
142         continue;
143       addRegClassForRVV(VT);
144     }
145 
146     if (Subtarget.hasVInstructionsF16())
147       for (MVT VT : F16VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.hasVInstructionsF32())
151       for (MVT VT : F32VecVTs)
152         addRegClassForRVV(VT);
153 
154     if (Subtarget.hasVInstructionsF64())
155       for (MVT VT : F64VecVTs)
156         addRegClassForRVV(VT);
157 
158     if (Subtarget.useRVVForFixedLengthVectors()) {
159       auto addRegClassForFixedVectors = [this](MVT VT) {
160         MVT ContainerVT = getContainerForFixedLengthVector(VT);
161         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
162         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
163         addRegisterClass(VT, TRI.getRegClass(RCID));
164       };
165       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
166         if (useRVVForFixedLengthVectorVT(VT))
167           addRegClassForFixedVectors(VT);
168 
169       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
170         if (useRVVForFixedLengthVectorVT(VT))
171           addRegClassForFixedVectors(VT);
172     }
173   }
174 
175   // Compute derived properties from the register classes.
176   computeRegisterProperties(STI.getRegisterInfo());
177 
178   setStackPointerRegisterToSaveRestore(RISCV::X2);
179 
180   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
181                    MVT::i1, Promote);
182 
183   // TODO: add all necessary setOperationAction calls.
184   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
185 
186   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187   setOperationAction(ISD::BR_CC, XLenVT, Expand);
188   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
189   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
190 
191   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
192 
193   setOperationAction(ISD::VASTART, MVT::Other, Custom);
194   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
195 
196   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
197 
198   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
199 
200   if (!Subtarget.hasStdExtZbb())
201     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
202 
203   if (Subtarget.is64Bit()) {
204     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
205 
206     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
207                        MVT::i32, Custom);
208 
209     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
210                        MVT::i32, Custom);
211   } else {
212     setLibcallName(
213         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
214         nullptr);
215     setLibcallName(RTLIB::MULO_I64, nullptr);
216   }
217 
218   if (!Subtarget.hasStdExtM()) {
219     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
220                         ISD::SREM, ISD::UREM},
221                        XLenVT, Expand);
222   } else {
223     if (Subtarget.is64Bit()) {
224       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
225 
226       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
227                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
228     } else {
229       setOperationAction(ISD::MUL, MVT::i64, Custom);
230     }
231   }
232 
233   setOperationAction(
234       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
235       Expand);
236 
237   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
238                      Custom);
239 
240   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
241       Subtarget.hasStdExtZbkb()) {
242     if (Subtarget.is64Bit())
243       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
244   } else {
245     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
246   }
247 
248   if (Subtarget.hasStdExtZbp()) {
249     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
250     // more combining.
251     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
252 
253     // BSWAP i8 doesn't exist.
254     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
255 
256     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
257 
258     if (Subtarget.is64Bit())
259       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
260   } else {
261     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
262     // pattern match it directly in isel.
263     setOperationAction(ISD::BSWAP, XLenVT,
264                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
265                            ? Legal
266                            : Expand);
267     // Zbkb can use rev8+brev8 to implement bitreverse.
268     setOperationAction(ISD::BITREVERSE, XLenVT,
269                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
270   }
271 
272   if (Subtarget.hasStdExtZbb()) {
273     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
274                        Legal);
275 
276     if (Subtarget.is64Bit())
277       setOperationAction(
278           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
279           MVT::i32, Custom);
280   } else {
281     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
282 
283     if (Subtarget.is64Bit())
284       setOperationAction(ISD::ABS, MVT::i32, Custom);
285   }
286 
287   if (Subtarget.hasStdExtZbt()) {
288     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
289     setOperationAction(ISD::SELECT, XLenVT, Legal);
290 
291     if (Subtarget.is64Bit())
292       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
293   } else {
294     setOperationAction(ISD::SELECT, XLenVT, Custom);
295   }
296 
297   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
298       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
299       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
300       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
301       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
302       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
303       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
304 
305   static const ISD::CondCode FPCCToExpand[] = {
306       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
307       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
308       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
309 
310   static const ISD::NodeType FPOpToExpand[] = {
311       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
312       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
313 
314   if (Subtarget.hasStdExtZfh())
315     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
316 
317   if (Subtarget.hasStdExtZfh()) {
318     for (auto NT : FPLegalNodeTypes)
319       setOperationAction(NT, MVT::f16, Legal);
320     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
321     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
322     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
323     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
324     setOperationAction(ISD::SELECT, MVT::f16, Custom);
325     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
326 
327     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
328                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
329                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
330                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
331                         ISD::FLOG2, ISD::FLOG10},
332                        MVT::f16, Promote);
333 
334     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
335     // complete support for all operations in LegalizeDAG.
336 
337     // We need to custom promote this.
338     if (Subtarget.is64Bit())
339       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
340   }
341 
342   if (Subtarget.hasStdExtF()) {
343     for (auto NT : FPLegalNodeTypes)
344       setOperationAction(NT, MVT::f32, Legal);
345     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
346     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
347     setOperationAction(ISD::SELECT, MVT::f32, Custom);
348     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
349     for (auto Op : FPOpToExpand)
350       setOperationAction(Op, MVT::f32, Expand);
351     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
352     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
353   }
354 
355   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
356     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
357 
358   if (Subtarget.hasStdExtD()) {
359     for (auto NT : FPLegalNodeTypes)
360       setOperationAction(NT, MVT::f64, Legal);
361     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
362     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
363     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
364     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
365     setOperationAction(ISD::SELECT, MVT::f64, Custom);
366     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
367     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
368     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
369     for (auto Op : FPOpToExpand)
370       setOperationAction(Op, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373   }
374 
375   if (Subtarget.is64Bit())
376     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
377                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
378                        MVT::i32, Custom);
379 
380   if (Subtarget.hasStdExtF()) {
381     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
382                        Custom);
383 
384     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
385                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
386                        XLenVT, Legal);
387 
388     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
389     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
390   }
391 
392   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
393                       ISD::JumpTable},
394                      XLenVT, Custom);
395 
396   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
397 
398   if (Subtarget.is64Bit())
399     setOperationAction(ISD::Constant, MVT::i64, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408   if (Subtarget.is64Bit())
409     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
410 
411   if (Subtarget.hasStdExtA()) {
412     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
413     setMinCmpXchgSizeInBits(32);
414   } else {
415     setMaxAtomicSizeInBitsSupported(0);
416   }
417 
418   setBooleanContents(ZeroOrOneBooleanContent);
419 
420   if (Subtarget.hasVInstructions()) {
421     setBooleanVectorContents(ZeroOrOneBooleanContent);
422 
423     setOperationAction(ISD::VSCALE, XLenVT, Custom);
424 
425     // RVV intrinsics may have illegal operands.
426     // We also need to custom legalize vmv.x.s.
427     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
428                        {MVT::i8, MVT::i16}, Custom);
429     if (Subtarget.is64Bit())
430       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
431     else
432       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
433                          MVT::i64, Custom);
434 
435     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
436                        MVT::Other, Custom);
437 
438     static const unsigned IntegerVPOps[] = {
439         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
440         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
441         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
442         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
443         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
444         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
445         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
446         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
447         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
448         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
449 
450     static const unsigned FloatingPointVPOps[] = {
451         ISD::VP_FADD,        ISD::VP_FSUB,
452         ISD::VP_FMUL,        ISD::VP_FDIV,
453         ISD::VP_FNEG,        ISD::VP_FMA,
454         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
455         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
456         ISD::VP_MERGE,       ISD::VP_SELECT,
457         ISD::VP_SITOFP,      ISD::VP_UITOFP,
458         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
459         ISD::VP_FP_EXTEND};
460 
461     if (!Subtarget.is64Bit()) {
462       // We must custom-lower certain vXi64 operations on RV32 due to the vector
463       // element type being illegal.
464       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
465                          MVT::i64, Custom);
466 
467       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
468                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
469                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
470                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
471                          MVT::i64, Custom);
472 
473       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
474                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
475                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
476                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
477                          MVT::i64, Custom);
478     }
479 
480     for (MVT VT : BoolVecVTs) {
481       if (!isTypeLegal(VT))
482         continue;
483 
484       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
485 
486       // Mask VTs are custom-expanded into a series of standard nodes
487       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
488                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
489                          VT, Custom);
490 
491       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
492                          Custom);
493 
494       setOperationAction(ISD::SELECT, VT, Custom);
495       setOperationAction(
496           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
497           Expand);
498 
499       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
500 
501       setOperationAction(
502           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
503           Custom);
504 
505       setOperationAction(
506           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
507           Custom);
508 
509       // RVV has native int->float & float->int conversions where the
510       // element type sizes are within one power-of-two of each other. Any
511       // wider distances between type sizes have to be lowered as sequences
512       // which progressively narrow the gap in stages.
513       setOperationAction(
514           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
515           VT, Custom);
516 
517       // Expand all extending loads to types larger than this, and truncating
518       // stores from types larger than this.
519       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
520         setTruncStoreAction(OtherVT, VT, Expand);
521         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
522                          VT, Expand);
523       }
524 
525       setOperationAction(
526           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
527           Custom);
528       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
529     }
530 
531     for (MVT VT : IntVecVTs) {
532       if (!isTypeLegal(VT))
533         continue;
534 
535       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
536       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
537 
538       // Vectors implement MULHS/MULHU.
539       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
540 
541       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
542       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
543         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
544 
545       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
546                          Legal);
547 
548       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
549 
550       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
551                          Expand);
552 
553       setOperationAction(ISD::BSWAP, VT, Expand);
554 
555       // Custom-lower extensions and truncations from/to mask types.
556       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
557                          VT, Custom);
558 
559       // RVV has native int->float & float->int conversions where the
560       // element type sizes are within one power-of-two of each other. Any
561       // wider distances between type sizes have to be lowered as sequences
562       // which progressively narrow the gap in stages.
563       setOperationAction(
564           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
565           VT, Custom);
566 
567       setOperationAction(
568           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
569 
570       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
571       // nodes which truncate by one power of two at a time.
572       setOperationAction(ISD::TRUNCATE, VT, Custom);
573 
574       // Custom-lower insert/extract operations to simplify patterns.
575       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
576                          Custom);
577 
578       // Custom-lower reduction operations to set up the corresponding custom
579       // nodes' operands.
580       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
581                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
582                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
583                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
584                          VT, Custom);
585 
586       setOperationAction(IntegerVPOps, VT, Custom);
587 
588       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
589 
590       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
591                          VT, Custom);
592 
593       setOperationAction(
594           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
595           Custom);
596 
597       setOperationAction(
598           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
599           VT, Custom);
600 
601       setOperationAction(ISD::SELECT, VT, Custom);
602       setOperationAction(ISD::SELECT_CC, VT, Expand);
603 
604       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
605 
606       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
607         setTruncStoreAction(VT, OtherVT, Expand);
608         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
609                          VT, Expand);
610       }
611 
612       // Splice
613       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
614 
615       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
616       // type that can represent the value exactly.
617       if (VT.getVectorElementType() != MVT::i64) {
618         MVT FloatEltVT =
619             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
620         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
621         if (isTypeLegal(FloatVT)) {
622           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
623                              Custom);
624         }
625       }
626     }
627 
628     // Expand various CCs to best match the RVV ISA, which natively supports UNE
629     // but no other unordered comparisons, and supports all ordered comparisons
630     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
631     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
632     // and we pattern-match those back to the "original", swapping operands once
633     // more. This way we catch both operations and both "vf" and "fv" forms with
634     // fewer patterns.
635     static const ISD::CondCode VFPCCToExpand[] = {
636         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
637         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
638         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
639     };
640 
641     // Sets common operation actions on RVV floating-point vector types.
642     const auto SetCommonVFPActions = [&](MVT VT) {
643       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
644       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
645       // sizes are within one power-of-two of each other. Therefore conversions
646       // between vXf16 and vXf64 must be lowered as sequences which convert via
647       // vXf32.
648       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
649       // Custom-lower insert/extract operations to simplify patterns.
650       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
651                          Custom);
652       // Expand various condition codes (explained above).
653       setCondCodeAction(VFPCCToExpand, VT, Expand);
654 
655       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
656 
657       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
658                          VT, Custom);
659 
660       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
661                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
662                          VT, Custom);
663 
664       // Expand FP operations that need libcalls.
665       setOperationAction(ISD::FREM, VT, Expand);
666       setOperationAction(ISD::FPOW, VT, Expand);
667       setOperationAction(ISD::FCOS, VT, Expand);
668       setOperationAction(ISD::FSIN, VT, Expand);
669       setOperationAction(ISD::FSINCOS, VT, Expand);
670       setOperationAction(ISD::FEXP, VT, Expand);
671       setOperationAction(ISD::FEXP2, VT, Expand);
672       setOperationAction(ISD::FLOG, VT, Expand);
673       setOperationAction(ISD::FLOG2, VT, Expand);
674       setOperationAction(ISD::FLOG10, VT, Expand);
675       setOperationAction(ISD::FRINT, VT, Expand);
676       setOperationAction(ISD::FNEARBYINT, VT, Expand);
677 
678       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
679       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
680       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
681       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
682 
683       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
684 
685       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
686 
687       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
688                          VT, Custom);
689 
690       setOperationAction(
691           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
692           Custom);
693 
694       setOperationAction(ISD::SELECT, VT, Custom);
695       setOperationAction(ISD::SELECT_CC, VT, Expand);
696 
697       setOperationAction(
698           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
699           VT, Custom);
700 
701       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
702 
703       setOperationAction(FloatingPointVPOps, VT, Custom);
704     };
705 
706     // Sets common extload/truncstore actions on RVV floating-point vector
707     // types.
708     const auto SetCommonVFPExtLoadTruncStoreActions =
709         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
710           for (auto SmallVT : SmallerVTs) {
711             setTruncStoreAction(VT, SmallVT, Expand);
712             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
713           }
714         };
715 
716     if (Subtarget.hasVInstructionsF16()) {
717       for (MVT VT : F16VecVTs) {
718         if (!isTypeLegal(VT))
719           continue;
720         SetCommonVFPActions(VT);
721       }
722     }
723 
724     if (Subtarget.hasVInstructionsF32()) {
725       for (MVT VT : F32VecVTs) {
726         if (!isTypeLegal(VT))
727           continue;
728         SetCommonVFPActions(VT);
729         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
730       }
731     }
732 
733     if (Subtarget.hasVInstructionsF64()) {
734       for (MVT VT : F64VecVTs) {
735         if (!isTypeLegal(VT))
736           continue;
737         SetCommonVFPActions(VT);
738         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
739         SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
740       }
741     }
742 
743     if (Subtarget.useRVVForFixedLengthVectors()) {
744       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
745         if (!useRVVForFixedLengthVectorVT(VT))
746           continue;
747 
748         // By default everything must be expanded.
749         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
750           setOperationAction(Op, VT, Expand);
751         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
752           setTruncStoreAction(VT, OtherVT, Expand);
753           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
754                            OtherVT, VT, Expand);
755         }
756 
757         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
758         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
759                            Custom);
760 
761         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
762                            Custom);
763 
764         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
765                            VT, Custom);
766 
767         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
768 
769         setOperationAction(ISD::SETCC, VT, Custom);
770 
771         setOperationAction(ISD::SELECT, VT, Custom);
772 
773         setOperationAction(ISD::TRUNCATE, VT, Custom);
774 
775         setOperationAction(ISD::BITCAST, VT, Custom);
776 
777         setOperationAction(
778             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
779             Custom);
780 
781         setOperationAction(
782             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
783             Custom);
784 
785         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
786                             ISD::FP_TO_UINT},
787                            VT, Custom);
788 
789         // Operations below are different for between masks and other vectors.
790         if (VT.getVectorElementType() == MVT::i1) {
791           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
792                               ISD::OR, ISD::XOR},
793                              VT, Custom);
794 
795           setOperationAction(
796               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
797               VT, Custom);
798           continue;
799         }
800 
801         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
802         // it before type legalization for i64 vectors on RV32. It will then be
803         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
804         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
805         // improvements first.
806         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
807           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
808           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
809         }
810 
811         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
812         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
813 
814         setOperationAction(
815             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
816 
817         setOperationAction(
818             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
819             Custom);
820 
821         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
822                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
823                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
824                            VT, Custom);
825 
826         setOperationAction(
827             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
828 
829         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
830         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
831           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
832 
833         setOperationAction(
834             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
835             Custom);
836 
837         setOperationAction(ISD::VSELECT, VT, Custom);
838         setOperationAction(ISD::SELECT_CC, VT, Expand);
839 
840         setOperationAction(
841             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
842 
843         // Custom-lower reduction operations to set up the corresponding custom
844         // nodes' operands.
845         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
846                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
847                             ISD::VECREDUCE_UMIN},
848                            VT, Custom);
849 
850         setOperationAction(IntegerVPOps, VT, Custom);
851 
852         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
853         // type that can represent the value exactly.
854         if (VT.getVectorElementType() != MVT::i64) {
855           MVT FloatEltVT =
856               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
857           EVT FloatVT =
858               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
859           if (isTypeLegal(FloatVT))
860             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
861                                Custom);
862         }
863       }
864 
865       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
866         if (!useRVVForFixedLengthVectorVT(VT))
867           continue;
868 
869         // By default everything must be expanded.
870         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
871           setOperationAction(Op, VT, Expand);
872         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
873           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
874           setTruncStoreAction(VT, OtherVT, Expand);
875         }
876 
877         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
878         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
879                            Custom);
880 
881         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
882                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
883                             ISD::EXTRACT_VECTOR_ELT},
884                            VT, Custom);
885 
886         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
887                             ISD::MGATHER, ISD::MSCATTER},
888                            VT, Custom);
889 
890         setOperationAction(
891             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
892             Custom);
893 
894         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
895                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
896                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
897                            VT, Custom);
898 
899         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
900 
901         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
902                            VT, Custom);
903 
904         for (auto CC : VFPCCToExpand)
905           setCondCodeAction(CC, VT, Expand);
906 
907         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
908         setOperationAction(ISD::SELECT_CC, VT, Expand);
909 
910         setOperationAction(ISD::BITCAST, VT, Custom);
911 
912         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
913                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
914                            VT, Custom);
915 
916         setOperationAction(FloatingPointVPOps, VT, Custom);
917       }
918 
919       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
920       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
921                          Custom);
922       if (Subtarget.hasStdExtZfh())
923         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
924       if (Subtarget.hasStdExtF())
925         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
926       if (Subtarget.hasStdExtD())
927         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
928     }
929   }
930 
931   // Function alignments.
932   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
933   setMinFunctionAlignment(FunctionAlignment);
934   setPrefFunctionAlignment(FunctionAlignment);
935 
936   setMinimumJumpTableEntries(5);
937 
938   // Jumps are expensive, compared to logic
939   setJumpIsExpensive();
940 
941   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
942                        ISD::OR, ISD::XOR});
943 
944   if (Subtarget.hasStdExtF())
945     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
946 
947   if (Subtarget.hasStdExtZbp())
948     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
949 
950   if (Subtarget.hasStdExtZbb())
951     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
952 
953   if (Subtarget.hasStdExtZbkb())
954     setTargetDAGCombine(ISD::BITREVERSE);
955   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
956     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
957   if (Subtarget.hasStdExtF())
958     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
959                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
960   if (Subtarget.hasVInstructions())
961     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
962                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
963                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
964   if (Subtarget.useRVVForFixedLengthVectors())
965     setTargetDAGCombine(ISD::BITCAST);
966 
967   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
968   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
969 }
970 
971 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
972                                             LLVMContext &Context,
973                                             EVT VT) const {
974   if (!VT.isVector())
975     return getPointerTy(DL);
976   if (Subtarget.hasVInstructions() &&
977       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
978     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
979   return VT.changeVectorElementTypeToInteger();
980 }
981 
982 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
983   return Subtarget.getXLenVT();
984 }
985 
986 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
987                                              const CallInst &I,
988                                              MachineFunction &MF,
989                                              unsigned Intrinsic) const {
990   auto &DL = I.getModule()->getDataLayout();
991   switch (Intrinsic) {
992   default:
993     return false;
994   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
995   case Intrinsic::riscv_masked_atomicrmw_add_i32:
996   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
997   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
998   case Intrinsic::riscv_masked_atomicrmw_max_i32:
999   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1000   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1001   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1002   case Intrinsic::riscv_masked_cmpxchg_i32:
1003     Info.opc = ISD::INTRINSIC_W_CHAIN;
1004     Info.memVT = MVT::i32;
1005     Info.ptrVal = I.getArgOperand(0);
1006     Info.offset = 0;
1007     Info.align = Align(4);
1008     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1009                  MachineMemOperand::MOVolatile;
1010     return true;
1011   case Intrinsic::riscv_masked_strided_load:
1012     Info.opc = ISD::INTRINSIC_W_CHAIN;
1013     Info.ptrVal = I.getArgOperand(1);
1014     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1015     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1016     Info.size = MemoryLocation::UnknownSize;
1017     Info.flags |= MachineMemOperand::MOLoad;
1018     return true;
1019   case Intrinsic::riscv_masked_strided_store:
1020     Info.opc = ISD::INTRINSIC_VOID;
1021     Info.ptrVal = I.getArgOperand(1);
1022     Info.memVT =
1023         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1024     Info.align = Align(
1025         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1026         8);
1027     Info.size = MemoryLocation::UnknownSize;
1028     Info.flags |= MachineMemOperand::MOStore;
1029     return true;
1030   case Intrinsic::riscv_seg2_load:
1031   case Intrinsic::riscv_seg3_load:
1032   case Intrinsic::riscv_seg4_load:
1033   case Intrinsic::riscv_seg5_load:
1034   case Intrinsic::riscv_seg6_load:
1035   case Intrinsic::riscv_seg7_load:
1036   case Intrinsic::riscv_seg8_load:
1037     Info.opc = ISD::INTRINSIC_W_CHAIN;
1038     Info.ptrVal = I.getArgOperand(0);
1039     Info.memVT =
1040         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1041     Info.align =
1042         Align(DL.getTypeSizeInBits(
1043                   I.getType()->getStructElementType(0)->getScalarType()) /
1044               8);
1045     Info.size = MemoryLocation::UnknownSize;
1046     Info.flags |= MachineMemOperand::MOLoad;
1047     return true;
1048   }
1049 }
1050 
1051 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1052                                                 const AddrMode &AM, Type *Ty,
1053                                                 unsigned AS,
1054                                                 Instruction *I) const {
1055   // No global is ever allowed as a base.
1056   if (AM.BaseGV)
1057     return false;
1058 
1059   // RVV instructions only support register addressing.
1060   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1061     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1062 
1063   // Require a 12-bit signed offset.
1064   if (!isInt<12>(AM.BaseOffs))
1065     return false;
1066 
1067   switch (AM.Scale) {
1068   case 0: // "r+i" or just "i", depending on HasBaseReg.
1069     break;
1070   case 1:
1071     if (!AM.HasBaseReg) // allow "r+i".
1072       break;
1073     return false; // disallow "r+r" or "r+r+i".
1074   default:
1075     return false;
1076   }
1077 
1078   return true;
1079 }
1080 
1081 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1082   return isInt<12>(Imm);
1083 }
1084 
1085 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1086   return isInt<12>(Imm);
1087 }
1088 
1089 // On RV32, 64-bit integers are split into their high and low parts and held
1090 // in two different registers, so the trunc is free since the low register can
1091 // just be used.
1092 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1093   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1094     return false;
1095   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1096   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1097   return (SrcBits == 64 && DestBits == 32);
1098 }
1099 
1100 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1101   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1102       !SrcVT.isInteger() || !DstVT.isInteger())
1103     return false;
1104   unsigned SrcBits = SrcVT.getSizeInBits();
1105   unsigned DestBits = DstVT.getSizeInBits();
1106   return (SrcBits == 64 && DestBits == 32);
1107 }
1108 
1109 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1110   // Zexts are free if they can be combined with a load.
1111   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1112   // poorly with type legalization of compares preferring sext.
1113   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1114     EVT MemVT = LD->getMemoryVT();
1115     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1116         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1117          LD->getExtensionType() == ISD::ZEXTLOAD))
1118       return true;
1119   }
1120 
1121   return TargetLowering::isZExtFree(Val, VT2);
1122 }
1123 
1124 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1125   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1126 }
1127 
1128 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1129   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1130 }
1131 
1132 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1133   return Subtarget.hasStdExtZbb();
1134 }
1135 
1136 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1137   return Subtarget.hasStdExtZbb();
1138 }
1139 
1140 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1141   EVT VT = Y.getValueType();
1142 
1143   // FIXME: Support vectors once we have tests.
1144   if (VT.isVector())
1145     return false;
1146 
1147   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1148           Subtarget.hasStdExtZbkb()) &&
1149          !isa<ConstantSDNode>(Y);
1150 }
1151 
1152 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1153   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1154   auto *C = dyn_cast<ConstantSDNode>(Y);
1155   return C && C->getAPIntValue().ule(10);
1156 }
1157 
1158 bool RISCVTargetLowering::
1159     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1160         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1161         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1162         SelectionDAG &DAG) const {
1163   // One interesting pattern that we'd want to form is 'bit extract':
1164   //   ((1 >> Y) & 1) ==/!= 0
1165   // But we also need to be careful not to try to reverse that fold.
1166 
1167   // Is this '((1 >> Y) & 1)'?
1168   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1169     return false; // Keep the 'bit extract' pattern.
1170 
1171   // Will this be '((1 >> Y) & 1)' after the transform?
1172   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1173     return true; // Do form the 'bit extract' pattern.
1174 
1175   // If 'X' is a constant, and we transform, then we will immediately
1176   // try to undo the fold, thus causing endless combine loop.
1177   // So only do the transform if X is not a constant. This matches the default
1178   // implementation of this function.
1179   return !XC;
1180 }
1181 
1182 /// Check if sinking \p I's operands to I's basic block is profitable, because
1183 /// the operands can be folded into a target instruction, e.g.
1184 /// splats of scalars can fold into vector instructions.
1185 bool RISCVTargetLowering::shouldSinkOperands(
1186     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1187   using namespace llvm::PatternMatch;
1188 
1189   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1190     return false;
1191 
1192   auto IsSinker = [&](Instruction *I, int Operand) {
1193     switch (I->getOpcode()) {
1194     case Instruction::Add:
1195     case Instruction::Sub:
1196     case Instruction::Mul:
1197     case Instruction::And:
1198     case Instruction::Or:
1199     case Instruction::Xor:
1200     case Instruction::FAdd:
1201     case Instruction::FSub:
1202     case Instruction::FMul:
1203     case Instruction::FDiv:
1204     case Instruction::ICmp:
1205     case Instruction::FCmp:
1206       return true;
1207     case Instruction::Shl:
1208     case Instruction::LShr:
1209     case Instruction::AShr:
1210     case Instruction::UDiv:
1211     case Instruction::SDiv:
1212     case Instruction::URem:
1213     case Instruction::SRem:
1214       return Operand == 1;
1215     case Instruction::Call:
1216       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1217         switch (II->getIntrinsicID()) {
1218         case Intrinsic::fma:
1219         case Intrinsic::vp_fma:
1220           return Operand == 0 || Operand == 1;
1221         // FIXME: Our patterns can only match vx/vf instructions when the splat
1222         // it on the RHS, because TableGen doesn't recognize our VP operations
1223         // as commutative.
1224         case Intrinsic::vp_add:
1225         case Intrinsic::vp_mul:
1226         case Intrinsic::vp_and:
1227         case Intrinsic::vp_or:
1228         case Intrinsic::vp_xor:
1229         case Intrinsic::vp_fadd:
1230         case Intrinsic::vp_fmul:
1231         case Intrinsic::vp_shl:
1232         case Intrinsic::vp_lshr:
1233         case Intrinsic::vp_ashr:
1234         case Intrinsic::vp_udiv:
1235         case Intrinsic::vp_sdiv:
1236         case Intrinsic::vp_urem:
1237         case Intrinsic::vp_srem:
1238           return Operand == 1;
1239         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1240         // explicit patterns for both LHS and RHS (as 'vr' versions).
1241         case Intrinsic::vp_sub:
1242         case Intrinsic::vp_fsub:
1243         case Intrinsic::vp_fdiv:
1244           return Operand == 0 || Operand == 1;
1245         default:
1246           return false;
1247         }
1248       }
1249       return false;
1250     default:
1251       return false;
1252     }
1253   };
1254 
1255   for (auto OpIdx : enumerate(I->operands())) {
1256     if (!IsSinker(I, OpIdx.index()))
1257       continue;
1258 
1259     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1260     // Make sure we are not already sinking this operand
1261     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1262       continue;
1263 
1264     // We are looking for a splat that can be sunk.
1265     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1266                              m_Undef(), m_ZeroMask())))
1267       continue;
1268 
1269     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1270     // and vector registers
1271     for (Use &U : Op->uses()) {
1272       Instruction *Insn = cast<Instruction>(U.getUser());
1273       if (!IsSinker(Insn, U.getOperandNo()))
1274         return false;
1275     }
1276 
1277     Ops.push_back(&Op->getOperandUse(0));
1278     Ops.push_back(&OpIdx.value());
1279   }
1280   return true;
1281 }
1282 
1283 bool RISCVTargetLowering::isOffsetFoldingLegal(
1284     const GlobalAddressSDNode *GA) const {
1285   // In order to maximise the opportunity for common subexpression elimination,
1286   // keep a separate ADD node for the global address offset instead of folding
1287   // it in the global address node. Later peephole optimisations may choose to
1288   // fold it back in when profitable.
1289   return false;
1290 }
1291 
1292 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1293                                        bool ForCodeSize) const {
1294   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1295   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1296     return false;
1297   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1298     return false;
1299   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1300     return false;
1301   return Imm.isZero();
1302 }
1303 
1304 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1305   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1306          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1307          (VT == MVT::f64 && Subtarget.hasStdExtD());
1308 }
1309 
1310 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1311                                                       CallingConv::ID CC,
1312                                                       EVT VT) const {
1313   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1314   // We might still end up using a GPR but that will be decided based on ABI.
1315   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1316   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1317     return MVT::f32;
1318 
1319   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1320 }
1321 
1322 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1323                                                            CallingConv::ID CC,
1324                                                            EVT VT) const {
1325   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1326   // We might still end up using a GPR but that will be decided based on ABI.
1327   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1328   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1329     return 1;
1330 
1331   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1332 }
1333 
1334 // Changes the condition code and swaps operands if necessary, so the SetCC
1335 // operation matches one of the comparisons supported directly by branches
1336 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1337 // with 1/-1.
1338 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1339                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1340   // Convert X > -1 to X >= 0.
1341   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1342     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1343     CC = ISD::SETGE;
1344     return;
1345   }
1346   // Convert X < 1 to 0 >= X.
1347   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1348     RHS = LHS;
1349     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1350     CC = ISD::SETGE;
1351     return;
1352   }
1353 
1354   switch (CC) {
1355   default:
1356     break;
1357   case ISD::SETGT:
1358   case ISD::SETLE:
1359   case ISD::SETUGT:
1360   case ISD::SETULE:
1361     CC = ISD::getSetCCSwappedOperands(CC);
1362     std::swap(LHS, RHS);
1363     break;
1364   }
1365 }
1366 
1367 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1368   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1369   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1370   if (VT.getVectorElementType() == MVT::i1)
1371     KnownSize *= 8;
1372 
1373   switch (KnownSize) {
1374   default:
1375     llvm_unreachable("Invalid LMUL.");
1376   case 8:
1377     return RISCVII::VLMUL::LMUL_F8;
1378   case 16:
1379     return RISCVII::VLMUL::LMUL_F4;
1380   case 32:
1381     return RISCVII::VLMUL::LMUL_F2;
1382   case 64:
1383     return RISCVII::VLMUL::LMUL_1;
1384   case 128:
1385     return RISCVII::VLMUL::LMUL_2;
1386   case 256:
1387     return RISCVII::VLMUL::LMUL_4;
1388   case 512:
1389     return RISCVII::VLMUL::LMUL_8;
1390   }
1391 }
1392 
1393 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1394   switch (LMul) {
1395   default:
1396     llvm_unreachable("Invalid LMUL.");
1397   case RISCVII::VLMUL::LMUL_F8:
1398   case RISCVII::VLMUL::LMUL_F4:
1399   case RISCVII::VLMUL::LMUL_F2:
1400   case RISCVII::VLMUL::LMUL_1:
1401     return RISCV::VRRegClassID;
1402   case RISCVII::VLMUL::LMUL_2:
1403     return RISCV::VRM2RegClassID;
1404   case RISCVII::VLMUL::LMUL_4:
1405     return RISCV::VRM4RegClassID;
1406   case RISCVII::VLMUL::LMUL_8:
1407     return RISCV::VRM8RegClassID;
1408   }
1409 }
1410 
1411 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1412   RISCVII::VLMUL LMUL = getLMUL(VT);
1413   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1414       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1415       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1416       LMUL == RISCVII::VLMUL::LMUL_1) {
1417     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1418                   "Unexpected subreg numbering");
1419     return RISCV::sub_vrm1_0 + Index;
1420   }
1421   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1422     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1423                   "Unexpected subreg numbering");
1424     return RISCV::sub_vrm2_0 + Index;
1425   }
1426   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1427     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1428                   "Unexpected subreg numbering");
1429     return RISCV::sub_vrm4_0 + Index;
1430   }
1431   llvm_unreachable("Invalid vector type.");
1432 }
1433 
1434 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1435   if (VT.getVectorElementType() == MVT::i1)
1436     return RISCV::VRRegClassID;
1437   return getRegClassIDForLMUL(getLMUL(VT));
1438 }
1439 
1440 // Attempt to decompose a subvector insert/extract between VecVT and
1441 // SubVecVT via subregister indices. Returns the subregister index that
1442 // can perform the subvector insert/extract with the given element index, as
1443 // well as the index corresponding to any leftover subvectors that must be
1444 // further inserted/extracted within the register class for SubVecVT.
1445 std::pair<unsigned, unsigned>
1446 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1447     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1448     const RISCVRegisterInfo *TRI) {
1449   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1450                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1451                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1452                 "Register classes not ordered");
1453   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1454   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1455   // Try to compose a subregister index that takes us from the incoming
1456   // LMUL>1 register class down to the outgoing one. At each step we half
1457   // the LMUL:
1458   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1459   // Note that this is not guaranteed to find a subregister index, such as
1460   // when we are extracting from one VR type to another.
1461   unsigned SubRegIdx = RISCV::NoSubRegister;
1462   for (const unsigned RCID :
1463        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1464     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1465       VecVT = VecVT.getHalfNumVectorElementsVT();
1466       bool IsHi =
1467           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1468       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1469                                             getSubregIndexByMVT(VecVT, IsHi));
1470       if (IsHi)
1471         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1472     }
1473   return {SubRegIdx, InsertExtractIdx};
1474 }
1475 
1476 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1477 // stores for those types.
1478 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1479   return !Subtarget.useRVVForFixedLengthVectors() ||
1480          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1481 }
1482 
1483 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1484   if (ScalarTy->isPointerTy())
1485     return true;
1486 
1487   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1488       ScalarTy->isIntegerTy(32))
1489     return true;
1490 
1491   if (ScalarTy->isIntegerTy(64))
1492     return Subtarget.hasVInstructionsI64();
1493 
1494   if (ScalarTy->isHalfTy())
1495     return Subtarget.hasVInstructionsF16();
1496   if (ScalarTy->isFloatTy())
1497     return Subtarget.hasVInstructionsF32();
1498   if (ScalarTy->isDoubleTy())
1499     return Subtarget.hasVInstructionsF64();
1500 
1501   return false;
1502 }
1503 
1504 static SDValue getVLOperand(SDValue Op) {
1505   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1506           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1507          "Unexpected opcode");
1508   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1509   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1510   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1511       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1512   if (!II)
1513     return SDValue();
1514   return Op.getOperand(II->VLOperand + 1 + HasChain);
1515 }
1516 
1517 static bool useRVVForFixedLengthVectorVT(MVT VT,
1518                                          const RISCVSubtarget &Subtarget) {
1519   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1520   if (!Subtarget.useRVVForFixedLengthVectors())
1521     return false;
1522 
1523   // We only support a set of vector types with a consistent maximum fixed size
1524   // across all supported vector element types to avoid legalization issues.
1525   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1526   // fixed-length vector type we support is 1024 bytes.
1527   if (VT.getFixedSizeInBits() > 1024 * 8)
1528     return false;
1529 
1530   unsigned MinVLen = Subtarget.getRealMinVLen();
1531 
1532   MVT EltVT = VT.getVectorElementType();
1533 
1534   // Don't use RVV for vectors we cannot scalarize if required.
1535   switch (EltVT.SimpleTy) {
1536   // i1 is supported but has different rules.
1537   default:
1538     return false;
1539   case MVT::i1:
1540     // Masks can only use a single register.
1541     if (VT.getVectorNumElements() > MinVLen)
1542       return false;
1543     MinVLen /= 8;
1544     break;
1545   case MVT::i8:
1546   case MVT::i16:
1547   case MVT::i32:
1548     break;
1549   case MVT::i64:
1550     if (!Subtarget.hasVInstructionsI64())
1551       return false;
1552     break;
1553   case MVT::f16:
1554     if (!Subtarget.hasVInstructionsF16())
1555       return false;
1556     break;
1557   case MVT::f32:
1558     if (!Subtarget.hasVInstructionsF32())
1559       return false;
1560     break;
1561   case MVT::f64:
1562     if (!Subtarget.hasVInstructionsF64())
1563       return false;
1564     break;
1565   }
1566 
1567   // Reject elements larger than ELEN.
1568   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1569     return false;
1570 
1571   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1572   // Don't use RVV for types that don't fit.
1573   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1574     return false;
1575 
1576   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1577   // the base fixed length RVV support in place.
1578   if (!VT.isPow2VectorType())
1579     return false;
1580 
1581   return true;
1582 }
1583 
1584 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1585   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1586 }
1587 
1588 // Return the largest legal scalable vector type that matches VT's element type.
1589 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1590                                             const RISCVSubtarget &Subtarget) {
1591   // This may be called before legal types are setup.
1592   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1593           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1594          "Expected legal fixed length vector!");
1595 
1596   unsigned MinVLen = Subtarget.getRealMinVLen();
1597   unsigned MaxELen = Subtarget.getELEN();
1598 
1599   MVT EltVT = VT.getVectorElementType();
1600   switch (EltVT.SimpleTy) {
1601   default:
1602     llvm_unreachable("unexpected element type for RVV container");
1603   case MVT::i1:
1604   case MVT::i8:
1605   case MVT::i16:
1606   case MVT::i32:
1607   case MVT::i64:
1608   case MVT::f16:
1609   case MVT::f32:
1610   case MVT::f64: {
1611     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1612     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1613     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1614     unsigned NumElts =
1615         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1616     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1617     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1618     return MVT::getScalableVectorVT(EltVT, NumElts);
1619   }
1620   }
1621 }
1622 
1623 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1624                                             const RISCVSubtarget &Subtarget) {
1625   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1626                                           Subtarget);
1627 }
1628 
1629 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1630   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1631 }
1632 
1633 // Grow V to consume an entire RVV register.
1634 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1635                                        const RISCVSubtarget &Subtarget) {
1636   assert(VT.isScalableVector() &&
1637          "Expected to convert into a scalable vector!");
1638   assert(V.getValueType().isFixedLengthVector() &&
1639          "Expected a fixed length vector operand!");
1640   SDLoc DL(V);
1641   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1642   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1643 }
1644 
1645 // Shrink V so it's just big enough to maintain a VT's worth of data.
1646 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1647                                          const RISCVSubtarget &Subtarget) {
1648   assert(VT.isFixedLengthVector() &&
1649          "Expected to convert into a fixed length vector!");
1650   assert(V.getValueType().isScalableVector() &&
1651          "Expected a scalable vector operand!");
1652   SDLoc DL(V);
1653   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1654   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1655 }
1656 
1657 /// Return the type of the mask type suitable for masking the provided
1658 /// vector type.  This is simply an i1 element type vector of the same
1659 /// (possibly scalable) length.
1660 static MVT getMaskTypeFor(EVT VecVT) {
1661   assert(VecVT.isVector());
1662   ElementCount EC = VecVT.getVectorElementCount();
1663   return MVT::getVectorVT(MVT::i1, EC);
1664 }
1665 
1666 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1667 /// vector length VL.  .
1668 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1669                               SelectionDAG &DAG) {
1670   MVT MaskVT = getMaskTypeFor(VecVT);
1671   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1672 }
1673 
1674 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1675 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1676 // the vector type that it is contained in.
1677 static std::pair<SDValue, SDValue>
1678 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1679                 const RISCVSubtarget &Subtarget) {
1680   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1681   MVT XLenVT = Subtarget.getXLenVT();
1682   SDValue VL = VecVT.isFixedLengthVector()
1683                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1684                    : DAG.getRegister(RISCV::X0, XLenVT);
1685   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1686   return {Mask, VL};
1687 }
1688 
1689 // As above but assuming the given type is a scalable vector type.
1690 static std::pair<SDValue, SDValue>
1691 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1692                         const RISCVSubtarget &Subtarget) {
1693   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1694   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1695 }
1696 
1697 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1698 // of either is (currently) supported. This can get us into an infinite loop
1699 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1700 // as a ..., etc.
1701 // Until either (or both) of these can reliably lower any node, reporting that
1702 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1703 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1704 // which is not desirable.
1705 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1706     EVT VT, unsigned DefinedValues) const {
1707   return false;
1708 }
1709 
1710 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1711                                   const RISCVSubtarget &Subtarget) {
1712   // RISCV FP-to-int conversions saturate to the destination register size, but
1713   // don't produce 0 for nan. We can use a conversion instruction and fix the
1714   // nan case with a compare and a select.
1715   SDValue Src = Op.getOperand(0);
1716 
1717   EVT DstVT = Op.getValueType();
1718   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1719 
1720   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1721   unsigned Opc;
1722   if (SatVT == DstVT)
1723     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1724   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1725     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1726   else
1727     return SDValue();
1728   // FIXME: Support other SatVTs by clamping before or after the conversion.
1729 
1730   SDLoc DL(Op);
1731   SDValue FpToInt = DAG.getNode(
1732       Opc, DL, DstVT, Src,
1733       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1734 
1735   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1736   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1737 }
1738 
1739 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1740 // and back. Taking care to avoid converting values that are nan or already
1741 // correct.
1742 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1743 // have FRM dependencies modeled yet.
1744 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1745   MVT VT = Op.getSimpleValueType();
1746   assert(VT.isVector() && "Unexpected type");
1747 
1748   SDLoc DL(Op);
1749 
1750   // Freeze the source since we are increasing the number of uses.
1751   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1752 
1753   // Truncate to integer and convert back to FP.
1754   MVT IntVT = VT.changeVectorElementTypeToInteger();
1755   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1756   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1757 
1758   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1759 
1760   if (Op.getOpcode() == ISD::FCEIL) {
1761     // If the truncated value is the greater than or equal to the original
1762     // value, we've computed the ceil. Otherwise, we went the wrong way and
1763     // need to increase by 1.
1764     // FIXME: This should use a masked operation. Handle here or in isel?
1765     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1766                                  DAG.getConstantFP(1.0, DL, VT));
1767     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1768     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1769   } else if (Op.getOpcode() == ISD::FFLOOR) {
1770     // If the truncated value is the less than or equal to the original value,
1771     // we've computed the floor. Otherwise, we went the wrong way and need to
1772     // decrease by 1.
1773     // FIXME: This should use a masked operation. Handle here or in isel?
1774     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1775                                  DAG.getConstantFP(1.0, DL, VT));
1776     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1777     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1778   }
1779 
1780   // Restore the original sign so that -0.0 is preserved.
1781   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1782 
1783   // Determine the largest integer that can be represented exactly. This and
1784   // values larger than it don't have any fractional bits so don't need to
1785   // be converted.
1786   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1787   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1788   APFloat MaxVal = APFloat(FltSem);
1789   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1790                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1791   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1792 
1793   // If abs(Src) was larger than MaxVal or nan, keep it.
1794   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1795   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1796   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1797 }
1798 
1799 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1800 // This mode isn't supported in vector hardware on RISCV. But as long as we
1801 // aren't compiling with trapping math, we can emulate this with
1802 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1803 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1804 // dependencies modeled yet.
1805 // FIXME: Use masked operations to avoid final merge.
1806 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1807   MVT VT = Op.getSimpleValueType();
1808   assert(VT.isVector() && "Unexpected type");
1809 
1810   SDLoc DL(Op);
1811 
1812   // Freeze the source since we are increasing the number of uses.
1813   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1814 
1815   // We do the conversion on the absolute value and fix the sign at the end.
1816   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1817 
1818   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1819   bool Ignored;
1820   APFloat Point5Pred = APFloat(0.5f);
1821   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1822   Point5Pred.next(/*nextDown*/ true);
1823 
1824   // Add the adjustment.
1825   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1826                                DAG.getConstantFP(Point5Pred, DL, VT));
1827 
1828   // Truncate to integer and convert back to fp.
1829   MVT IntVT = VT.changeVectorElementTypeToInteger();
1830   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1831   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1832 
1833   // Restore the original sign.
1834   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1835 
1836   // Determine the largest integer that can be represented exactly. This and
1837   // values larger than it don't have any fractional bits so don't need to
1838   // be converted.
1839   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1840   APFloat MaxVal = APFloat(FltSem);
1841   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1842                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1843   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1844 
1845   // If abs(Src) was larger than MaxVal or nan, keep it.
1846   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1847   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1848   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1849 }
1850 
1851 struct VIDSequence {
1852   int64_t StepNumerator;
1853   unsigned StepDenominator;
1854   int64_t Addend;
1855 };
1856 
1857 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1858 // to the (non-zero) step S and start value X. This can be then lowered as the
1859 // RVV sequence (VID * S) + X, for example.
1860 // The step S is represented as an integer numerator divided by a positive
1861 // denominator. Note that the implementation currently only identifies
1862 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1863 // cannot detect 2/3, for example.
1864 // Note that this method will also match potentially unappealing index
1865 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1866 // determine whether this is worth generating code for.
1867 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1868   unsigned NumElts = Op.getNumOperands();
1869   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1870   if (!Op.getValueType().isInteger())
1871     return None;
1872 
1873   Optional<unsigned> SeqStepDenom;
1874   Optional<int64_t> SeqStepNum, SeqAddend;
1875   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1876   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1877   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1878     // Assume undef elements match the sequence; we just have to be careful
1879     // when interpolating across them.
1880     if (Op.getOperand(Idx).isUndef())
1881       continue;
1882     // The BUILD_VECTOR must be all constants.
1883     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1884       return None;
1885 
1886     uint64_t Val = Op.getConstantOperandVal(Idx) &
1887                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1888 
1889     if (PrevElt) {
1890       // Calculate the step since the last non-undef element, and ensure
1891       // it's consistent across the entire sequence.
1892       unsigned IdxDiff = Idx - PrevElt->second;
1893       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1894 
1895       // A zero-value value difference means that we're somewhere in the middle
1896       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1897       // step change before evaluating the sequence.
1898       if (ValDiff == 0)
1899         continue;
1900 
1901       int64_t Remainder = ValDiff % IdxDiff;
1902       // Normalize the step if it's greater than 1.
1903       if (Remainder != ValDiff) {
1904         // The difference must cleanly divide the element span.
1905         if (Remainder != 0)
1906           return None;
1907         ValDiff /= IdxDiff;
1908         IdxDiff = 1;
1909       }
1910 
1911       if (!SeqStepNum)
1912         SeqStepNum = ValDiff;
1913       else if (ValDiff != SeqStepNum)
1914         return None;
1915 
1916       if (!SeqStepDenom)
1917         SeqStepDenom = IdxDiff;
1918       else if (IdxDiff != *SeqStepDenom)
1919         return None;
1920     }
1921 
1922     // Record this non-undef element for later.
1923     if (!PrevElt || PrevElt->first != Val)
1924       PrevElt = std::make_pair(Val, Idx);
1925   }
1926 
1927   // We need to have logged a step for this to count as a legal index sequence.
1928   if (!SeqStepNum || !SeqStepDenom)
1929     return None;
1930 
1931   // Loop back through the sequence and validate elements we might have skipped
1932   // while waiting for a valid step. While doing this, log any sequence addend.
1933   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1934     if (Op.getOperand(Idx).isUndef())
1935       continue;
1936     uint64_t Val = Op.getConstantOperandVal(Idx) &
1937                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1938     uint64_t ExpectedVal =
1939         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1940     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1941     if (!SeqAddend)
1942       SeqAddend = Addend;
1943     else if (Addend != SeqAddend)
1944       return None;
1945   }
1946 
1947   assert(SeqAddend && "Must have an addend if we have a step");
1948 
1949   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1950 }
1951 
1952 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1953 // and lower it as a VRGATHER_VX_VL from the source vector.
1954 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1955                                   SelectionDAG &DAG,
1956                                   const RISCVSubtarget &Subtarget) {
1957   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1958     return SDValue();
1959   SDValue Vec = SplatVal.getOperand(0);
1960   // Only perform this optimization on vectors of the same size for simplicity.
1961   // Don't perform this optimization for i1 vectors.
1962   // FIXME: Support i1 vectors, maybe by promoting to i8?
1963   if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
1964     return SDValue();
1965   SDValue Idx = SplatVal.getOperand(1);
1966   // The index must be a legal type.
1967   if (Idx.getValueType() != Subtarget.getXLenVT())
1968     return SDValue();
1969 
1970   MVT ContainerVT = VT;
1971   if (VT.isFixedLengthVector()) {
1972     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1973     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1974   }
1975 
1976   SDValue Mask, VL;
1977   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1978 
1979   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
1980                                Idx, Mask, DAG.getUNDEF(ContainerVT), VL);
1981 
1982   if (!VT.isFixedLengthVector())
1983     return Gather;
1984 
1985   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1986 }
1987 
1988 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1989                                  const RISCVSubtarget &Subtarget) {
1990   MVT VT = Op.getSimpleValueType();
1991   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1992 
1993   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1994 
1995   SDLoc DL(Op);
1996   SDValue Mask, VL;
1997   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1998 
1999   MVT XLenVT = Subtarget.getXLenVT();
2000   unsigned NumElts = Op.getNumOperands();
2001 
2002   if (VT.getVectorElementType() == MVT::i1) {
2003     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2004       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2005       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2006     }
2007 
2008     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2009       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2010       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2011     }
2012 
2013     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2014     // scalar integer chunks whose bit-width depends on the number of mask
2015     // bits and XLEN.
2016     // First, determine the most appropriate scalar integer type to use. This
2017     // is at most XLenVT, but may be shrunk to a smaller vector element type
2018     // according to the size of the final vector - use i8 chunks rather than
2019     // XLenVT if we're producing a v8i1. This results in more consistent
2020     // codegen across RV32 and RV64.
2021     unsigned NumViaIntegerBits =
2022         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2023     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2024     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2025       // If we have to use more than one INSERT_VECTOR_ELT then this
2026       // optimization is likely to increase code size; avoid peforming it in
2027       // such a case. We can use a load from a constant pool in this case.
2028       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2029         return SDValue();
2030       // Now we can create our integer vector type. Note that it may be larger
2031       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2032       MVT IntegerViaVecVT =
2033           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2034                            divideCeil(NumElts, NumViaIntegerBits));
2035 
2036       uint64_t Bits = 0;
2037       unsigned BitPos = 0, IntegerEltIdx = 0;
2038       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2039 
2040       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2041         // Once we accumulate enough bits to fill our scalar type, insert into
2042         // our vector and clear our accumulated data.
2043         if (I != 0 && I % NumViaIntegerBits == 0) {
2044           if (NumViaIntegerBits <= 32)
2045             Bits = SignExtend64<32>(Bits);
2046           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2047           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2048                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2049           Bits = 0;
2050           BitPos = 0;
2051           IntegerEltIdx++;
2052         }
2053         SDValue V = Op.getOperand(I);
2054         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2055         Bits |= ((uint64_t)BitValue << BitPos);
2056       }
2057 
2058       // Insert the (remaining) scalar value into position in our integer
2059       // vector type.
2060       if (NumViaIntegerBits <= 32)
2061         Bits = SignExtend64<32>(Bits);
2062       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2063       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2064                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2065 
2066       if (NumElts < NumViaIntegerBits) {
2067         // If we're producing a smaller vector than our minimum legal integer
2068         // type, bitcast to the equivalent (known-legal) mask type, and extract
2069         // our final mask.
2070         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2071         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2072         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2073                           DAG.getConstant(0, DL, XLenVT));
2074       } else {
2075         // Else we must have produced an integer type with the same size as the
2076         // mask type; bitcast for the final result.
2077         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2078         Vec = DAG.getBitcast(VT, Vec);
2079       }
2080 
2081       return Vec;
2082     }
2083 
2084     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2085     // vector type, we have a legal equivalently-sized i8 type, so we can use
2086     // that.
2087     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2088     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2089 
2090     SDValue WideVec;
2091     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2092       // For a splat, perform a scalar truncate before creating the wider
2093       // vector.
2094       assert(Splat.getValueType() == XLenVT &&
2095              "Unexpected type for i1 splat value");
2096       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2097                           DAG.getConstant(1, DL, XLenVT));
2098       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2099     } else {
2100       SmallVector<SDValue, 8> Ops(Op->op_values());
2101       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2102       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2103       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2104     }
2105 
2106     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2107   }
2108 
2109   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2110     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2111       return Gather;
2112     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2113                                         : RISCVISD::VMV_V_X_VL;
2114     Splat =
2115         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2116     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2117   }
2118 
2119   // Try and match index sequences, which we can lower to the vid instruction
2120   // with optional modifications. An all-undef vector is matched by
2121   // getSplatValue, above.
2122   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2123     int64_t StepNumerator = SimpleVID->StepNumerator;
2124     unsigned StepDenominator = SimpleVID->StepDenominator;
2125     int64_t Addend = SimpleVID->Addend;
2126 
2127     assert(StepNumerator != 0 && "Invalid step");
2128     bool Negate = false;
2129     int64_t SplatStepVal = StepNumerator;
2130     unsigned StepOpcode = ISD::MUL;
2131     if (StepNumerator != 1) {
2132       if (isPowerOf2_64(std::abs(StepNumerator))) {
2133         Negate = StepNumerator < 0;
2134         StepOpcode = ISD::SHL;
2135         SplatStepVal = Log2_64(std::abs(StepNumerator));
2136       }
2137     }
2138 
2139     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2140     // threshold since it's the immediate value many RVV instructions accept.
2141     // There is no vmul.vi instruction so ensure multiply constant can fit in
2142     // a single addi instruction.
2143     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2144          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2145         isPowerOf2_32(StepDenominator) &&
2146         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2147       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2148       // Convert right out of the scalable type so we can use standard ISD
2149       // nodes for the rest of the computation. If we used scalable types with
2150       // these, we'd lose the fixed-length vector info and generate worse
2151       // vsetvli code.
2152       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2153       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2154           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2155         SDValue SplatStep = DAG.getSplatBuildVector(
2156             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2157         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2158       }
2159       if (StepDenominator != 1) {
2160         SDValue SplatStep = DAG.getSplatBuildVector(
2161             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2162         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2163       }
2164       if (Addend != 0 || Negate) {
2165         SDValue SplatAddend = DAG.getSplatBuildVector(
2166             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2167         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2168       }
2169       return VID;
2170     }
2171   }
2172 
2173   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2174   // when re-interpreted as a vector with a larger element type. For example,
2175   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2176   // could be instead splat as
2177   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2178   // TODO: This optimization could also work on non-constant splats, but it
2179   // would require bit-manipulation instructions to construct the splat value.
2180   SmallVector<SDValue> Sequence;
2181   unsigned EltBitSize = VT.getScalarSizeInBits();
2182   const auto *BV = cast<BuildVectorSDNode>(Op);
2183   if (VT.isInteger() && EltBitSize < 64 &&
2184       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2185       BV->getRepeatedSequence(Sequence) &&
2186       (Sequence.size() * EltBitSize) <= 64) {
2187     unsigned SeqLen = Sequence.size();
2188     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2189     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2190     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2191             ViaIntVT == MVT::i64) &&
2192            "Unexpected sequence type");
2193 
2194     unsigned EltIdx = 0;
2195     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2196     uint64_t SplatValue = 0;
2197     // Construct the amalgamated value which can be splatted as this larger
2198     // vector type.
2199     for (const auto &SeqV : Sequence) {
2200       if (!SeqV.isUndef())
2201         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2202                        << (EltIdx * EltBitSize));
2203       EltIdx++;
2204     }
2205 
2206     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2207     // achieve better constant materializion.
2208     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2209       SplatValue = SignExtend64<32>(SplatValue);
2210 
2211     // Since we can't introduce illegal i64 types at this stage, we can only
2212     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2213     // way we can use RVV instructions to splat.
2214     assert((ViaIntVT.bitsLE(XLenVT) ||
2215             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2216            "Unexpected bitcast sequence");
2217     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2218       SDValue ViaVL =
2219           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2220       MVT ViaContainerVT =
2221           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2222       SDValue Splat =
2223           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2224                       DAG.getUNDEF(ViaContainerVT),
2225                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2226       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2227       return DAG.getBitcast(VT, Splat);
2228     }
2229   }
2230 
2231   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2232   // which constitute a large proportion of the elements. In such cases we can
2233   // splat a vector with the dominant element and make up the shortfall with
2234   // INSERT_VECTOR_ELTs.
2235   // Note that this includes vectors of 2 elements by association. The
2236   // upper-most element is the "dominant" one, allowing us to use a splat to
2237   // "insert" the upper element, and an insert of the lower element at position
2238   // 0, which improves codegen.
2239   SDValue DominantValue;
2240   unsigned MostCommonCount = 0;
2241   DenseMap<SDValue, unsigned> ValueCounts;
2242   unsigned NumUndefElts =
2243       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2244 
2245   // Track the number of scalar loads we know we'd be inserting, estimated as
2246   // any non-zero floating-point constant. Other kinds of element are either
2247   // already in registers or are materialized on demand. The threshold at which
2248   // a vector load is more desirable than several scalar materializion and
2249   // vector-insertion instructions is not known.
2250   unsigned NumScalarLoads = 0;
2251 
2252   for (SDValue V : Op->op_values()) {
2253     if (V.isUndef())
2254       continue;
2255 
2256     ValueCounts.insert(std::make_pair(V, 0));
2257     unsigned &Count = ValueCounts[V];
2258 
2259     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2260       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2261 
2262     // Is this value dominant? In case of a tie, prefer the highest element as
2263     // it's cheaper to insert near the beginning of a vector than it is at the
2264     // end.
2265     if (++Count >= MostCommonCount) {
2266       DominantValue = V;
2267       MostCommonCount = Count;
2268     }
2269   }
2270 
2271   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2272   unsigned NumDefElts = NumElts - NumUndefElts;
2273   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2274 
2275   // Don't perform this optimization when optimizing for size, since
2276   // materializing elements and inserting them tends to cause code bloat.
2277   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2278       ((MostCommonCount > DominantValueCountThreshold) ||
2279        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2280     // Start by splatting the most common element.
2281     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2282 
2283     DenseSet<SDValue> Processed{DominantValue};
2284     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2285     for (const auto &OpIdx : enumerate(Op->ops())) {
2286       const SDValue &V = OpIdx.value();
2287       if (V.isUndef() || !Processed.insert(V).second)
2288         continue;
2289       if (ValueCounts[V] == 1) {
2290         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2291                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2292       } else {
2293         // Blend in all instances of this value using a VSELECT, using a
2294         // mask where each bit signals whether that element is the one
2295         // we're after.
2296         SmallVector<SDValue> Ops;
2297         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2298           return DAG.getConstant(V == V1, DL, XLenVT);
2299         });
2300         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2301                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2302                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2303       }
2304     }
2305 
2306     return Vec;
2307   }
2308 
2309   return SDValue();
2310 }
2311 
2312 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2313                                    SDValue Lo, SDValue Hi, SDValue VL,
2314                                    SelectionDAG &DAG) {
2315   if (!Passthru)
2316     Passthru = DAG.getUNDEF(VT);
2317   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2318     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2319     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2320     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2321     // node in order to try and match RVV vector/scalar instructions.
2322     if ((LoC >> 31) == HiC)
2323       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2324 
2325     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2326     // vmv.v.x whose EEW = 32 to lower it.
2327     auto *Const = dyn_cast<ConstantSDNode>(VL);
2328     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2329       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2330       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2331       // access the subtarget here now.
2332       auto InterVec = DAG.getNode(
2333           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2334                                   DAG.getRegister(RISCV::X0, MVT::i32));
2335       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2336     }
2337   }
2338 
2339   // Fall back to a stack store and stride x0 vector load.
2340   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2341                      Hi, VL);
2342 }
2343 
2344 // Called by type legalization to handle splat of i64 on RV32.
2345 // FIXME: We can optimize this when the type has sign or zero bits in one
2346 // of the halves.
2347 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2348                                    SDValue Scalar, SDValue VL,
2349                                    SelectionDAG &DAG) {
2350   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2351   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2352                            DAG.getConstant(0, DL, MVT::i32));
2353   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2354                            DAG.getConstant(1, DL, MVT::i32));
2355   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2356 }
2357 
2358 // This function lowers a splat of a scalar operand Splat with the vector
2359 // length VL. It ensures the final sequence is type legal, which is useful when
2360 // lowering a splat after type legalization.
2361 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2362                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2363                                 const RISCVSubtarget &Subtarget) {
2364   bool HasPassthru = Passthru && !Passthru.isUndef();
2365   if (!HasPassthru && !Passthru)
2366     Passthru = DAG.getUNDEF(VT);
2367   if (VT.isFloatingPoint()) {
2368     // If VL is 1, we could use vfmv.s.f.
2369     if (isOneConstant(VL))
2370       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2371     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2372   }
2373 
2374   MVT XLenVT = Subtarget.getXLenVT();
2375 
2376   // Simplest case is that the operand needs to be promoted to XLenVT.
2377   if (Scalar.getValueType().bitsLE(XLenVT)) {
2378     // If the operand is a constant, sign extend to increase our chances
2379     // of being able to use a .vi instruction. ANY_EXTEND would become a
2380     // a zero extend and the simm5 check in isel would fail.
2381     // FIXME: Should we ignore the upper bits in isel instead?
2382     unsigned ExtOpc =
2383         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2384     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2385     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2386     // If VL is 1 and the scalar value won't benefit from immediate, we could
2387     // use vmv.s.x.
2388     if (isOneConstant(VL) &&
2389         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2390       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2391     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2392   }
2393 
2394   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2395          "Unexpected scalar for splat lowering!");
2396 
2397   if (isOneConstant(VL) && isNullConstant(Scalar))
2398     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2399                        DAG.getConstant(0, DL, XLenVT), VL);
2400 
2401   // Otherwise use the more complicated splatting algorithm.
2402   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2403 }
2404 
2405 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2406                                 const RISCVSubtarget &Subtarget) {
2407   // We need to be able to widen elements to the next larger integer type.
2408   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2409     return false;
2410 
2411   int Size = Mask.size();
2412   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2413 
2414   int Srcs[] = {-1, -1};
2415   for (int i = 0; i != Size; ++i) {
2416     // Ignore undef elements.
2417     if (Mask[i] < 0)
2418       continue;
2419 
2420     // Is this an even or odd element.
2421     int Pol = i % 2;
2422 
2423     // Ensure we consistently use the same source for this element polarity.
2424     int Src = Mask[i] / Size;
2425     if (Srcs[Pol] < 0)
2426       Srcs[Pol] = Src;
2427     if (Srcs[Pol] != Src)
2428       return false;
2429 
2430     // Make sure the element within the source is appropriate for this element
2431     // in the destination.
2432     int Elt = Mask[i] % Size;
2433     if (Elt != i / 2)
2434       return false;
2435   }
2436 
2437   // We need to find a source for each polarity and they can't be the same.
2438   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2439     return false;
2440 
2441   // Swap the sources if the second source was in the even polarity.
2442   SwapSources = Srcs[0] > Srcs[1];
2443 
2444   return true;
2445 }
2446 
2447 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2448 /// and then extract the original number of elements from the rotated result.
2449 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2450 /// returned rotation amount is for a rotate right, where elements move from
2451 /// higher elements to lower elements. \p LoSrc indicates the first source
2452 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2453 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2454 /// 0 or 1 if a rotation is found.
2455 ///
2456 /// NOTE: We talk about rotate to the right which matches how bit shift and
2457 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2458 /// and the table below write vectors with the lowest elements on the left.
2459 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2460   int Size = Mask.size();
2461 
2462   // We need to detect various ways of spelling a rotation:
2463   //   [11, 12, 13, 14, 15,  0,  1,  2]
2464   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2465   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2466   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2467   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2468   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2469   int Rotation = 0;
2470   LoSrc = -1;
2471   HiSrc = -1;
2472   for (int i = 0; i != Size; ++i) {
2473     int M = Mask[i];
2474     if (M < 0)
2475       continue;
2476 
2477     // Determine where a rotate vector would have started.
2478     int StartIdx = i - (M % Size);
2479     // The identity rotation isn't interesting, stop.
2480     if (StartIdx == 0)
2481       return -1;
2482 
2483     // If we found the tail of a vector the rotation must be the missing
2484     // front. If we found the head of a vector, it must be how much of the
2485     // head.
2486     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2487 
2488     if (Rotation == 0)
2489       Rotation = CandidateRotation;
2490     else if (Rotation != CandidateRotation)
2491       // The rotations don't match, so we can't match this mask.
2492       return -1;
2493 
2494     // Compute which value this mask is pointing at.
2495     int MaskSrc = M < Size ? 0 : 1;
2496 
2497     // Compute which of the two target values this index should be assigned to.
2498     // This reflects whether the high elements are remaining or the low elemnts
2499     // are remaining.
2500     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2501 
2502     // Either set up this value if we've not encountered it before, or check
2503     // that it remains consistent.
2504     if (TargetSrc < 0)
2505       TargetSrc = MaskSrc;
2506     else if (TargetSrc != MaskSrc)
2507       // This may be a rotation, but it pulls from the inputs in some
2508       // unsupported interleaving.
2509       return -1;
2510   }
2511 
2512   // Check that we successfully analyzed the mask, and normalize the results.
2513   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2514   assert((LoSrc >= 0 || HiSrc >= 0) &&
2515          "Failed to find a rotated input vector!");
2516 
2517   return Rotation;
2518 }
2519 
2520 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2521                                    const RISCVSubtarget &Subtarget) {
2522   SDValue V1 = Op.getOperand(0);
2523   SDValue V2 = Op.getOperand(1);
2524   SDLoc DL(Op);
2525   MVT XLenVT = Subtarget.getXLenVT();
2526   MVT VT = Op.getSimpleValueType();
2527   unsigned NumElts = VT.getVectorNumElements();
2528   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2529 
2530   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2531 
2532   SDValue TrueMask, VL;
2533   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2534 
2535   if (SVN->isSplat()) {
2536     const int Lane = SVN->getSplatIndex();
2537     if (Lane >= 0) {
2538       MVT SVT = VT.getVectorElementType();
2539 
2540       // Turn splatted vector load into a strided load with an X0 stride.
2541       SDValue V = V1;
2542       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2543       // with undef.
2544       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2545       int Offset = Lane;
2546       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2547         int OpElements =
2548             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2549         V = V.getOperand(Offset / OpElements);
2550         Offset %= OpElements;
2551       }
2552 
2553       // We need to ensure the load isn't atomic or volatile.
2554       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2555         auto *Ld = cast<LoadSDNode>(V);
2556         Offset *= SVT.getStoreSize();
2557         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2558                                                    TypeSize::Fixed(Offset), DL);
2559 
2560         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2561         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2562           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2563           SDValue IntID =
2564               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2565           SDValue Ops[] = {Ld->getChain(),
2566                            IntID,
2567                            DAG.getUNDEF(ContainerVT),
2568                            NewAddr,
2569                            DAG.getRegister(RISCV::X0, XLenVT),
2570                            VL};
2571           SDValue NewLoad = DAG.getMemIntrinsicNode(
2572               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2573               DAG.getMachineFunction().getMachineMemOperand(
2574                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2575           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2576           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2577         }
2578 
2579         // Otherwise use a scalar load and splat. This will give the best
2580         // opportunity to fold a splat into the operation. ISel can turn it into
2581         // the x0 strided load if we aren't able to fold away the select.
2582         if (SVT.isFloatingPoint())
2583           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2584                           Ld->getPointerInfo().getWithOffset(Offset),
2585                           Ld->getOriginalAlign(),
2586                           Ld->getMemOperand()->getFlags());
2587         else
2588           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2589                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2590                              Ld->getOriginalAlign(),
2591                              Ld->getMemOperand()->getFlags());
2592         DAG.makeEquivalentMemoryOrdering(Ld, V);
2593 
2594         unsigned Opc =
2595             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2596         SDValue Splat =
2597             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2598         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2599       }
2600 
2601       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2602       assert(Lane < (int)NumElts && "Unexpected lane!");
2603       SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
2604                                    V1, DAG.getConstant(Lane, DL, XLenVT),
2605                                    TrueMask, DAG.getUNDEF(ContainerVT), VL);
2606       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2607     }
2608   }
2609 
2610   ArrayRef<int> Mask = SVN->getMask();
2611 
2612   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2613   // be undef which can be handled with a single SLIDEDOWN/UP.
2614   int LoSrc, HiSrc;
2615   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2616   if (Rotation > 0) {
2617     SDValue LoV, HiV;
2618     if (LoSrc >= 0) {
2619       LoV = LoSrc == 0 ? V1 : V2;
2620       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2621     }
2622     if (HiSrc >= 0) {
2623       HiV = HiSrc == 0 ? V1 : V2;
2624       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2625     }
2626 
2627     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2628     // to slide LoV up by (NumElts - Rotation).
2629     unsigned InvRotate = NumElts - Rotation;
2630 
2631     SDValue Res = DAG.getUNDEF(ContainerVT);
2632     if (HiV) {
2633       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2634       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2635       // causes multiple vsetvlis in some test cases such as lowering
2636       // reduce.mul
2637       SDValue DownVL = VL;
2638       if (LoV)
2639         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2640       Res =
2641           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2642                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2643     }
2644     if (LoV)
2645       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2646                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2647 
2648     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2649   }
2650 
2651   // Detect an interleave shuffle and lower to
2652   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2653   bool SwapSources;
2654   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2655     // Swap sources if needed.
2656     if (SwapSources)
2657       std::swap(V1, V2);
2658 
2659     // Extract the lower half of the vectors.
2660     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2661     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2662                      DAG.getConstant(0, DL, XLenVT));
2663     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2664                      DAG.getConstant(0, DL, XLenVT));
2665 
2666     // Double the element width and halve the number of elements in an int type.
2667     unsigned EltBits = VT.getScalarSizeInBits();
2668     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2669     MVT WideIntVT =
2670         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2671     // Convert this to a scalable vector. We need to base this on the
2672     // destination size to ensure there's always a type with a smaller LMUL.
2673     MVT WideIntContainerVT =
2674         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2675 
2676     // Convert sources to scalable vectors with the same element count as the
2677     // larger type.
2678     MVT HalfContainerVT = MVT::getVectorVT(
2679         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2680     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2681     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2682 
2683     // Cast sources to integer.
2684     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2685     MVT IntHalfVT =
2686         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2687     V1 = DAG.getBitcast(IntHalfVT, V1);
2688     V2 = DAG.getBitcast(IntHalfVT, V2);
2689 
2690     // Freeze V2 since we use it twice and we need to be sure that the add and
2691     // multiply see the same value.
2692     V2 = DAG.getFreeze(V2);
2693 
2694     // Recreate TrueMask using the widened type's element count.
2695     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2696 
2697     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2698     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2699                               V2, TrueMask, VL);
2700     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2701     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2702                                      DAG.getUNDEF(IntHalfVT),
2703                                      DAG.getAllOnesConstant(DL, XLenVT));
2704     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2705                                    V2, Multiplier, TrueMask, VL);
2706     // Add the new copies to our previous addition giving us 2^eltbits copies of
2707     // V2. This is equivalent to shifting V2 left by eltbits. This should
2708     // combine with the vwmulu.vv above to form vwmaccu.vv.
2709     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2710                       TrueMask, VL);
2711     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2712     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2713     // vector VT.
2714     ContainerVT =
2715         MVT::getVectorVT(VT.getVectorElementType(),
2716                          WideIntContainerVT.getVectorElementCount() * 2);
2717     Add = DAG.getBitcast(ContainerVT, Add);
2718     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2719   }
2720 
2721   // Detect shuffles which can be re-expressed as vector selects; these are
2722   // shuffles in which each element in the destination is taken from an element
2723   // at the corresponding index in either source vectors.
2724   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2725     int MaskIndex = MaskIdx.value();
2726     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2727   });
2728 
2729   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2730 
2731   SmallVector<SDValue> MaskVals;
2732   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2733   // merged with a second vrgather.
2734   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2735 
2736   // By default we preserve the original operand order, and use a mask to
2737   // select LHS as true and RHS as false. However, since RVV vector selects may
2738   // feature splats but only on the LHS, we may choose to invert our mask and
2739   // instead select between RHS and LHS.
2740   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2741   bool InvertMask = IsSelect == SwapOps;
2742 
2743   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2744   // half.
2745   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2746 
2747   // Now construct the mask that will be used by the vselect or blended
2748   // vrgather operation. For vrgathers, construct the appropriate indices into
2749   // each vector.
2750   for (int MaskIndex : Mask) {
2751     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2752     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2753     if (!IsSelect) {
2754       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2755       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2756                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2757                                      : DAG.getUNDEF(XLenVT));
2758       GatherIndicesRHS.push_back(
2759           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2760                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2761       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2762         ++LHSIndexCounts[MaskIndex];
2763       if (!IsLHSOrUndefIndex)
2764         ++RHSIndexCounts[MaskIndex - NumElts];
2765     }
2766   }
2767 
2768   if (SwapOps) {
2769     std::swap(V1, V2);
2770     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2771   }
2772 
2773   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2774   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2775   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2776 
2777   if (IsSelect)
2778     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2779 
2780   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2781     // On such a large vector we're unable to use i8 as the index type.
2782     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2783     // may involve vector splitting if we're already at LMUL=8, or our
2784     // user-supplied maximum fixed-length LMUL.
2785     return SDValue();
2786   }
2787 
2788   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2789   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2790   MVT IndexVT = VT.changeTypeToInteger();
2791   // Since we can't introduce illegal index types at this stage, use i16 and
2792   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2793   // than XLenVT.
2794   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2795     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2796     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2797   }
2798 
2799   MVT IndexContainerVT =
2800       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2801 
2802   SDValue Gather;
2803   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2804   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2805   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2806     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2807                               Subtarget);
2808   } else {
2809     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2810     // If only one index is used, we can use a "splat" vrgather.
2811     // TODO: We can splat the most-common index and fix-up any stragglers, if
2812     // that's beneficial.
2813     if (LHSIndexCounts.size() == 1) {
2814       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2815       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2816                            DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask,
2817                            DAG.getUNDEF(ContainerVT), VL);
2818     } else {
2819       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2820       LHSIndices =
2821           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2822 
2823       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2824                            TrueMask, DAG.getUNDEF(ContainerVT), VL);
2825     }
2826   }
2827 
2828   // If a second vector operand is used by this shuffle, blend it in with an
2829   // additional vrgather.
2830   if (!V2.isUndef()) {
2831     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2832 
2833     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2834     SelectMask =
2835         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2836 
2837     // If only one index is used, we can use a "splat" vrgather.
2838     // TODO: We can splat the most-common index and fix-up any stragglers, if
2839     // that's beneficial.
2840     if (RHSIndexCounts.size() == 1) {
2841       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2842       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2843                            DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask,
2844                            Gather, VL);
2845     } else {
2846       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2847       RHSIndices =
2848           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2849       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices,
2850                            SelectMask, Gather, VL);
2851     }
2852   }
2853 
2854   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2855 }
2856 
2857 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2858   // Support splats for any type. These should type legalize well.
2859   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2860     return true;
2861 
2862   // Only support legal VTs for other shuffles for now.
2863   if (!isTypeLegal(VT))
2864     return false;
2865 
2866   MVT SVT = VT.getSimpleVT();
2867 
2868   bool SwapSources;
2869   int LoSrc, HiSrc;
2870   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2871          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2872 }
2873 
2874 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2875 // the exponent.
2876 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2877   MVT VT = Op.getSimpleValueType();
2878   unsigned EltSize = VT.getScalarSizeInBits();
2879   SDValue Src = Op.getOperand(0);
2880   SDLoc DL(Op);
2881 
2882   // We need a FP type that can represent the value.
2883   // TODO: Use f16 for i8 when possible?
2884   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2885   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2886 
2887   // Legal types should have been checked in the RISCVTargetLowering
2888   // constructor.
2889   // TODO: Splitting may make sense in some cases.
2890   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2891          "Expected legal float type!");
2892 
2893   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2894   // The trailing zero count is equal to log2 of this single bit value.
2895   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2896     SDValue Neg =
2897         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2898     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2899   }
2900 
2901   // We have a legal FP type, convert to it.
2902   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2903   // Bitcast to integer and shift the exponent to the LSB.
2904   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2905   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2906   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2907   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2908                               DAG.getConstant(ShiftAmt, DL, IntVT));
2909   // Truncate back to original type to allow vnsrl.
2910   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2911   // The exponent contains log2 of the value in biased form.
2912   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2913 
2914   // For trailing zeros, we just need to subtract the bias.
2915   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2916     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2917                        DAG.getConstant(ExponentBias, DL, VT));
2918 
2919   // For leading zeros, we need to remove the bias and convert from log2 to
2920   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2921   unsigned Adjust = ExponentBias + (EltSize - 1);
2922   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2923 }
2924 
2925 // While RVV has alignment restrictions, we should always be able to load as a
2926 // legal equivalently-sized byte-typed vector instead. This method is
2927 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2928 // the load is already correctly-aligned, it returns SDValue().
2929 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2930                                                     SelectionDAG &DAG) const {
2931   auto *Load = cast<LoadSDNode>(Op);
2932   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2933 
2934   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2935                                      Load->getMemoryVT(),
2936                                      *Load->getMemOperand()))
2937     return SDValue();
2938 
2939   SDLoc DL(Op);
2940   MVT VT = Op.getSimpleValueType();
2941   unsigned EltSizeBits = VT.getScalarSizeInBits();
2942   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2943          "Unexpected unaligned RVV load type");
2944   MVT NewVT =
2945       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2946   assert(NewVT.isValid() &&
2947          "Expecting equally-sized RVV vector types to be legal");
2948   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2949                           Load->getPointerInfo(), Load->getOriginalAlign(),
2950                           Load->getMemOperand()->getFlags());
2951   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2952 }
2953 
2954 // While RVV has alignment restrictions, we should always be able to store as a
2955 // legal equivalently-sized byte-typed vector instead. This method is
2956 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2957 // returns SDValue() if the store is already correctly aligned.
2958 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2959                                                      SelectionDAG &DAG) const {
2960   auto *Store = cast<StoreSDNode>(Op);
2961   assert(Store && Store->getValue().getValueType().isVector() &&
2962          "Expected vector store");
2963 
2964   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2965                                      Store->getMemoryVT(),
2966                                      *Store->getMemOperand()))
2967     return SDValue();
2968 
2969   SDLoc DL(Op);
2970   SDValue StoredVal = Store->getValue();
2971   MVT VT = StoredVal.getSimpleValueType();
2972   unsigned EltSizeBits = VT.getScalarSizeInBits();
2973   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2974          "Unexpected unaligned RVV store type");
2975   MVT NewVT =
2976       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2977   assert(NewVT.isValid() &&
2978          "Expecting equally-sized RVV vector types to be legal");
2979   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2980   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2981                       Store->getPointerInfo(), Store->getOriginalAlign(),
2982                       Store->getMemOperand()->getFlags());
2983 }
2984 
2985 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
2986                              const RISCVSubtarget &Subtarget) {
2987   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
2988 
2989   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
2990 
2991   // All simm32 constants should be handled by isel.
2992   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
2993   // this check redundant, but small immediates are common so this check
2994   // should have better compile time.
2995   if (isInt<32>(Imm))
2996     return Op;
2997 
2998   // We only need to cost the immediate, if constant pool lowering is enabled.
2999   if (!Subtarget.useConstantPoolForLargeInts())
3000     return Op;
3001 
3002   RISCVMatInt::InstSeq Seq =
3003       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
3004   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
3005     return Op;
3006 
3007   // Expand to a constant pool using the default expansion code.
3008   return SDValue();
3009 }
3010 
3011 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3012                                             SelectionDAG &DAG) const {
3013   switch (Op.getOpcode()) {
3014   default:
3015     report_fatal_error("unimplemented operand");
3016   case ISD::GlobalAddress:
3017     return lowerGlobalAddress(Op, DAG);
3018   case ISD::BlockAddress:
3019     return lowerBlockAddress(Op, DAG);
3020   case ISD::ConstantPool:
3021     return lowerConstantPool(Op, DAG);
3022   case ISD::JumpTable:
3023     return lowerJumpTable(Op, DAG);
3024   case ISD::GlobalTLSAddress:
3025     return lowerGlobalTLSAddress(Op, DAG);
3026   case ISD::Constant:
3027     return lowerConstant(Op, DAG, Subtarget);
3028   case ISD::SELECT:
3029     return lowerSELECT(Op, DAG);
3030   case ISD::BRCOND:
3031     return lowerBRCOND(Op, DAG);
3032   case ISD::VASTART:
3033     return lowerVASTART(Op, DAG);
3034   case ISD::FRAMEADDR:
3035     return lowerFRAMEADDR(Op, DAG);
3036   case ISD::RETURNADDR:
3037     return lowerRETURNADDR(Op, DAG);
3038   case ISD::SHL_PARTS:
3039     return lowerShiftLeftParts(Op, DAG);
3040   case ISD::SRA_PARTS:
3041     return lowerShiftRightParts(Op, DAG, true);
3042   case ISD::SRL_PARTS:
3043     return lowerShiftRightParts(Op, DAG, false);
3044   case ISD::BITCAST: {
3045     SDLoc DL(Op);
3046     EVT VT = Op.getValueType();
3047     SDValue Op0 = Op.getOperand(0);
3048     EVT Op0VT = Op0.getValueType();
3049     MVT XLenVT = Subtarget.getXLenVT();
3050     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3051       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3052       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3053       return FPConv;
3054     }
3055     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3056         Subtarget.hasStdExtF()) {
3057       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3058       SDValue FPConv =
3059           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3060       return FPConv;
3061     }
3062 
3063     // Consider other scalar<->scalar casts as legal if the types are legal.
3064     // Otherwise expand them.
3065     if (!VT.isVector() && !Op0VT.isVector()) {
3066       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3067         return Op;
3068       return SDValue();
3069     }
3070 
3071     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3072            "Unexpected types");
3073 
3074     if (VT.isFixedLengthVector()) {
3075       // We can handle fixed length vector bitcasts with a simple replacement
3076       // in isel.
3077       if (Op0VT.isFixedLengthVector())
3078         return Op;
3079       // When bitcasting from scalar to fixed-length vector, insert the scalar
3080       // into a one-element vector of the result type, and perform a vector
3081       // bitcast.
3082       if (!Op0VT.isVector()) {
3083         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3084         if (!isTypeLegal(BVT))
3085           return SDValue();
3086         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3087                                               DAG.getUNDEF(BVT), Op0,
3088                                               DAG.getConstant(0, DL, XLenVT)));
3089       }
3090       return SDValue();
3091     }
3092     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3093     // thus: bitcast the vector to a one-element vector type whose element type
3094     // is the same as the result type, and extract the first element.
3095     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3096       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3097       if (!isTypeLegal(BVT))
3098         return SDValue();
3099       SDValue BVec = DAG.getBitcast(BVT, Op0);
3100       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3101                          DAG.getConstant(0, DL, XLenVT));
3102     }
3103     return SDValue();
3104   }
3105   case ISD::INTRINSIC_WO_CHAIN:
3106     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3107   case ISD::INTRINSIC_W_CHAIN:
3108     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3109   case ISD::INTRINSIC_VOID:
3110     return LowerINTRINSIC_VOID(Op, DAG);
3111   case ISD::BSWAP:
3112   case ISD::BITREVERSE: {
3113     MVT VT = Op.getSimpleValueType();
3114     SDLoc DL(Op);
3115     if (Subtarget.hasStdExtZbp()) {
3116       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3117       // Start with the maximum immediate value which is the bitwidth - 1.
3118       unsigned Imm = VT.getSizeInBits() - 1;
3119       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3120       if (Op.getOpcode() == ISD::BSWAP)
3121         Imm &= ~0x7U;
3122       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3123                          DAG.getConstant(Imm, DL, VT));
3124     }
3125     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3126     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3127     // Expand bitreverse to a bswap(rev8) followed by brev8.
3128     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3129     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3130     // as brev8 by an isel pattern.
3131     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3132                        DAG.getConstant(7, DL, VT));
3133   }
3134   case ISD::FSHL:
3135   case ISD::FSHR: {
3136     MVT VT = Op.getSimpleValueType();
3137     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3138     SDLoc DL(Op);
3139     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3140     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3141     // accidentally setting the extra bit.
3142     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3143     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3144                                 DAG.getConstant(ShAmtWidth, DL, VT));
3145     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3146     // instruction use different orders. fshl will return its first operand for
3147     // shift of zero, fshr will return its second operand. fsl and fsr both
3148     // return rs1 so the ISD nodes need to have different operand orders.
3149     // Shift amount is in rs2.
3150     SDValue Op0 = Op.getOperand(0);
3151     SDValue Op1 = Op.getOperand(1);
3152     unsigned Opc = RISCVISD::FSL;
3153     if (Op.getOpcode() == ISD::FSHR) {
3154       std::swap(Op0, Op1);
3155       Opc = RISCVISD::FSR;
3156     }
3157     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3158   }
3159   case ISD::TRUNCATE:
3160     // Only custom-lower vector truncates
3161     if (!Op.getSimpleValueType().isVector())
3162       return Op;
3163     return lowerVectorTruncLike(Op, DAG);
3164   case ISD::ANY_EXTEND:
3165   case ISD::ZERO_EXTEND:
3166     if (Op.getOperand(0).getValueType().isVector() &&
3167         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3168       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3169     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3170   case ISD::SIGN_EXTEND:
3171     if (Op.getOperand(0).getValueType().isVector() &&
3172         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3173       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3174     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3175   case ISD::SPLAT_VECTOR_PARTS:
3176     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3177   case ISD::INSERT_VECTOR_ELT:
3178     return lowerINSERT_VECTOR_ELT(Op, DAG);
3179   case ISD::EXTRACT_VECTOR_ELT:
3180     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3181   case ISD::VSCALE: {
3182     MVT VT = Op.getSimpleValueType();
3183     SDLoc DL(Op);
3184     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3185     // We define our scalable vector types for lmul=1 to use a 64 bit known
3186     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3187     // vscale as VLENB / 8.
3188     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3189     if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
3190       report_fatal_error("Support for VLEN==32 is incomplete.");
3191     // We assume VLENB is a multiple of 8. We manually choose the best shift
3192     // here because SimplifyDemandedBits isn't always able to simplify it.
3193     uint64_t Val = Op.getConstantOperandVal(0);
3194     if (isPowerOf2_64(Val)) {
3195       uint64_t Log2 = Log2_64(Val);
3196       if (Log2 < 3)
3197         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3198                            DAG.getConstant(3 - Log2, DL, VT));
3199       if (Log2 > 3)
3200         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3201                            DAG.getConstant(Log2 - 3, DL, VT));
3202       return VLENB;
3203     }
3204     // If the multiplier is a multiple of 8, scale it down to avoid needing
3205     // to shift the VLENB value.
3206     if ((Val % 8) == 0)
3207       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3208                          DAG.getConstant(Val / 8, DL, VT));
3209 
3210     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3211                                  DAG.getConstant(3, DL, VT));
3212     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3213   }
3214   case ISD::FPOWI: {
3215     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3216     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3217     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3218         Op.getOperand(1).getValueType() == MVT::i32) {
3219       SDLoc DL(Op);
3220       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3221       SDValue Powi =
3222           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3223       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3224                          DAG.getIntPtrConstant(0, DL));
3225     }
3226     return SDValue();
3227   }
3228   case ISD::FP_EXTEND:
3229   case ISD::FP_ROUND:
3230     if (!Op.getValueType().isVector())
3231       return Op;
3232     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3233   case ISD::FP_TO_SINT:
3234   case ISD::FP_TO_UINT:
3235   case ISD::SINT_TO_FP:
3236   case ISD::UINT_TO_FP: {
3237     // RVV can only do fp<->int conversions to types half/double the size as
3238     // the source. We custom-lower any conversions that do two hops into
3239     // sequences.
3240     MVT VT = Op.getSimpleValueType();
3241     if (!VT.isVector())
3242       return Op;
3243     SDLoc DL(Op);
3244     SDValue Src = Op.getOperand(0);
3245     MVT EltVT = VT.getVectorElementType();
3246     MVT SrcVT = Src.getSimpleValueType();
3247     MVT SrcEltVT = SrcVT.getVectorElementType();
3248     unsigned EltSize = EltVT.getSizeInBits();
3249     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3250     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3251            "Unexpected vector element types");
3252 
3253     bool IsInt2FP = SrcEltVT.isInteger();
3254     // Widening conversions
3255     if (EltSize > (2 * SrcEltSize)) {
3256       if (IsInt2FP) {
3257         // Do a regular integer sign/zero extension then convert to float.
3258         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3259                                       VT.getVectorElementCount());
3260         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3261                                  ? ISD::ZERO_EXTEND
3262                                  : ISD::SIGN_EXTEND;
3263         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3264         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3265       }
3266       // FP2Int
3267       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3268       // Do one doubling fp_extend then complete the operation by converting
3269       // to int.
3270       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3271       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3272       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3273     }
3274 
3275     // Narrowing conversions
3276     if (SrcEltSize > (2 * EltSize)) {
3277       if (IsInt2FP) {
3278         // One narrowing int_to_fp, then an fp_round.
3279         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3280         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3281         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3282         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3283       }
3284       // FP2Int
3285       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3286       // representable by the integer, the result is poison.
3287       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3288                                     VT.getVectorElementCount());
3289       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3290       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3291     }
3292 
3293     // Scalable vectors can exit here. Patterns will handle equally-sized
3294     // conversions halving/doubling ones.
3295     if (!VT.isFixedLengthVector())
3296       return Op;
3297 
3298     // For fixed-length vectors we lower to a custom "VL" node.
3299     unsigned RVVOpc = 0;
3300     switch (Op.getOpcode()) {
3301     default:
3302       llvm_unreachable("Impossible opcode");
3303     case ISD::FP_TO_SINT:
3304       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3305       break;
3306     case ISD::FP_TO_UINT:
3307       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3308       break;
3309     case ISD::SINT_TO_FP:
3310       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3311       break;
3312     case ISD::UINT_TO_FP:
3313       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3314       break;
3315     }
3316 
3317     MVT ContainerVT, SrcContainerVT;
3318     // Derive the reference container type from the larger vector type.
3319     if (SrcEltSize > EltSize) {
3320       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3321       ContainerVT =
3322           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3323     } else {
3324       ContainerVT = getContainerForFixedLengthVector(VT);
3325       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3326     }
3327 
3328     SDValue Mask, VL;
3329     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3330 
3331     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3332     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3333     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3334   }
3335   case ISD::FP_TO_SINT_SAT:
3336   case ISD::FP_TO_UINT_SAT:
3337     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3338   case ISD::FTRUNC:
3339   case ISD::FCEIL:
3340   case ISD::FFLOOR:
3341     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3342   case ISD::FROUND:
3343     return lowerFROUND(Op, DAG);
3344   case ISD::VECREDUCE_ADD:
3345   case ISD::VECREDUCE_UMAX:
3346   case ISD::VECREDUCE_SMAX:
3347   case ISD::VECREDUCE_UMIN:
3348   case ISD::VECREDUCE_SMIN:
3349     return lowerVECREDUCE(Op, DAG);
3350   case ISD::VECREDUCE_AND:
3351   case ISD::VECREDUCE_OR:
3352   case ISD::VECREDUCE_XOR:
3353     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3354       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3355     return lowerVECREDUCE(Op, DAG);
3356   case ISD::VECREDUCE_FADD:
3357   case ISD::VECREDUCE_SEQ_FADD:
3358   case ISD::VECREDUCE_FMIN:
3359   case ISD::VECREDUCE_FMAX:
3360     return lowerFPVECREDUCE(Op, DAG);
3361   case ISD::VP_REDUCE_ADD:
3362   case ISD::VP_REDUCE_UMAX:
3363   case ISD::VP_REDUCE_SMAX:
3364   case ISD::VP_REDUCE_UMIN:
3365   case ISD::VP_REDUCE_SMIN:
3366   case ISD::VP_REDUCE_FADD:
3367   case ISD::VP_REDUCE_SEQ_FADD:
3368   case ISD::VP_REDUCE_FMIN:
3369   case ISD::VP_REDUCE_FMAX:
3370     return lowerVPREDUCE(Op, DAG);
3371   case ISD::VP_REDUCE_AND:
3372   case ISD::VP_REDUCE_OR:
3373   case ISD::VP_REDUCE_XOR:
3374     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3375       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3376     return lowerVPREDUCE(Op, DAG);
3377   case ISD::INSERT_SUBVECTOR:
3378     return lowerINSERT_SUBVECTOR(Op, DAG);
3379   case ISD::EXTRACT_SUBVECTOR:
3380     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3381   case ISD::STEP_VECTOR:
3382     return lowerSTEP_VECTOR(Op, DAG);
3383   case ISD::VECTOR_REVERSE:
3384     return lowerVECTOR_REVERSE(Op, DAG);
3385   case ISD::VECTOR_SPLICE:
3386     return lowerVECTOR_SPLICE(Op, DAG);
3387   case ISD::BUILD_VECTOR:
3388     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3389   case ISD::SPLAT_VECTOR:
3390     if (Op.getValueType().getVectorElementType() == MVT::i1)
3391       return lowerVectorMaskSplat(Op, DAG);
3392     return SDValue();
3393   case ISD::VECTOR_SHUFFLE:
3394     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3395   case ISD::CONCAT_VECTORS: {
3396     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3397     // better than going through the stack, as the default expansion does.
3398     SDLoc DL(Op);
3399     MVT VT = Op.getSimpleValueType();
3400     unsigned NumOpElts =
3401         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3402     SDValue Vec = DAG.getUNDEF(VT);
3403     for (const auto &OpIdx : enumerate(Op->ops())) {
3404       SDValue SubVec = OpIdx.value();
3405       // Don't insert undef subvectors.
3406       if (SubVec.isUndef())
3407         continue;
3408       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3409                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3410     }
3411     return Vec;
3412   }
3413   case ISD::LOAD:
3414     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3415       return V;
3416     if (Op.getValueType().isFixedLengthVector())
3417       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3418     return Op;
3419   case ISD::STORE:
3420     if (auto V = expandUnalignedRVVStore(Op, DAG))
3421       return V;
3422     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3423       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3424     return Op;
3425   case ISD::MLOAD:
3426   case ISD::VP_LOAD:
3427     return lowerMaskedLoad(Op, DAG);
3428   case ISD::MSTORE:
3429   case ISD::VP_STORE:
3430     return lowerMaskedStore(Op, DAG);
3431   case ISD::SETCC:
3432     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3433   case ISD::ADD:
3434     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3435   case ISD::SUB:
3436     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3437   case ISD::MUL:
3438     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3439   case ISD::MULHS:
3440     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3441   case ISD::MULHU:
3442     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3443   case ISD::AND:
3444     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3445                                               RISCVISD::AND_VL);
3446   case ISD::OR:
3447     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3448                                               RISCVISD::OR_VL);
3449   case ISD::XOR:
3450     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3451                                               RISCVISD::XOR_VL);
3452   case ISD::SDIV:
3453     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3454   case ISD::SREM:
3455     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3456   case ISD::UDIV:
3457     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3458   case ISD::UREM:
3459     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3460   case ISD::SHL:
3461   case ISD::SRA:
3462   case ISD::SRL:
3463     if (Op.getSimpleValueType().isFixedLengthVector())
3464       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3465     // This can be called for an i32 shift amount that needs to be promoted.
3466     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3467            "Unexpected custom legalisation");
3468     return SDValue();
3469   case ISD::SADDSAT:
3470     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3471   case ISD::UADDSAT:
3472     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3473   case ISD::SSUBSAT:
3474     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3475   case ISD::USUBSAT:
3476     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3477   case ISD::FADD:
3478     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3479   case ISD::FSUB:
3480     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3481   case ISD::FMUL:
3482     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3483   case ISD::FDIV:
3484     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3485   case ISD::FNEG:
3486     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3487   case ISD::FABS:
3488     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3489   case ISD::FSQRT:
3490     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3491   case ISD::FMA:
3492     return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL);
3493   case ISD::SMIN:
3494     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3495   case ISD::SMAX:
3496     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3497   case ISD::UMIN:
3498     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3499   case ISD::UMAX:
3500     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3501   case ISD::FMINNUM:
3502     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3503   case ISD::FMAXNUM:
3504     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3505   case ISD::ABS:
3506     return lowerABS(Op, DAG);
3507   case ISD::CTLZ_ZERO_UNDEF:
3508   case ISD::CTTZ_ZERO_UNDEF:
3509     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3510   case ISD::VSELECT:
3511     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3512   case ISD::FCOPYSIGN:
3513     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3514   case ISD::MGATHER:
3515   case ISD::VP_GATHER:
3516     return lowerMaskedGather(Op, DAG);
3517   case ISD::MSCATTER:
3518   case ISD::VP_SCATTER:
3519     return lowerMaskedScatter(Op, DAG);
3520   case ISD::FLT_ROUNDS_:
3521     return lowerGET_ROUNDING(Op, DAG);
3522   case ISD::SET_ROUNDING:
3523     return lowerSET_ROUNDING(Op, DAG);
3524   case ISD::EH_DWARF_CFA:
3525     return lowerEH_DWARF_CFA(Op, DAG);
3526   case ISD::VP_SELECT:
3527     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3528   case ISD::VP_MERGE:
3529     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3530   case ISD::VP_ADD:
3531     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3532   case ISD::VP_SUB:
3533     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3534   case ISD::VP_MUL:
3535     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3536   case ISD::VP_SDIV:
3537     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3538   case ISD::VP_UDIV:
3539     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3540   case ISD::VP_SREM:
3541     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3542   case ISD::VP_UREM:
3543     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3544   case ISD::VP_AND:
3545     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3546   case ISD::VP_OR:
3547     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3548   case ISD::VP_XOR:
3549     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3550   case ISD::VP_ASHR:
3551     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3552   case ISD::VP_LSHR:
3553     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3554   case ISD::VP_SHL:
3555     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3556   case ISD::VP_FADD:
3557     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3558   case ISD::VP_FSUB:
3559     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3560   case ISD::VP_FMUL:
3561     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3562   case ISD::VP_FDIV:
3563     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3564   case ISD::VP_FNEG:
3565     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3566   case ISD::VP_FMA:
3567     return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL);
3568   case ISD::VP_SIGN_EXTEND:
3569   case ISD::VP_ZERO_EXTEND:
3570     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3571       return lowerVPExtMaskOp(Op, DAG);
3572     return lowerVPOp(Op, DAG,
3573                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3574                          ? RISCVISD::VSEXT_VL
3575                          : RISCVISD::VZEXT_VL);
3576   case ISD::VP_TRUNCATE:
3577     return lowerVectorTruncLike(Op, DAG);
3578   case ISD::VP_FP_EXTEND:
3579   case ISD::VP_FP_ROUND:
3580     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3581   case ISD::VP_FPTOSI:
3582     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3583   case ISD::VP_FPTOUI:
3584     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3585   case ISD::VP_SITOFP:
3586     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3587   case ISD::VP_UITOFP:
3588     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3589   case ISD::VP_SETCC:
3590     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3591       return lowerVPSetCCMaskOp(Op, DAG);
3592     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3593   }
3594 }
3595 
3596 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3597                              SelectionDAG &DAG, unsigned Flags) {
3598   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3599 }
3600 
3601 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3602                              SelectionDAG &DAG, unsigned Flags) {
3603   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3604                                    Flags);
3605 }
3606 
3607 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3608                              SelectionDAG &DAG, unsigned Flags) {
3609   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3610                                    N->getOffset(), Flags);
3611 }
3612 
3613 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3614                              SelectionDAG &DAG, unsigned Flags) {
3615   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3616 }
3617 
3618 template <class NodeTy>
3619 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3620                                      bool IsLocal) const {
3621   SDLoc DL(N);
3622   EVT Ty = getPointerTy(DAG.getDataLayout());
3623 
3624   if (isPositionIndependent()) {
3625     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3626     if (IsLocal)
3627       // Use PC-relative addressing to access the symbol. This generates the
3628       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3629       // %pcrel_lo(auipc)).
3630       return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3631 
3632     // Use PC-relative addressing to access the GOT for this symbol, then load
3633     // the address from the GOT. This generates the pattern (PseudoLA sym),
3634     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3635     MachineFunction &MF = DAG.getMachineFunction();
3636     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3637         MachinePointerInfo::getGOT(MF),
3638         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3639             MachineMemOperand::MOInvariant,
3640         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3641     SDValue Load =
3642         DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other),
3643                                 {DAG.getEntryNode(), Addr}, Ty, MemOp);
3644     return Load;
3645   }
3646 
3647   switch (getTargetMachine().getCodeModel()) {
3648   default:
3649     report_fatal_error("Unsupported code model for lowering");
3650   case CodeModel::Small: {
3651     // Generate a sequence for accessing addresses within the first 2 GiB of
3652     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3653     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3654     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3655     SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3656     return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
3657   }
3658   case CodeModel::Medium: {
3659     // Generate a sequence for accessing addresses within any 2GiB range within
3660     // the address space. This generates the pattern (PseudoLLA sym), which
3661     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3662     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3663     return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3664   }
3665   }
3666 }
3667 
3668 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3669                                                 SelectionDAG &DAG) const {
3670   SDLoc DL(Op);
3671   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3672   assert(N->getOffset() == 0 && "unexpected offset in global node");
3673 
3674   const GlobalValue *GV = N->getGlobal();
3675   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3676   return getAddr(N, DAG, IsLocal);
3677 }
3678 
3679 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3680                                                SelectionDAG &DAG) const {
3681   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3682 
3683   return getAddr(N, DAG);
3684 }
3685 
3686 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3687                                                SelectionDAG &DAG) const {
3688   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3689 
3690   return getAddr(N, DAG);
3691 }
3692 
3693 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3694                                             SelectionDAG &DAG) const {
3695   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3696 
3697   return getAddr(N, DAG);
3698 }
3699 
3700 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3701                                               SelectionDAG &DAG,
3702                                               bool UseGOT) const {
3703   SDLoc DL(N);
3704   EVT Ty = getPointerTy(DAG.getDataLayout());
3705   const GlobalValue *GV = N->getGlobal();
3706   MVT XLenVT = Subtarget.getXLenVT();
3707 
3708   if (UseGOT) {
3709     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3710     // load the address from the GOT and add the thread pointer. This generates
3711     // the pattern (PseudoLA_TLS_IE sym), which expands to
3712     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3713     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3714     MachineFunction &MF = DAG.getMachineFunction();
3715     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3716         MachinePointerInfo::getGOT(MF),
3717         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3718             MachineMemOperand::MOInvariant,
3719         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3720     SDValue Load = DAG.getMemIntrinsicNode(
3721         RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other),
3722         {DAG.getEntryNode(), Addr}, Ty, MemOp);
3723 
3724     // Add the thread pointer.
3725     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3726     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3727   }
3728 
3729   // Generate a sequence for accessing the address relative to the thread
3730   // pointer, with the appropriate adjustment for the thread pointer offset.
3731   // This generates the pattern
3732   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3733   SDValue AddrHi =
3734       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3735   SDValue AddrAdd =
3736       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3737   SDValue AddrLo =
3738       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3739 
3740   SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3741   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3742   SDValue MNAdd =
3743       DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
3744   return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
3745 }
3746 
3747 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3748                                                SelectionDAG &DAG) const {
3749   SDLoc DL(N);
3750   EVT Ty = getPointerTy(DAG.getDataLayout());
3751   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3752   const GlobalValue *GV = N->getGlobal();
3753 
3754   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3755   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3756   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3757   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3758   SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr);
3759 
3760   // Prepare argument list to generate call.
3761   ArgListTy Args;
3762   ArgListEntry Entry;
3763   Entry.Node = Load;
3764   Entry.Ty = CallTy;
3765   Args.push_back(Entry);
3766 
3767   // Setup call to __tls_get_addr.
3768   TargetLowering::CallLoweringInfo CLI(DAG);
3769   CLI.setDebugLoc(DL)
3770       .setChain(DAG.getEntryNode())
3771       .setLibCallee(CallingConv::C, CallTy,
3772                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3773                     std::move(Args));
3774 
3775   return LowerCallTo(CLI).first;
3776 }
3777 
3778 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3779                                                    SelectionDAG &DAG) const {
3780   SDLoc DL(Op);
3781   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3782   assert(N->getOffset() == 0 && "unexpected offset in global node");
3783 
3784   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3785 
3786   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3787       CallingConv::GHC)
3788     report_fatal_error("In GHC calling convention TLS is not supported");
3789 
3790   SDValue Addr;
3791   switch (Model) {
3792   case TLSModel::LocalExec:
3793     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3794     break;
3795   case TLSModel::InitialExec:
3796     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3797     break;
3798   case TLSModel::LocalDynamic:
3799   case TLSModel::GeneralDynamic:
3800     Addr = getDynamicTLSAddr(N, DAG);
3801     break;
3802   }
3803 
3804   return Addr;
3805 }
3806 
3807 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3808   SDValue CondV = Op.getOperand(0);
3809   SDValue TrueV = Op.getOperand(1);
3810   SDValue FalseV = Op.getOperand(2);
3811   SDLoc DL(Op);
3812   MVT VT = Op.getSimpleValueType();
3813   MVT XLenVT = Subtarget.getXLenVT();
3814 
3815   // Lower vector SELECTs to VSELECTs by splatting the condition.
3816   if (VT.isVector()) {
3817     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3818     SDValue CondSplat = VT.isScalableVector()
3819                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3820                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3821     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3822   }
3823 
3824   // If the result type is XLenVT and CondV is the output of a SETCC node
3825   // which also operated on XLenVT inputs, then merge the SETCC node into the
3826   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3827   // compare+branch instructions. i.e.:
3828   // (select (setcc lhs, rhs, cc), truev, falsev)
3829   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3830   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3831       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3832     SDValue LHS = CondV.getOperand(0);
3833     SDValue RHS = CondV.getOperand(1);
3834     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3835     ISD::CondCode CCVal = CC->get();
3836 
3837     // Special case for a select of 2 constants that have a diffence of 1.
3838     // Normally this is done by DAGCombine, but if the select is introduced by
3839     // type legalization or op legalization, we miss it. Restricting to SETLT
3840     // case for now because that is what signed saturating add/sub need.
3841     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3842     // but we would probably want to swap the true/false values if the condition
3843     // is SETGE/SETLE to avoid an XORI.
3844     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3845         CCVal == ISD::SETLT) {
3846       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3847       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3848       if (TrueVal - 1 == FalseVal)
3849         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3850       if (TrueVal + 1 == FalseVal)
3851         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3852     }
3853 
3854     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3855 
3856     SDValue TargetCC = DAG.getCondCode(CCVal);
3857     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3858     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3859   }
3860 
3861   // Otherwise:
3862   // (select condv, truev, falsev)
3863   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3864   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3865   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3866 
3867   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3868 
3869   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3870 }
3871 
3872 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3873   SDValue CondV = Op.getOperand(1);
3874   SDLoc DL(Op);
3875   MVT XLenVT = Subtarget.getXLenVT();
3876 
3877   if (CondV.getOpcode() == ISD::SETCC &&
3878       CondV.getOperand(0).getValueType() == XLenVT) {
3879     SDValue LHS = CondV.getOperand(0);
3880     SDValue RHS = CondV.getOperand(1);
3881     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3882 
3883     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3884 
3885     SDValue TargetCC = DAG.getCondCode(CCVal);
3886     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3887                        LHS, RHS, TargetCC, Op.getOperand(2));
3888   }
3889 
3890   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3891                      CondV, DAG.getConstant(0, DL, XLenVT),
3892                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3893 }
3894 
3895 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3896   MachineFunction &MF = DAG.getMachineFunction();
3897   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3898 
3899   SDLoc DL(Op);
3900   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3901                                  getPointerTy(MF.getDataLayout()));
3902 
3903   // vastart just stores the address of the VarArgsFrameIndex slot into the
3904   // memory location argument.
3905   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3906   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3907                       MachinePointerInfo(SV));
3908 }
3909 
3910 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3911                                             SelectionDAG &DAG) const {
3912   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3913   MachineFunction &MF = DAG.getMachineFunction();
3914   MachineFrameInfo &MFI = MF.getFrameInfo();
3915   MFI.setFrameAddressIsTaken(true);
3916   Register FrameReg = RI.getFrameRegister(MF);
3917   int XLenInBytes = Subtarget.getXLen() / 8;
3918 
3919   EVT VT = Op.getValueType();
3920   SDLoc DL(Op);
3921   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3922   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3923   while (Depth--) {
3924     int Offset = -(XLenInBytes * 2);
3925     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3926                               DAG.getIntPtrConstant(Offset, DL));
3927     FrameAddr =
3928         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3929   }
3930   return FrameAddr;
3931 }
3932 
3933 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3934                                              SelectionDAG &DAG) const {
3935   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3936   MachineFunction &MF = DAG.getMachineFunction();
3937   MachineFrameInfo &MFI = MF.getFrameInfo();
3938   MFI.setReturnAddressIsTaken(true);
3939   MVT XLenVT = Subtarget.getXLenVT();
3940   int XLenInBytes = Subtarget.getXLen() / 8;
3941 
3942   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3943     return SDValue();
3944 
3945   EVT VT = Op.getValueType();
3946   SDLoc DL(Op);
3947   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3948   if (Depth) {
3949     int Off = -XLenInBytes;
3950     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3951     SDValue Offset = DAG.getConstant(Off, DL, VT);
3952     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3953                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3954                        MachinePointerInfo());
3955   }
3956 
3957   // Return the value of the return address register, marking it an implicit
3958   // live-in.
3959   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3960   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3961 }
3962 
3963 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3964                                                  SelectionDAG &DAG) const {
3965   SDLoc DL(Op);
3966   SDValue Lo = Op.getOperand(0);
3967   SDValue Hi = Op.getOperand(1);
3968   SDValue Shamt = Op.getOperand(2);
3969   EVT VT = Lo.getValueType();
3970 
3971   // if Shamt-XLEN < 0: // Shamt < XLEN
3972   //   Lo = Lo << Shamt
3973   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3974   // else:
3975   //   Lo = 0
3976   //   Hi = Lo << (Shamt-XLEN)
3977 
3978   SDValue Zero = DAG.getConstant(0, DL, VT);
3979   SDValue One = DAG.getConstant(1, DL, VT);
3980   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3981   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3982   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3983   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3984 
3985   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3986   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3987   SDValue ShiftRightLo =
3988       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3989   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3990   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3991   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3992 
3993   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3994 
3995   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3996   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3997 
3998   SDValue Parts[2] = {Lo, Hi};
3999   return DAG.getMergeValues(Parts, DL);
4000 }
4001 
4002 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4003                                                   bool IsSRA) const {
4004   SDLoc DL(Op);
4005   SDValue Lo = Op.getOperand(0);
4006   SDValue Hi = Op.getOperand(1);
4007   SDValue Shamt = Op.getOperand(2);
4008   EVT VT = Lo.getValueType();
4009 
4010   // SRA expansion:
4011   //   if Shamt-XLEN < 0: // Shamt < XLEN
4012   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4013   //     Hi = Hi >>s Shamt
4014   //   else:
4015   //     Lo = Hi >>s (Shamt-XLEN);
4016   //     Hi = Hi >>s (XLEN-1)
4017   //
4018   // SRL expansion:
4019   //   if Shamt-XLEN < 0: // Shamt < XLEN
4020   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4021   //     Hi = Hi >>u Shamt
4022   //   else:
4023   //     Lo = Hi >>u (Shamt-XLEN);
4024   //     Hi = 0;
4025 
4026   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4027 
4028   SDValue Zero = DAG.getConstant(0, DL, VT);
4029   SDValue One = DAG.getConstant(1, DL, VT);
4030   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4031   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4032   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4033   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4034 
4035   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4036   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4037   SDValue ShiftLeftHi =
4038       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4039   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4040   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4041   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4042   SDValue HiFalse =
4043       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4044 
4045   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4046 
4047   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4048   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4049 
4050   SDValue Parts[2] = {Lo, Hi};
4051   return DAG.getMergeValues(Parts, DL);
4052 }
4053 
4054 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4055 // legal equivalently-sized i8 type, so we can use that as a go-between.
4056 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4057                                                   SelectionDAG &DAG) const {
4058   SDLoc DL(Op);
4059   MVT VT = Op.getSimpleValueType();
4060   SDValue SplatVal = Op.getOperand(0);
4061   // All-zeros or all-ones splats are handled specially.
4062   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4063     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4064     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4065   }
4066   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4067     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4068     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4069   }
4070   MVT XLenVT = Subtarget.getXLenVT();
4071   assert(SplatVal.getValueType() == XLenVT &&
4072          "Unexpected type for i1 splat value");
4073   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4074   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4075                          DAG.getConstant(1, DL, XLenVT));
4076   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4077   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4078   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4079 }
4080 
4081 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4082 // illegal (currently only vXi64 RV32).
4083 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4084 // them to VMV_V_X_VL.
4085 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4086                                                      SelectionDAG &DAG) const {
4087   SDLoc DL(Op);
4088   MVT VecVT = Op.getSimpleValueType();
4089   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4090          "Unexpected SPLAT_VECTOR_PARTS lowering");
4091 
4092   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4093   SDValue Lo = Op.getOperand(0);
4094   SDValue Hi = Op.getOperand(1);
4095 
4096   if (VecVT.isFixedLengthVector()) {
4097     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4098     SDLoc DL(Op);
4099     SDValue Mask, VL;
4100     std::tie(Mask, VL) =
4101         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4102 
4103     SDValue Res =
4104         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4105     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4106   }
4107 
4108   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4109     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4110     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4111     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4112     // node in order to try and match RVV vector/scalar instructions.
4113     if ((LoC >> 31) == HiC)
4114       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4115                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4116   }
4117 
4118   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4119   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4120       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4121       Hi.getConstantOperandVal(1) == 31)
4122     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4123                        DAG.getRegister(RISCV::X0, MVT::i32));
4124 
4125   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4126   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4127                      DAG.getUNDEF(VecVT), Lo, Hi,
4128                      DAG.getRegister(RISCV::X0, MVT::i32));
4129 }
4130 
4131 // Custom-lower extensions from mask vectors by using a vselect either with 1
4132 // for zero/any-extension or -1 for sign-extension:
4133 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4134 // Note that any-extension is lowered identically to zero-extension.
4135 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4136                                                 int64_t ExtTrueVal) const {
4137   SDLoc DL(Op);
4138   MVT VecVT = Op.getSimpleValueType();
4139   SDValue Src = Op.getOperand(0);
4140   // Only custom-lower extensions from mask types
4141   assert(Src.getValueType().isVector() &&
4142          Src.getValueType().getVectorElementType() == MVT::i1);
4143 
4144   if (VecVT.isScalableVector()) {
4145     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4146     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4147     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4148   }
4149 
4150   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4151   MVT I1ContainerVT =
4152       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4153 
4154   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4155 
4156   SDValue Mask, VL;
4157   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4158 
4159   MVT XLenVT = Subtarget.getXLenVT();
4160   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4161   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4162 
4163   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4164                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4165   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4166                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4167   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4168                                SplatTrueVal, SplatZero, VL);
4169 
4170   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4171 }
4172 
4173 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4174     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4175   MVT ExtVT = Op.getSimpleValueType();
4176   // Only custom-lower extensions from fixed-length vector types.
4177   if (!ExtVT.isFixedLengthVector())
4178     return Op;
4179   MVT VT = Op.getOperand(0).getSimpleValueType();
4180   // Grab the canonical container type for the extended type. Infer the smaller
4181   // type from that to ensure the same number of vector elements, as we know
4182   // the LMUL will be sufficient to hold the smaller type.
4183   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4184   // Get the extended container type manually to ensure the same number of
4185   // vector elements between source and dest.
4186   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4187                                      ContainerExtVT.getVectorElementCount());
4188 
4189   SDValue Op1 =
4190       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4191 
4192   SDLoc DL(Op);
4193   SDValue Mask, VL;
4194   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4195 
4196   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4197 
4198   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4199 }
4200 
4201 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4202 // setcc operation:
4203 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4204 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4205                                                       SelectionDAG &DAG) const {
4206   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4207   SDLoc DL(Op);
4208   EVT MaskVT = Op.getValueType();
4209   // Only expect to custom-lower truncations to mask types
4210   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4211          "Unexpected type for vector mask lowering");
4212   SDValue Src = Op.getOperand(0);
4213   MVT VecVT = Src.getSimpleValueType();
4214   SDValue Mask, VL;
4215   if (IsVPTrunc) {
4216     Mask = Op.getOperand(1);
4217     VL = Op.getOperand(2);
4218   }
4219   // If this is a fixed vector, we need to convert it to a scalable vector.
4220   MVT ContainerVT = VecVT;
4221 
4222   if (VecVT.isFixedLengthVector()) {
4223     ContainerVT = getContainerForFixedLengthVector(VecVT);
4224     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4225     if (IsVPTrunc) {
4226       MVT MaskContainerVT =
4227           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4228       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4229     }
4230   }
4231 
4232   if (!IsVPTrunc) {
4233     std::tie(Mask, VL) =
4234         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4235   }
4236 
4237   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4238   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4239 
4240   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4241                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4242   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4243                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4244 
4245   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4246   SDValue Trunc =
4247       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4248   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4249                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4250   if (MaskVT.isFixedLengthVector())
4251     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4252   return Trunc;
4253 }
4254 
4255 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4256                                                   SelectionDAG &DAG) const {
4257   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4258   SDLoc DL(Op);
4259 
4260   MVT VT = Op.getSimpleValueType();
4261   // Only custom-lower vector truncates
4262   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4263 
4264   // Truncates to mask types are handled differently
4265   if (VT.getVectorElementType() == MVT::i1)
4266     return lowerVectorMaskTruncLike(Op, DAG);
4267 
4268   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4269   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4270   // truncate by one power of two at a time.
4271   MVT DstEltVT = VT.getVectorElementType();
4272 
4273   SDValue Src = Op.getOperand(0);
4274   MVT SrcVT = Src.getSimpleValueType();
4275   MVT SrcEltVT = SrcVT.getVectorElementType();
4276 
4277   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4278          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4279          "Unexpected vector truncate lowering");
4280 
4281   MVT ContainerVT = SrcVT;
4282   SDValue Mask, VL;
4283   if (IsVPTrunc) {
4284     Mask = Op.getOperand(1);
4285     VL = Op.getOperand(2);
4286   }
4287   if (SrcVT.isFixedLengthVector()) {
4288     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4289     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4290     if (IsVPTrunc) {
4291       MVT MaskVT = getMaskTypeFor(ContainerVT);
4292       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4293     }
4294   }
4295 
4296   SDValue Result = Src;
4297   if (!IsVPTrunc) {
4298     std::tie(Mask, VL) =
4299         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4300   }
4301 
4302   LLVMContext &Context = *DAG.getContext();
4303   const ElementCount Count = ContainerVT.getVectorElementCount();
4304   do {
4305     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4306     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4307     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4308                          Mask, VL);
4309   } while (SrcEltVT != DstEltVT);
4310 
4311   if (SrcVT.isFixedLengthVector())
4312     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4313 
4314   return Result;
4315 }
4316 
4317 SDValue
4318 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4319                                                     SelectionDAG &DAG) const {
4320   bool IsVP =
4321       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4322   bool IsExtend =
4323       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4324   // RVV can only do truncate fp to types half the size as the source. We
4325   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4326   // conversion instruction.
4327   SDLoc DL(Op);
4328   MVT VT = Op.getSimpleValueType();
4329 
4330   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4331 
4332   SDValue Src = Op.getOperand(0);
4333   MVT SrcVT = Src.getSimpleValueType();
4334 
4335   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4336                                      SrcVT.getVectorElementType() != MVT::f16);
4337   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4338                                      SrcVT.getVectorElementType() != MVT::f64);
4339 
4340   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4341 
4342   // Prepare any fixed-length vector operands.
4343   MVT ContainerVT = VT;
4344   SDValue Mask, VL;
4345   if (IsVP) {
4346     Mask = Op.getOperand(1);
4347     VL = Op.getOperand(2);
4348   }
4349   if (VT.isFixedLengthVector()) {
4350     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4351     ContainerVT =
4352         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4353     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4354     if (IsVP) {
4355       MVT MaskVT = getMaskTypeFor(ContainerVT);
4356       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4357     }
4358   }
4359 
4360   if (!IsVP)
4361     std::tie(Mask, VL) =
4362         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4363 
4364   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4365 
4366   if (IsDirectConv) {
4367     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4368     if (VT.isFixedLengthVector())
4369       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4370     return Src;
4371   }
4372 
4373   unsigned InterConvOpc =
4374       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4375 
4376   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4377   SDValue IntermediateConv =
4378       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4379   SDValue Result =
4380       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4381   if (VT.isFixedLengthVector())
4382     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4383   return Result;
4384 }
4385 
4386 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4387 // first position of a vector, and that vector is slid up to the insert index.
4388 // By limiting the active vector length to index+1 and merging with the
4389 // original vector (with an undisturbed tail policy for elements >= VL), we
4390 // achieve the desired result of leaving all elements untouched except the one
4391 // at VL-1, which is replaced with the desired value.
4392 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4393                                                     SelectionDAG &DAG) const {
4394   SDLoc DL(Op);
4395   MVT VecVT = Op.getSimpleValueType();
4396   SDValue Vec = Op.getOperand(0);
4397   SDValue Val = Op.getOperand(1);
4398   SDValue Idx = Op.getOperand(2);
4399 
4400   if (VecVT.getVectorElementType() == MVT::i1) {
4401     // FIXME: For now we just promote to an i8 vector and insert into that,
4402     // but this is probably not optimal.
4403     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4404     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4405     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4406     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4407   }
4408 
4409   MVT ContainerVT = VecVT;
4410   // If the operand is a fixed-length vector, convert to a scalable one.
4411   if (VecVT.isFixedLengthVector()) {
4412     ContainerVT = getContainerForFixedLengthVector(VecVT);
4413     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4414   }
4415 
4416   MVT XLenVT = Subtarget.getXLenVT();
4417 
4418   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4419   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4420   // Even i64-element vectors on RV32 can be lowered without scalar
4421   // legalization if the most-significant 32 bits of the value are not affected
4422   // by the sign-extension of the lower 32 bits.
4423   // TODO: We could also catch sign extensions of a 32-bit value.
4424   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4425     const auto *CVal = cast<ConstantSDNode>(Val);
4426     if (isInt<32>(CVal->getSExtValue())) {
4427       IsLegalInsert = true;
4428       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4429     }
4430   }
4431 
4432   SDValue Mask, VL;
4433   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4434 
4435   SDValue ValInVec;
4436 
4437   if (IsLegalInsert) {
4438     unsigned Opc =
4439         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4440     if (isNullConstant(Idx)) {
4441       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4442       if (!VecVT.isFixedLengthVector())
4443         return Vec;
4444       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4445     }
4446     ValInVec =
4447         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4448   } else {
4449     // On RV32, i64-element vectors must be specially handled to place the
4450     // value at element 0, by using two vslide1up instructions in sequence on
4451     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4452     // this.
4453     SDValue One = DAG.getConstant(1, DL, XLenVT);
4454     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4455     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4456     MVT I32ContainerVT =
4457         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4458     SDValue I32Mask =
4459         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4460     // Limit the active VL to two.
4461     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4462     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4463     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4464     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4465                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4466     // First slide in the hi value, then the lo in underneath it.
4467     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4468                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4469                            I32Mask, InsertI64VL);
4470     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4471                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4472                            I32Mask, InsertI64VL);
4473     // Bitcast back to the right container type.
4474     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4475   }
4476 
4477   // Now that the value is in a vector, slide it into position.
4478   SDValue InsertVL =
4479       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4480   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4481                                 ValInVec, Idx, Mask, InsertVL);
4482   if (!VecVT.isFixedLengthVector())
4483     return Slideup;
4484   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4485 }
4486 
4487 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4488 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4489 // types this is done using VMV_X_S to allow us to glean information about the
4490 // sign bits of the result.
4491 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4492                                                      SelectionDAG &DAG) const {
4493   SDLoc DL(Op);
4494   SDValue Idx = Op.getOperand(1);
4495   SDValue Vec = Op.getOperand(0);
4496   EVT EltVT = Op.getValueType();
4497   MVT VecVT = Vec.getSimpleValueType();
4498   MVT XLenVT = Subtarget.getXLenVT();
4499 
4500   if (VecVT.getVectorElementType() == MVT::i1) {
4501     if (VecVT.isFixedLengthVector()) {
4502       unsigned NumElts = VecVT.getVectorNumElements();
4503       if (NumElts >= 8) {
4504         MVT WideEltVT;
4505         unsigned WidenVecLen;
4506         SDValue ExtractElementIdx;
4507         SDValue ExtractBitIdx;
4508         unsigned MaxEEW = Subtarget.getELEN();
4509         MVT LargestEltVT = MVT::getIntegerVT(
4510             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4511         if (NumElts <= LargestEltVT.getSizeInBits()) {
4512           assert(isPowerOf2_32(NumElts) &&
4513                  "the number of elements should be power of 2");
4514           WideEltVT = MVT::getIntegerVT(NumElts);
4515           WidenVecLen = 1;
4516           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4517           ExtractBitIdx = Idx;
4518         } else {
4519           WideEltVT = LargestEltVT;
4520           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4521           // extract element index = index / element width
4522           ExtractElementIdx = DAG.getNode(
4523               ISD::SRL, DL, XLenVT, Idx,
4524               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4525           // mask bit index = index % element width
4526           ExtractBitIdx = DAG.getNode(
4527               ISD::AND, DL, XLenVT, Idx,
4528               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4529         }
4530         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4531         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4532         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4533                                          Vec, ExtractElementIdx);
4534         // Extract the bit from GPR.
4535         SDValue ShiftRight =
4536             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4537         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4538                            DAG.getConstant(1, DL, XLenVT));
4539       }
4540     }
4541     // Otherwise, promote to an i8 vector and extract from that.
4542     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4543     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4544     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4545   }
4546 
4547   // If this is a fixed vector, we need to convert it to a scalable vector.
4548   MVT ContainerVT = VecVT;
4549   if (VecVT.isFixedLengthVector()) {
4550     ContainerVT = getContainerForFixedLengthVector(VecVT);
4551     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4552   }
4553 
4554   // If the index is 0, the vector is already in the right position.
4555   if (!isNullConstant(Idx)) {
4556     // Use a VL of 1 to avoid processing more elements than we need.
4557     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4558     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4559     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4560                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4561   }
4562 
4563   if (!EltVT.isInteger()) {
4564     // Floating-point extracts are handled in TableGen.
4565     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4566                        DAG.getConstant(0, DL, XLenVT));
4567   }
4568 
4569   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4570   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4571 }
4572 
4573 // Some RVV intrinsics may claim that they want an integer operand to be
4574 // promoted or expanded.
4575 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4576                                            const RISCVSubtarget &Subtarget) {
4577   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4578           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4579          "Unexpected opcode");
4580 
4581   if (!Subtarget.hasVInstructions())
4582     return SDValue();
4583 
4584   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4585   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4586   SDLoc DL(Op);
4587 
4588   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4589       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4590   if (!II || !II->hasScalarOperand())
4591     return SDValue();
4592 
4593   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4594   assert(SplatOp < Op.getNumOperands());
4595 
4596   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4597   SDValue &ScalarOp = Operands[SplatOp];
4598   MVT OpVT = ScalarOp.getSimpleValueType();
4599   MVT XLenVT = Subtarget.getXLenVT();
4600 
4601   // If this isn't a scalar, or its type is XLenVT we're done.
4602   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4603     return SDValue();
4604 
4605   // Simplest case is that the operand needs to be promoted to XLenVT.
4606   if (OpVT.bitsLT(XLenVT)) {
4607     // If the operand is a constant, sign extend to increase our chances
4608     // of being able to use a .vi instruction. ANY_EXTEND would become a
4609     // a zero extend and the simm5 check in isel would fail.
4610     // FIXME: Should we ignore the upper bits in isel instead?
4611     unsigned ExtOpc =
4612         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4613     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4614     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4615   }
4616 
4617   // Use the previous operand to get the vXi64 VT. The result might be a mask
4618   // VT for compares. Using the previous operand assumes that the previous
4619   // operand will never have a smaller element size than a scalar operand and
4620   // that a widening operation never uses SEW=64.
4621   // NOTE: If this fails the below assert, we can probably just find the
4622   // element count from any operand or result and use it to construct the VT.
4623   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4624   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4625 
4626   // The more complex case is when the scalar is larger than XLenVT.
4627   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4628          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4629 
4630   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4631   // instruction to sign-extend since SEW>XLEN.
4632   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4633     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4634     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4635   }
4636 
4637   switch (IntNo) {
4638   case Intrinsic::riscv_vslide1up:
4639   case Intrinsic::riscv_vslide1down:
4640   case Intrinsic::riscv_vslide1up_mask:
4641   case Intrinsic::riscv_vslide1down_mask: {
4642     // We need to special case these when the scalar is larger than XLen.
4643     unsigned NumOps = Op.getNumOperands();
4644     bool IsMasked = NumOps == 7;
4645 
4646     // Convert the vector source to the equivalent nxvXi32 vector.
4647     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4648     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4649 
4650     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4651                                    DAG.getConstant(0, DL, XLenVT));
4652     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4653                                    DAG.getConstant(1, DL, XLenVT));
4654 
4655     // Double the VL since we halved SEW.
4656     SDValue AVL = getVLOperand(Op);
4657     SDValue I32VL;
4658 
4659     // Optimize for constant AVL
4660     if (isa<ConstantSDNode>(AVL)) {
4661       unsigned EltSize = VT.getScalarSizeInBits();
4662       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4663 
4664       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4665       unsigned MaxVLMAX =
4666           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4667 
4668       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4669       unsigned MinVLMAX =
4670           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4671 
4672       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4673       if (AVLInt <= MinVLMAX) {
4674         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4675       } else if (AVLInt >= 2 * MaxVLMAX) {
4676         // Just set vl to VLMAX in this situation
4677         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4678         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4679         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4680         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4681         SDValue SETVLMAX = DAG.getTargetConstant(
4682             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4683         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4684                             LMUL);
4685       } else {
4686         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4687         // is related to the hardware implementation.
4688         // So let the following code handle
4689       }
4690     }
4691     if (!I32VL) {
4692       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4693       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4694       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4695       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4696       SDValue SETVL =
4697           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4698       // Using vsetvli instruction to get actually used length which related to
4699       // the hardware implementation
4700       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4701                                SEW, LMUL);
4702       I32VL =
4703           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4704     }
4705 
4706     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4707 
4708     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4709     // instructions.
4710     SDValue Passthru;
4711     if (IsMasked)
4712       Passthru = DAG.getUNDEF(I32VT);
4713     else
4714       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4715 
4716     if (IntNo == Intrinsic::riscv_vslide1up ||
4717         IntNo == Intrinsic::riscv_vslide1up_mask) {
4718       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4719                         ScalarHi, I32Mask, I32VL);
4720       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4721                         ScalarLo, I32Mask, I32VL);
4722     } else {
4723       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4724                         ScalarLo, I32Mask, I32VL);
4725       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4726                         ScalarHi, I32Mask, I32VL);
4727     }
4728 
4729     // Convert back to nxvXi64.
4730     Vec = DAG.getBitcast(VT, Vec);
4731 
4732     if (!IsMasked)
4733       return Vec;
4734     // Apply mask after the operation.
4735     SDValue Mask = Operands[NumOps - 3];
4736     SDValue MaskedOff = Operands[1];
4737     // Assume Policy operand is the last operand.
4738     uint64_t Policy =
4739         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4740     // We don't need to select maskedoff if it's undef.
4741     if (MaskedOff.isUndef())
4742       return Vec;
4743     // TAMU
4744     if (Policy == RISCVII::TAIL_AGNOSTIC)
4745       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4746                          AVL);
4747     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4748     // It's fine because vmerge does not care mask policy.
4749     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4750                        AVL);
4751   }
4752   }
4753 
4754   // We need to convert the scalar to a splat vector.
4755   SDValue VL = getVLOperand(Op);
4756   assert(VL.getValueType() == XLenVT);
4757   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4758   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4759 }
4760 
4761 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4762                                                      SelectionDAG &DAG) const {
4763   unsigned IntNo = Op.getConstantOperandVal(0);
4764   SDLoc DL(Op);
4765   MVT XLenVT = Subtarget.getXLenVT();
4766 
4767   switch (IntNo) {
4768   default:
4769     break; // Don't custom lower most intrinsics.
4770   case Intrinsic::thread_pointer: {
4771     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4772     return DAG.getRegister(RISCV::X4, PtrVT);
4773   }
4774   case Intrinsic::riscv_orc_b:
4775   case Intrinsic::riscv_brev8: {
4776     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4777     unsigned Opc =
4778         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4779     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4780                        DAG.getConstant(7, DL, XLenVT));
4781   }
4782   case Intrinsic::riscv_grev:
4783   case Intrinsic::riscv_gorc: {
4784     unsigned Opc =
4785         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4786     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4787   }
4788   case Intrinsic::riscv_zip:
4789   case Intrinsic::riscv_unzip: {
4790     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4791     // For i32 the immediate is 15. For i64 the immediate is 31.
4792     unsigned Opc =
4793         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4794     unsigned BitWidth = Op.getValueSizeInBits();
4795     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4796     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4797                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4798   }
4799   case Intrinsic::riscv_shfl:
4800   case Intrinsic::riscv_unshfl: {
4801     unsigned Opc =
4802         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4803     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4804   }
4805   case Intrinsic::riscv_bcompress:
4806   case Intrinsic::riscv_bdecompress: {
4807     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4808                                                        : RISCVISD::BDECOMPRESS;
4809     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4810   }
4811   case Intrinsic::riscv_bfp:
4812     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4813                        Op.getOperand(2));
4814   case Intrinsic::riscv_fsl:
4815     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4816                        Op.getOperand(2), Op.getOperand(3));
4817   case Intrinsic::riscv_fsr:
4818     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4819                        Op.getOperand(2), Op.getOperand(3));
4820   case Intrinsic::riscv_vmv_x_s:
4821     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4822     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4823                        Op.getOperand(1));
4824   case Intrinsic::riscv_vmv_v_x:
4825     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4826                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4827                             Subtarget);
4828   case Intrinsic::riscv_vfmv_v_f:
4829     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4830                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4831   case Intrinsic::riscv_vmv_s_x: {
4832     SDValue Scalar = Op.getOperand(2);
4833 
4834     if (Scalar.getValueType().bitsLE(XLenVT)) {
4835       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4836       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4837                          Op.getOperand(1), Scalar, Op.getOperand(3));
4838     }
4839 
4840     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4841 
4842     // This is an i64 value that lives in two scalar registers. We have to
4843     // insert this in a convoluted way. First we build vXi64 splat containing
4844     // the two values that we assemble using some bit math. Next we'll use
4845     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4846     // to merge element 0 from our splat into the source vector.
4847     // FIXME: This is probably not the best way to do this, but it is
4848     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4849     // point.
4850     //   sw lo, (a0)
4851     //   sw hi, 4(a0)
4852     //   vlse vX, (a0)
4853     //
4854     //   vid.v      vVid
4855     //   vmseq.vx   mMask, vVid, 0
4856     //   vmerge.vvm vDest, vSrc, vVal, mMask
4857     MVT VT = Op.getSimpleValueType();
4858     SDValue Vec = Op.getOperand(1);
4859     SDValue VL = getVLOperand(Op);
4860 
4861     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4862     if (Op.getOperand(1).isUndef())
4863       return SplattedVal;
4864     SDValue SplattedIdx =
4865         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4866                     DAG.getConstant(0, DL, MVT::i32), VL);
4867 
4868     MVT MaskVT = getMaskTypeFor(VT);
4869     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4870     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4871     SDValue SelectCond =
4872         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4873                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4874     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4875                        Vec, VL);
4876   }
4877   }
4878 
4879   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4880 }
4881 
4882 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4883                                                     SelectionDAG &DAG) const {
4884   unsigned IntNo = Op.getConstantOperandVal(1);
4885   switch (IntNo) {
4886   default:
4887     break;
4888   case Intrinsic::riscv_masked_strided_load: {
4889     SDLoc DL(Op);
4890     MVT XLenVT = Subtarget.getXLenVT();
4891 
4892     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4893     // the selection of the masked intrinsics doesn't do this for us.
4894     SDValue Mask = Op.getOperand(5);
4895     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4896 
4897     MVT VT = Op->getSimpleValueType(0);
4898     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4899 
4900     SDValue PassThru = Op.getOperand(2);
4901     if (!IsUnmasked) {
4902       MVT MaskVT = getMaskTypeFor(ContainerVT);
4903       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4904       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4905     }
4906 
4907     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4908 
4909     SDValue IntID = DAG.getTargetConstant(
4910         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4911         XLenVT);
4912 
4913     auto *Load = cast<MemIntrinsicSDNode>(Op);
4914     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4915     if (IsUnmasked)
4916       Ops.push_back(DAG.getUNDEF(ContainerVT));
4917     else
4918       Ops.push_back(PassThru);
4919     Ops.push_back(Op.getOperand(3)); // Ptr
4920     Ops.push_back(Op.getOperand(4)); // Stride
4921     if (!IsUnmasked)
4922       Ops.push_back(Mask);
4923     Ops.push_back(VL);
4924     if (!IsUnmasked) {
4925       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4926       Ops.push_back(Policy);
4927     }
4928 
4929     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4930     SDValue Result =
4931         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4932                                 Load->getMemoryVT(), Load->getMemOperand());
4933     SDValue Chain = Result.getValue(1);
4934     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4935     return DAG.getMergeValues({Result, Chain}, DL);
4936   }
4937   case Intrinsic::riscv_seg2_load:
4938   case Intrinsic::riscv_seg3_load:
4939   case Intrinsic::riscv_seg4_load:
4940   case Intrinsic::riscv_seg5_load:
4941   case Intrinsic::riscv_seg6_load:
4942   case Intrinsic::riscv_seg7_load:
4943   case Intrinsic::riscv_seg8_load: {
4944     SDLoc DL(Op);
4945     static const Intrinsic::ID VlsegInts[7] = {
4946         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4947         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4948         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4949         Intrinsic::riscv_vlseg8};
4950     unsigned NF = Op->getNumValues() - 1;
4951     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4952     MVT XLenVT = Subtarget.getXLenVT();
4953     MVT VT = Op->getSimpleValueType(0);
4954     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4955 
4956     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4957     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4958     auto *Load = cast<MemIntrinsicSDNode>(Op);
4959     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4960     ContainerVTs.push_back(MVT::Other);
4961     SDVTList VTs = DAG.getVTList(ContainerVTs);
4962     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
4963     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
4964     Ops.push_back(Op.getOperand(2));
4965     Ops.push_back(VL);
4966     SDValue Result =
4967         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4968                                 Load->getMemoryVT(), Load->getMemOperand());
4969     SmallVector<SDValue, 9> Results;
4970     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4971       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4972                                                   DAG, Subtarget));
4973     Results.push_back(Result.getValue(NF));
4974     return DAG.getMergeValues(Results, DL);
4975   }
4976   }
4977 
4978   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4979 }
4980 
4981 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4982                                                  SelectionDAG &DAG) const {
4983   unsigned IntNo = Op.getConstantOperandVal(1);
4984   switch (IntNo) {
4985   default:
4986     break;
4987   case Intrinsic::riscv_masked_strided_store: {
4988     SDLoc DL(Op);
4989     MVT XLenVT = Subtarget.getXLenVT();
4990 
4991     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4992     // the selection of the masked intrinsics doesn't do this for us.
4993     SDValue Mask = Op.getOperand(5);
4994     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4995 
4996     SDValue Val = Op.getOperand(2);
4997     MVT VT = Val.getSimpleValueType();
4998     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4999 
5000     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5001     if (!IsUnmasked) {
5002       MVT MaskVT = getMaskTypeFor(ContainerVT);
5003       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5004     }
5005 
5006     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5007 
5008     SDValue IntID = DAG.getTargetConstant(
5009         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5010         XLenVT);
5011 
5012     auto *Store = cast<MemIntrinsicSDNode>(Op);
5013     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5014     Ops.push_back(Val);
5015     Ops.push_back(Op.getOperand(3)); // Ptr
5016     Ops.push_back(Op.getOperand(4)); // Stride
5017     if (!IsUnmasked)
5018       Ops.push_back(Mask);
5019     Ops.push_back(VL);
5020 
5021     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5022                                    Ops, Store->getMemoryVT(),
5023                                    Store->getMemOperand());
5024   }
5025   }
5026 
5027   return SDValue();
5028 }
5029 
5030 static MVT getLMUL1VT(MVT VT) {
5031   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5032          "Unexpected vector MVT");
5033   return MVT::getScalableVectorVT(
5034       VT.getVectorElementType(),
5035       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5036 }
5037 
5038 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5039   switch (ISDOpcode) {
5040   default:
5041     llvm_unreachable("Unhandled reduction");
5042   case ISD::VECREDUCE_ADD:
5043     return RISCVISD::VECREDUCE_ADD_VL;
5044   case ISD::VECREDUCE_UMAX:
5045     return RISCVISD::VECREDUCE_UMAX_VL;
5046   case ISD::VECREDUCE_SMAX:
5047     return RISCVISD::VECREDUCE_SMAX_VL;
5048   case ISD::VECREDUCE_UMIN:
5049     return RISCVISD::VECREDUCE_UMIN_VL;
5050   case ISD::VECREDUCE_SMIN:
5051     return RISCVISD::VECREDUCE_SMIN_VL;
5052   case ISD::VECREDUCE_AND:
5053     return RISCVISD::VECREDUCE_AND_VL;
5054   case ISD::VECREDUCE_OR:
5055     return RISCVISD::VECREDUCE_OR_VL;
5056   case ISD::VECREDUCE_XOR:
5057     return RISCVISD::VECREDUCE_XOR_VL;
5058   }
5059 }
5060 
5061 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5062                                                          SelectionDAG &DAG,
5063                                                          bool IsVP) const {
5064   SDLoc DL(Op);
5065   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5066   MVT VecVT = Vec.getSimpleValueType();
5067   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5068           Op.getOpcode() == ISD::VECREDUCE_OR ||
5069           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5070           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5071           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5072           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5073          "Unexpected reduction lowering");
5074 
5075   MVT XLenVT = Subtarget.getXLenVT();
5076   assert(Op.getValueType() == XLenVT &&
5077          "Expected reduction output to be legalized to XLenVT");
5078 
5079   MVT ContainerVT = VecVT;
5080   if (VecVT.isFixedLengthVector()) {
5081     ContainerVT = getContainerForFixedLengthVector(VecVT);
5082     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5083   }
5084 
5085   SDValue Mask, VL;
5086   if (IsVP) {
5087     Mask = Op.getOperand(2);
5088     VL = Op.getOperand(3);
5089   } else {
5090     std::tie(Mask, VL) =
5091         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5092   }
5093 
5094   unsigned BaseOpc;
5095   ISD::CondCode CC;
5096   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5097 
5098   switch (Op.getOpcode()) {
5099   default:
5100     llvm_unreachable("Unhandled reduction");
5101   case ISD::VECREDUCE_AND:
5102   case ISD::VP_REDUCE_AND: {
5103     // vcpop ~x == 0
5104     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5105     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5106     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5107     CC = ISD::SETEQ;
5108     BaseOpc = ISD::AND;
5109     break;
5110   }
5111   case ISD::VECREDUCE_OR:
5112   case ISD::VP_REDUCE_OR:
5113     // vcpop x != 0
5114     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5115     CC = ISD::SETNE;
5116     BaseOpc = ISD::OR;
5117     break;
5118   case ISD::VECREDUCE_XOR:
5119   case ISD::VP_REDUCE_XOR: {
5120     // ((vcpop x) & 1) != 0
5121     SDValue One = DAG.getConstant(1, DL, XLenVT);
5122     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5123     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5124     CC = ISD::SETNE;
5125     BaseOpc = ISD::XOR;
5126     break;
5127   }
5128   }
5129 
5130   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5131 
5132   if (!IsVP)
5133     return SetCC;
5134 
5135   // Now include the start value in the operation.
5136   // Note that we must return the start value when no elements are operated
5137   // upon. The vcpop instructions we've emitted in each case above will return
5138   // 0 for an inactive vector, and so we've already received the neutral value:
5139   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5140   // can simply include the start value.
5141   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5142 }
5143 
5144 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5145                                             SelectionDAG &DAG) const {
5146   SDLoc DL(Op);
5147   SDValue Vec = Op.getOperand(0);
5148   EVT VecEVT = Vec.getValueType();
5149 
5150   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5151 
5152   // Due to ordering in legalize types we may have a vector type that needs to
5153   // be split. Do that manually so we can get down to a legal type.
5154   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5155          TargetLowering::TypeSplitVector) {
5156     SDValue Lo, Hi;
5157     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5158     VecEVT = Lo.getValueType();
5159     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5160   }
5161 
5162   // TODO: The type may need to be widened rather than split. Or widened before
5163   // it can be split.
5164   if (!isTypeLegal(VecEVT))
5165     return SDValue();
5166 
5167   MVT VecVT = VecEVT.getSimpleVT();
5168   MVT VecEltVT = VecVT.getVectorElementType();
5169   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5170 
5171   MVT ContainerVT = VecVT;
5172   if (VecVT.isFixedLengthVector()) {
5173     ContainerVT = getContainerForFixedLengthVector(VecVT);
5174     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5175   }
5176 
5177   MVT M1VT = getLMUL1VT(ContainerVT);
5178   MVT XLenVT = Subtarget.getXLenVT();
5179 
5180   SDValue Mask, VL;
5181   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5182 
5183   SDValue NeutralElem =
5184       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5185   SDValue IdentitySplat =
5186       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5187                        M1VT, DL, DAG, Subtarget);
5188   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5189                                   IdentitySplat, Mask, VL);
5190   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5191                              DAG.getConstant(0, DL, XLenVT));
5192   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5193 }
5194 
5195 // Given a reduction op, this function returns the matching reduction opcode,
5196 // the vector SDValue and the scalar SDValue required to lower this to a
5197 // RISCVISD node.
5198 static std::tuple<unsigned, SDValue, SDValue>
5199 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5200   SDLoc DL(Op);
5201   auto Flags = Op->getFlags();
5202   unsigned Opcode = Op.getOpcode();
5203   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5204   switch (Opcode) {
5205   default:
5206     llvm_unreachable("Unhandled reduction");
5207   case ISD::VECREDUCE_FADD: {
5208     // Use positive zero if we can. It is cheaper to materialize.
5209     SDValue Zero =
5210         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5211     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5212   }
5213   case ISD::VECREDUCE_SEQ_FADD:
5214     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5215                            Op.getOperand(0));
5216   case ISD::VECREDUCE_FMIN:
5217     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5218                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5219   case ISD::VECREDUCE_FMAX:
5220     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5221                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5222   }
5223 }
5224 
5225 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5226                                               SelectionDAG &DAG) const {
5227   SDLoc DL(Op);
5228   MVT VecEltVT = Op.getSimpleValueType();
5229 
5230   unsigned RVVOpcode;
5231   SDValue VectorVal, ScalarVal;
5232   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5233       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5234   MVT VecVT = VectorVal.getSimpleValueType();
5235 
5236   MVT ContainerVT = VecVT;
5237   if (VecVT.isFixedLengthVector()) {
5238     ContainerVT = getContainerForFixedLengthVector(VecVT);
5239     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5240   }
5241 
5242   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5243   MVT XLenVT = Subtarget.getXLenVT();
5244 
5245   SDValue Mask, VL;
5246   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5247 
5248   SDValue ScalarSplat =
5249       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5250                        M1VT, DL, DAG, Subtarget);
5251   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5252                                   VectorVal, ScalarSplat, Mask, VL);
5253   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5254                      DAG.getConstant(0, DL, XLenVT));
5255 }
5256 
5257 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5258   switch (ISDOpcode) {
5259   default:
5260     llvm_unreachable("Unhandled reduction");
5261   case ISD::VP_REDUCE_ADD:
5262     return RISCVISD::VECREDUCE_ADD_VL;
5263   case ISD::VP_REDUCE_UMAX:
5264     return RISCVISD::VECREDUCE_UMAX_VL;
5265   case ISD::VP_REDUCE_SMAX:
5266     return RISCVISD::VECREDUCE_SMAX_VL;
5267   case ISD::VP_REDUCE_UMIN:
5268     return RISCVISD::VECREDUCE_UMIN_VL;
5269   case ISD::VP_REDUCE_SMIN:
5270     return RISCVISD::VECREDUCE_SMIN_VL;
5271   case ISD::VP_REDUCE_AND:
5272     return RISCVISD::VECREDUCE_AND_VL;
5273   case ISD::VP_REDUCE_OR:
5274     return RISCVISD::VECREDUCE_OR_VL;
5275   case ISD::VP_REDUCE_XOR:
5276     return RISCVISD::VECREDUCE_XOR_VL;
5277   case ISD::VP_REDUCE_FADD:
5278     return RISCVISD::VECREDUCE_FADD_VL;
5279   case ISD::VP_REDUCE_SEQ_FADD:
5280     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5281   case ISD::VP_REDUCE_FMAX:
5282     return RISCVISD::VECREDUCE_FMAX_VL;
5283   case ISD::VP_REDUCE_FMIN:
5284     return RISCVISD::VECREDUCE_FMIN_VL;
5285   }
5286 }
5287 
5288 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5289                                            SelectionDAG &DAG) const {
5290   SDLoc DL(Op);
5291   SDValue Vec = Op.getOperand(1);
5292   EVT VecEVT = Vec.getValueType();
5293 
5294   // TODO: The type may need to be widened rather than split. Or widened before
5295   // it can be split.
5296   if (!isTypeLegal(VecEVT))
5297     return SDValue();
5298 
5299   MVT VecVT = VecEVT.getSimpleVT();
5300   MVT VecEltVT = VecVT.getVectorElementType();
5301   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5302 
5303   MVT ContainerVT = VecVT;
5304   if (VecVT.isFixedLengthVector()) {
5305     ContainerVT = getContainerForFixedLengthVector(VecVT);
5306     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5307   }
5308 
5309   SDValue VL = Op.getOperand(3);
5310   SDValue Mask = Op.getOperand(2);
5311 
5312   MVT M1VT = getLMUL1VT(ContainerVT);
5313   MVT XLenVT = Subtarget.getXLenVT();
5314   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5315 
5316   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5317                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5318                                         DL, DAG, Subtarget);
5319   SDValue Reduction =
5320       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5321   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5322                              DAG.getConstant(0, DL, XLenVT));
5323   if (!VecVT.isInteger())
5324     return Elt0;
5325   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5326 }
5327 
5328 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5329                                                    SelectionDAG &DAG) const {
5330   SDValue Vec = Op.getOperand(0);
5331   SDValue SubVec = Op.getOperand(1);
5332   MVT VecVT = Vec.getSimpleValueType();
5333   MVT SubVecVT = SubVec.getSimpleValueType();
5334 
5335   SDLoc DL(Op);
5336   MVT XLenVT = Subtarget.getXLenVT();
5337   unsigned OrigIdx = Op.getConstantOperandVal(2);
5338   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5339 
5340   // We don't have the ability to slide mask vectors up indexed by their i1
5341   // elements; the smallest we can do is i8. Often we are able to bitcast to
5342   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5343   // into a scalable one, we might not necessarily have enough scalable
5344   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5345   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5346       (OrigIdx != 0 || !Vec.isUndef())) {
5347     if (VecVT.getVectorMinNumElements() >= 8 &&
5348         SubVecVT.getVectorMinNumElements() >= 8) {
5349       assert(OrigIdx % 8 == 0 && "Invalid index");
5350       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5351              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5352              "Unexpected mask vector lowering");
5353       OrigIdx /= 8;
5354       SubVecVT =
5355           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5356                            SubVecVT.isScalableVector());
5357       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5358                                VecVT.isScalableVector());
5359       Vec = DAG.getBitcast(VecVT, Vec);
5360       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5361     } else {
5362       // We can't slide this mask vector up indexed by its i1 elements.
5363       // This poses a problem when we wish to insert a scalable vector which
5364       // can't be re-expressed as a larger type. Just choose the slow path and
5365       // extend to a larger type, then truncate back down.
5366       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5367       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5368       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5369       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5370       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5371                         Op.getOperand(2));
5372       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5373       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5374     }
5375   }
5376 
5377   // If the subvector vector is a fixed-length type, we cannot use subregister
5378   // manipulation to simplify the codegen; we don't know which register of a
5379   // LMUL group contains the specific subvector as we only know the minimum
5380   // register size. Therefore we must slide the vector group up the full
5381   // amount.
5382   if (SubVecVT.isFixedLengthVector()) {
5383     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5384       return Op;
5385     MVT ContainerVT = VecVT;
5386     if (VecVT.isFixedLengthVector()) {
5387       ContainerVT = getContainerForFixedLengthVector(VecVT);
5388       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5389     }
5390     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5391                          DAG.getUNDEF(ContainerVT), SubVec,
5392                          DAG.getConstant(0, DL, XLenVT));
5393     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5394       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5395       return DAG.getBitcast(Op.getValueType(), SubVec);
5396     }
5397     SDValue Mask =
5398         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5399     // Set the vector length to only the number of elements we care about. Note
5400     // that for slideup this includes the offset.
5401     SDValue VL =
5402         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5403     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5404     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5405                                   SubVec, SlideupAmt, Mask, VL);
5406     if (VecVT.isFixedLengthVector())
5407       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5408     return DAG.getBitcast(Op.getValueType(), Slideup);
5409   }
5410 
5411   unsigned SubRegIdx, RemIdx;
5412   std::tie(SubRegIdx, RemIdx) =
5413       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5414           VecVT, SubVecVT, OrigIdx, TRI);
5415 
5416   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5417   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5418                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5419                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5420 
5421   // 1. If the Idx has been completely eliminated and this subvector's size is
5422   // a vector register or a multiple thereof, or the surrounding elements are
5423   // undef, then this is a subvector insert which naturally aligns to a vector
5424   // register. These can easily be handled using subregister manipulation.
5425   // 2. If the subvector is smaller than a vector register, then the insertion
5426   // must preserve the undisturbed elements of the register. We do this by
5427   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5428   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5429   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5430   // LMUL=1 type back into the larger vector (resolving to another subregister
5431   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5432   // to avoid allocating a large register group to hold our subvector.
5433   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5434     return Op;
5435 
5436   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5437   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5438   // (in our case undisturbed). This means we can set up a subvector insertion
5439   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5440   // size of the subvector.
5441   MVT InterSubVT = VecVT;
5442   SDValue AlignedExtract = Vec;
5443   unsigned AlignedIdx = OrigIdx - RemIdx;
5444   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5445     InterSubVT = getLMUL1VT(VecVT);
5446     // Extract a subvector equal to the nearest full vector register type. This
5447     // should resolve to a EXTRACT_SUBREG instruction.
5448     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5449                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5450   }
5451 
5452   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5453   // For scalable vectors this must be further multiplied by vscale.
5454   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5455 
5456   SDValue Mask, VL;
5457   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5458 
5459   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5460   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5461   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5462   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5463 
5464   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5465                        DAG.getUNDEF(InterSubVT), SubVec,
5466                        DAG.getConstant(0, DL, XLenVT));
5467 
5468   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5469                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5470 
5471   // If required, insert this subvector back into the correct vector register.
5472   // This should resolve to an INSERT_SUBREG instruction.
5473   if (VecVT.bitsGT(InterSubVT))
5474     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5475                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5476 
5477   // We might have bitcast from a mask type: cast back to the original type if
5478   // required.
5479   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5480 }
5481 
5482 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5483                                                     SelectionDAG &DAG) const {
5484   SDValue Vec = Op.getOperand(0);
5485   MVT SubVecVT = Op.getSimpleValueType();
5486   MVT VecVT = Vec.getSimpleValueType();
5487 
5488   SDLoc DL(Op);
5489   MVT XLenVT = Subtarget.getXLenVT();
5490   unsigned OrigIdx = Op.getConstantOperandVal(1);
5491   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5492 
5493   // We don't have the ability to slide mask vectors down indexed by their i1
5494   // elements; the smallest we can do is i8. Often we are able to bitcast to
5495   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5496   // from a scalable one, we might not necessarily have enough scalable
5497   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5498   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5499     if (VecVT.getVectorMinNumElements() >= 8 &&
5500         SubVecVT.getVectorMinNumElements() >= 8) {
5501       assert(OrigIdx % 8 == 0 && "Invalid index");
5502       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5503              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5504              "Unexpected mask vector lowering");
5505       OrigIdx /= 8;
5506       SubVecVT =
5507           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5508                            SubVecVT.isScalableVector());
5509       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5510                                VecVT.isScalableVector());
5511       Vec = DAG.getBitcast(VecVT, Vec);
5512     } else {
5513       // We can't slide this mask vector down, indexed by its i1 elements.
5514       // This poses a problem when we wish to extract a scalable vector which
5515       // can't be re-expressed as a larger type. Just choose the slow path and
5516       // extend to a larger type, then truncate back down.
5517       // TODO: We could probably improve this when extracting certain fixed
5518       // from fixed, where we can extract as i8 and shift the correct element
5519       // right to reach the desired subvector?
5520       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5521       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5522       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5523       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5524                         Op.getOperand(1));
5525       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5526       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5527     }
5528   }
5529 
5530   // If the subvector vector is a fixed-length type, we cannot use subregister
5531   // manipulation to simplify the codegen; we don't know which register of a
5532   // LMUL group contains the specific subvector as we only know the minimum
5533   // register size. Therefore we must slide the vector group down the full
5534   // amount.
5535   if (SubVecVT.isFixedLengthVector()) {
5536     // With an index of 0 this is a cast-like subvector, which can be performed
5537     // with subregister operations.
5538     if (OrigIdx == 0)
5539       return Op;
5540     MVT ContainerVT = VecVT;
5541     if (VecVT.isFixedLengthVector()) {
5542       ContainerVT = getContainerForFixedLengthVector(VecVT);
5543       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5544     }
5545     SDValue Mask =
5546         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5547     // Set the vector length to only the number of elements we care about. This
5548     // avoids sliding down elements we're going to discard straight away.
5549     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5550     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5551     SDValue Slidedown =
5552         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5553                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5554     // Now we can use a cast-like subvector extract to get the result.
5555     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5556                             DAG.getConstant(0, DL, XLenVT));
5557     return DAG.getBitcast(Op.getValueType(), Slidedown);
5558   }
5559 
5560   unsigned SubRegIdx, RemIdx;
5561   std::tie(SubRegIdx, RemIdx) =
5562       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5563           VecVT, SubVecVT, OrigIdx, TRI);
5564 
5565   // If the Idx has been completely eliminated then this is a subvector extract
5566   // which naturally aligns to a vector register. These can easily be handled
5567   // using subregister manipulation.
5568   if (RemIdx == 0)
5569     return Op;
5570 
5571   // Else we must shift our vector register directly to extract the subvector.
5572   // Do this using VSLIDEDOWN.
5573 
5574   // If the vector type is an LMUL-group type, extract a subvector equal to the
5575   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5576   // instruction.
5577   MVT InterSubVT = VecVT;
5578   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5579     InterSubVT = getLMUL1VT(VecVT);
5580     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5581                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5582   }
5583 
5584   // Slide this vector register down by the desired number of elements in order
5585   // to place the desired subvector starting at element 0.
5586   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5587   // For scalable vectors this must be further multiplied by vscale.
5588   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5589 
5590   SDValue Mask, VL;
5591   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5592   SDValue Slidedown =
5593       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5594                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5595 
5596   // Now the vector is in the right position, extract our final subvector. This
5597   // should resolve to a COPY.
5598   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5599                           DAG.getConstant(0, DL, XLenVT));
5600 
5601   // We might have bitcast from a mask type: cast back to the original type if
5602   // required.
5603   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5604 }
5605 
5606 // Lower step_vector to the vid instruction. Any non-identity step value must
5607 // be accounted for my manual expansion.
5608 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5609                                               SelectionDAG &DAG) const {
5610   SDLoc DL(Op);
5611   MVT VT = Op.getSimpleValueType();
5612   MVT XLenVT = Subtarget.getXLenVT();
5613   SDValue Mask, VL;
5614   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5615   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5616   uint64_t StepValImm = Op.getConstantOperandVal(0);
5617   if (StepValImm != 1) {
5618     if (isPowerOf2_64(StepValImm)) {
5619       SDValue StepVal =
5620           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5621                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5622       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5623     } else {
5624       SDValue StepVal = lowerScalarSplat(
5625           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5626           VL, VT, DL, DAG, Subtarget);
5627       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5628     }
5629   }
5630   return StepVec;
5631 }
5632 
5633 // Implement vector_reverse using vrgather.vv with indices determined by
5634 // subtracting the id of each element from (VLMAX-1). This will convert
5635 // the indices like so:
5636 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5637 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5638 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5639                                                  SelectionDAG &DAG) const {
5640   SDLoc DL(Op);
5641   MVT VecVT = Op.getSimpleValueType();
5642   if (VecVT.getVectorElementType() == MVT::i1) {
5643     MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
5644     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0));
5645     SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1);
5646     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2);
5647   }
5648   unsigned EltSize = VecVT.getScalarSizeInBits();
5649   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5650   unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
5651   unsigned MaxVLMAX =
5652     RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5653 
5654   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5655   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5656 
5657   // If this is SEW=8 and VLMAX is potentially more than 256, we need
5658   // to use vrgatherei16.vv.
5659   // TODO: It's also possible to use vrgatherei16.vv for other types to
5660   // decrease register width for the index calculation.
5661   if (MaxVLMAX > 256 && EltSize == 8) {
5662     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5663     // Reverse each half, then reassemble them in reverse order.
5664     // NOTE: It's also possible that after splitting that VLMAX no longer
5665     // requires vrgatherei16.vv.
5666     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5667       SDValue Lo, Hi;
5668       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5669       EVT LoVT, HiVT;
5670       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5671       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5672       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5673       // Reassemble the low and high pieces reversed.
5674       // FIXME: This is a CONCAT_VECTORS.
5675       SDValue Res =
5676           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5677                       DAG.getIntPtrConstant(0, DL));
5678       return DAG.getNode(
5679           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5680           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5681     }
5682 
5683     // Just promote the int type to i16 which will double the LMUL.
5684     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5685     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5686   }
5687 
5688   MVT XLenVT = Subtarget.getXLenVT();
5689   SDValue Mask, VL;
5690   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5691 
5692   // Calculate VLMAX-1 for the desired SEW.
5693   unsigned MinElts = VecVT.getVectorMinNumElements();
5694   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5695                               DAG.getConstant(MinElts, DL, XLenVT));
5696   SDValue VLMinus1 =
5697       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5698 
5699   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5700   bool IsRV32E64 =
5701       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5702   SDValue SplatVL;
5703   if (!IsRV32E64)
5704     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5705   else
5706     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5707                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5708 
5709   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5710   SDValue Indices =
5711       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5712 
5713   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask,
5714                      DAG.getUNDEF(VecVT), VL);
5715 }
5716 
5717 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5718                                                 SelectionDAG &DAG) const {
5719   SDLoc DL(Op);
5720   SDValue V1 = Op.getOperand(0);
5721   SDValue V2 = Op.getOperand(1);
5722   MVT XLenVT = Subtarget.getXLenVT();
5723   MVT VecVT = Op.getSimpleValueType();
5724 
5725   unsigned MinElts = VecVT.getVectorMinNumElements();
5726   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5727                               DAG.getConstant(MinElts, DL, XLenVT));
5728 
5729   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5730   SDValue DownOffset, UpOffset;
5731   if (ImmValue >= 0) {
5732     // The operand is a TargetConstant, we need to rebuild it as a regular
5733     // constant.
5734     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5735     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5736   } else {
5737     // The operand is a TargetConstant, we need to rebuild it as a regular
5738     // constant rather than negating the original operand.
5739     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5740     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5741   }
5742 
5743   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5744 
5745   SDValue SlideDown =
5746       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5747                   DownOffset, TrueMask, UpOffset);
5748   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5749                      TrueMask,
5750                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5751 }
5752 
5753 SDValue
5754 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5755                                                      SelectionDAG &DAG) const {
5756   SDLoc DL(Op);
5757   auto *Load = cast<LoadSDNode>(Op);
5758 
5759   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5760                                         Load->getMemoryVT(),
5761                                         *Load->getMemOperand()) &&
5762          "Expecting a correctly-aligned load");
5763 
5764   MVT VT = Op.getSimpleValueType();
5765   MVT XLenVT = Subtarget.getXLenVT();
5766   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5767 
5768   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5769 
5770   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5771   SDValue IntID = DAG.getTargetConstant(
5772       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5773   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5774   if (!IsMaskOp)
5775     Ops.push_back(DAG.getUNDEF(ContainerVT));
5776   Ops.push_back(Load->getBasePtr());
5777   Ops.push_back(VL);
5778   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5779   SDValue NewLoad =
5780       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5781                               Load->getMemoryVT(), Load->getMemOperand());
5782 
5783   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5784   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5785 }
5786 
5787 SDValue
5788 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5789                                                       SelectionDAG &DAG) const {
5790   SDLoc DL(Op);
5791   auto *Store = cast<StoreSDNode>(Op);
5792 
5793   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5794                                         Store->getMemoryVT(),
5795                                         *Store->getMemOperand()) &&
5796          "Expecting a correctly-aligned store");
5797 
5798   SDValue StoreVal = Store->getValue();
5799   MVT VT = StoreVal.getSimpleValueType();
5800   MVT XLenVT = Subtarget.getXLenVT();
5801 
5802   // If the size less than a byte, we need to pad with zeros to make a byte.
5803   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5804     VT = MVT::v8i1;
5805     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5806                            DAG.getConstant(0, DL, VT), StoreVal,
5807                            DAG.getIntPtrConstant(0, DL));
5808   }
5809 
5810   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5811 
5812   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5813 
5814   SDValue NewValue =
5815       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5816 
5817   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5818   SDValue IntID = DAG.getTargetConstant(
5819       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5820   return DAG.getMemIntrinsicNode(
5821       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5822       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5823       Store->getMemoryVT(), Store->getMemOperand());
5824 }
5825 
5826 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5827                                              SelectionDAG &DAG) const {
5828   SDLoc DL(Op);
5829   MVT VT = Op.getSimpleValueType();
5830 
5831   const auto *MemSD = cast<MemSDNode>(Op);
5832   EVT MemVT = MemSD->getMemoryVT();
5833   MachineMemOperand *MMO = MemSD->getMemOperand();
5834   SDValue Chain = MemSD->getChain();
5835   SDValue BasePtr = MemSD->getBasePtr();
5836 
5837   SDValue Mask, PassThru, VL;
5838   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5839     Mask = VPLoad->getMask();
5840     PassThru = DAG.getUNDEF(VT);
5841     VL = VPLoad->getVectorLength();
5842   } else {
5843     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5844     Mask = MLoad->getMask();
5845     PassThru = MLoad->getPassThru();
5846   }
5847 
5848   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5849 
5850   MVT XLenVT = Subtarget.getXLenVT();
5851 
5852   MVT ContainerVT = VT;
5853   if (VT.isFixedLengthVector()) {
5854     ContainerVT = getContainerForFixedLengthVector(VT);
5855     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5856     if (!IsUnmasked) {
5857       MVT MaskVT = getMaskTypeFor(ContainerVT);
5858       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5859     }
5860   }
5861 
5862   if (!VL)
5863     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5864 
5865   unsigned IntID =
5866       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5867   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5868   if (IsUnmasked)
5869     Ops.push_back(DAG.getUNDEF(ContainerVT));
5870   else
5871     Ops.push_back(PassThru);
5872   Ops.push_back(BasePtr);
5873   if (!IsUnmasked)
5874     Ops.push_back(Mask);
5875   Ops.push_back(VL);
5876   if (!IsUnmasked)
5877     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5878 
5879   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5880 
5881   SDValue Result =
5882       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5883   Chain = Result.getValue(1);
5884 
5885   if (VT.isFixedLengthVector())
5886     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5887 
5888   return DAG.getMergeValues({Result, Chain}, DL);
5889 }
5890 
5891 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5892                                               SelectionDAG &DAG) const {
5893   SDLoc DL(Op);
5894 
5895   const auto *MemSD = cast<MemSDNode>(Op);
5896   EVT MemVT = MemSD->getMemoryVT();
5897   MachineMemOperand *MMO = MemSD->getMemOperand();
5898   SDValue Chain = MemSD->getChain();
5899   SDValue BasePtr = MemSD->getBasePtr();
5900   SDValue Val, Mask, VL;
5901 
5902   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5903     Val = VPStore->getValue();
5904     Mask = VPStore->getMask();
5905     VL = VPStore->getVectorLength();
5906   } else {
5907     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5908     Val = MStore->getValue();
5909     Mask = MStore->getMask();
5910   }
5911 
5912   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5913 
5914   MVT VT = Val.getSimpleValueType();
5915   MVT XLenVT = Subtarget.getXLenVT();
5916 
5917   MVT ContainerVT = VT;
5918   if (VT.isFixedLengthVector()) {
5919     ContainerVT = getContainerForFixedLengthVector(VT);
5920 
5921     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5922     if (!IsUnmasked) {
5923       MVT MaskVT = getMaskTypeFor(ContainerVT);
5924       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5925     }
5926   }
5927 
5928   if (!VL)
5929     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5930 
5931   unsigned IntID =
5932       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5933   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5934   Ops.push_back(Val);
5935   Ops.push_back(BasePtr);
5936   if (!IsUnmasked)
5937     Ops.push_back(Mask);
5938   Ops.push_back(VL);
5939 
5940   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5941                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5942 }
5943 
5944 SDValue
5945 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5946                                                       SelectionDAG &DAG) const {
5947   MVT InVT = Op.getOperand(0).getSimpleValueType();
5948   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5949 
5950   MVT VT = Op.getSimpleValueType();
5951 
5952   SDValue Op1 =
5953       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5954   SDValue Op2 =
5955       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5956 
5957   SDLoc DL(Op);
5958   SDValue VL =
5959       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5960 
5961   MVT MaskVT = getMaskTypeFor(ContainerVT);
5962   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
5963 
5964   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5965                             Op.getOperand(2), Mask, VL);
5966 
5967   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5968 }
5969 
5970 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5971     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5972   MVT VT = Op.getSimpleValueType();
5973 
5974   if (VT.getVectorElementType() == MVT::i1)
5975     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5976 
5977   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5978 }
5979 
5980 SDValue
5981 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5982                                                       SelectionDAG &DAG) const {
5983   unsigned Opc;
5984   switch (Op.getOpcode()) {
5985   default: llvm_unreachable("Unexpected opcode!");
5986   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5987   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5988   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5989   }
5990 
5991   return lowerToScalableOp(Op, DAG, Opc);
5992 }
5993 
5994 // Lower vector ABS to smax(X, sub(0, X)).
5995 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5996   SDLoc DL(Op);
5997   MVT VT = Op.getSimpleValueType();
5998   SDValue X = Op.getOperand(0);
5999 
6000   assert(VT.isFixedLengthVector() && "Unexpected type");
6001 
6002   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6003   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6004 
6005   SDValue Mask, VL;
6006   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6007 
6008   SDValue SplatZero = DAG.getNode(
6009       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6010       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6011   SDValue NegX =
6012       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6013   SDValue Max =
6014       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6015 
6016   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6017 }
6018 
6019 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6020     SDValue Op, SelectionDAG &DAG) const {
6021   SDLoc DL(Op);
6022   MVT VT = Op.getSimpleValueType();
6023   SDValue Mag = Op.getOperand(0);
6024   SDValue Sign = Op.getOperand(1);
6025   assert(Mag.getValueType() == Sign.getValueType() &&
6026          "Can only handle COPYSIGN with matching types.");
6027 
6028   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6029   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6030   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6031 
6032   SDValue Mask, VL;
6033   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6034 
6035   SDValue CopySign =
6036       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6037 
6038   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6039 }
6040 
6041 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6042     SDValue Op, SelectionDAG &DAG) const {
6043   MVT VT = Op.getSimpleValueType();
6044   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6045 
6046   MVT I1ContainerVT =
6047       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6048 
6049   SDValue CC =
6050       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6051   SDValue Op1 =
6052       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6053   SDValue Op2 =
6054       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6055 
6056   SDLoc DL(Op);
6057   SDValue Mask, VL;
6058   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6059 
6060   SDValue Select =
6061       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6062 
6063   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6064 }
6065 
6066 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6067                                                unsigned NewOpc,
6068                                                bool HasMask) const {
6069   MVT VT = Op.getSimpleValueType();
6070   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6071 
6072   // Create list of operands by converting existing ones to scalable types.
6073   SmallVector<SDValue, 6> Ops;
6074   for (const SDValue &V : Op->op_values()) {
6075     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6076 
6077     // Pass through non-vector operands.
6078     if (!V.getValueType().isVector()) {
6079       Ops.push_back(V);
6080       continue;
6081     }
6082 
6083     // "cast" fixed length vector to a scalable vector.
6084     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6085            "Only fixed length vectors are supported!");
6086     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6087   }
6088 
6089   SDLoc DL(Op);
6090   SDValue Mask, VL;
6091   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6092   if (HasMask)
6093     Ops.push_back(Mask);
6094   Ops.push_back(VL);
6095 
6096   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6097   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6098 }
6099 
6100 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6101 // * Operands of each node are assumed to be in the same order.
6102 // * The EVL operand is promoted from i32 to i64 on RV64.
6103 // * Fixed-length vectors are converted to their scalable-vector container
6104 //   types.
6105 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6106                                        unsigned RISCVISDOpc) const {
6107   SDLoc DL(Op);
6108   MVT VT = Op.getSimpleValueType();
6109   SmallVector<SDValue, 4> Ops;
6110 
6111   for (const auto &OpIdx : enumerate(Op->ops())) {
6112     SDValue V = OpIdx.value();
6113     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6114     // Pass through operands which aren't fixed-length vectors.
6115     if (!V.getValueType().isFixedLengthVector()) {
6116       Ops.push_back(V);
6117       continue;
6118     }
6119     // "cast" fixed length vector to a scalable vector.
6120     MVT OpVT = V.getSimpleValueType();
6121     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6122     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6123            "Only fixed length vectors are supported!");
6124     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6125   }
6126 
6127   if (!VT.isFixedLengthVector())
6128     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6129 
6130   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6131 
6132   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6133 
6134   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6135 }
6136 
6137 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6138                                               SelectionDAG &DAG) const {
6139   SDLoc DL(Op);
6140   MVT VT = Op.getSimpleValueType();
6141 
6142   SDValue Src = Op.getOperand(0);
6143   // NOTE: Mask is dropped.
6144   SDValue VL = Op.getOperand(2);
6145 
6146   MVT ContainerVT = VT;
6147   if (VT.isFixedLengthVector()) {
6148     ContainerVT = getContainerForFixedLengthVector(VT);
6149     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6150     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6151   }
6152 
6153   MVT XLenVT = Subtarget.getXLenVT();
6154   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6155   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6156                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6157 
6158   SDValue SplatValue = DAG.getConstant(
6159       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6160   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6161                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6162 
6163   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6164                                Splat, ZeroSplat, VL);
6165   if (!VT.isFixedLengthVector())
6166     return Result;
6167   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6168 }
6169 
6170 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6171                                                 SelectionDAG &DAG) const {
6172   SDLoc DL(Op);
6173   MVT VT = Op.getSimpleValueType();
6174 
6175   SDValue Op1 = Op.getOperand(0);
6176   SDValue Op2 = Op.getOperand(1);
6177   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6178   // NOTE: Mask is dropped.
6179   SDValue VL = Op.getOperand(4);
6180 
6181   MVT ContainerVT = VT;
6182   if (VT.isFixedLengthVector()) {
6183     ContainerVT = getContainerForFixedLengthVector(VT);
6184     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6185     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6186   }
6187 
6188   SDValue Result;
6189   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6190 
6191   switch (Condition) {
6192   default:
6193     break;
6194   // X != Y  --> (X^Y)
6195   case ISD::SETNE:
6196     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6197     break;
6198   // X == Y  --> ~(X^Y)
6199   case ISD::SETEQ: {
6200     SDValue Temp =
6201         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6202     Result =
6203         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6204     break;
6205   }
6206   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6207   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6208   case ISD::SETGT:
6209   case ISD::SETULT: {
6210     SDValue Temp =
6211         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6212     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6213     break;
6214   }
6215   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6216   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6217   case ISD::SETLT:
6218   case ISD::SETUGT: {
6219     SDValue Temp =
6220         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6221     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6222     break;
6223   }
6224   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6225   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6226   case ISD::SETGE:
6227   case ISD::SETULE: {
6228     SDValue Temp =
6229         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6230     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6231     break;
6232   }
6233   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6234   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6235   case ISD::SETLE:
6236   case ISD::SETUGE: {
6237     SDValue Temp =
6238         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6239     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6240     break;
6241   }
6242   }
6243 
6244   if (!VT.isFixedLengthVector())
6245     return Result;
6246   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6247 }
6248 
6249 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6250 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6251                                                 unsigned RISCVISDOpc) const {
6252   SDLoc DL(Op);
6253 
6254   SDValue Src = Op.getOperand(0);
6255   SDValue Mask = Op.getOperand(1);
6256   SDValue VL = Op.getOperand(2);
6257 
6258   MVT DstVT = Op.getSimpleValueType();
6259   MVT SrcVT = Src.getSimpleValueType();
6260   if (DstVT.isFixedLengthVector()) {
6261     DstVT = getContainerForFixedLengthVector(DstVT);
6262     SrcVT = getContainerForFixedLengthVector(SrcVT);
6263     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6264     MVT MaskVT = getMaskTypeFor(DstVT);
6265     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6266   }
6267 
6268   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6269                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6270                                 ? RISCVISD::VSEXT_VL
6271                                 : RISCVISD::VZEXT_VL;
6272 
6273   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6274   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6275 
6276   SDValue Result;
6277   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6278     if (SrcVT.isInteger()) {
6279       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6280 
6281       // Do we need to do any pre-widening before converting?
6282       if (SrcEltSize == 1) {
6283         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6284         MVT XLenVT = Subtarget.getXLenVT();
6285         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6286         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6287                                         DAG.getUNDEF(IntVT), Zero, VL);
6288         SDValue One = DAG.getConstant(
6289             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6290         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6291                                        DAG.getUNDEF(IntVT), One, VL);
6292         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6293                           ZeroSplat, VL);
6294       } else if (DstEltSize > (2 * SrcEltSize)) {
6295         // Widen before converting.
6296         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6297                                      DstVT.getVectorElementCount());
6298         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6299       }
6300 
6301       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6302     } else {
6303       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6304              "Wrong input/output vector types");
6305 
6306       // Convert f16 to f32 then convert f32 to i64.
6307       if (DstEltSize > (2 * SrcEltSize)) {
6308         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6309         MVT InterimFVT =
6310             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6311         Src =
6312             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6313       }
6314 
6315       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6316     }
6317   } else { // Narrowing + Conversion
6318     if (SrcVT.isInteger()) {
6319       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6320       // First do a narrowing convert to an FP type half the size, then round
6321       // the FP type to a small FP type if needed.
6322 
6323       MVT InterimFVT = DstVT;
6324       if (SrcEltSize > (2 * DstEltSize)) {
6325         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6326         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6327         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6328       }
6329 
6330       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6331 
6332       if (InterimFVT != DstVT) {
6333         Src = Result;
6334         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6335       }
6336     } else {
6337       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6338              "Wrong input/output vector types");
6339       // First do a narrowing conversion to an integer half the size, then
6340       // truncate if needed.
6341 
6342       if (DstEltSize == 1) {
6343         // First convert to the same size integer, then convert to mask using
6344         // setcc.
6345         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6346         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6347                                           DstVT.getVectorElementCount());
6348         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6349 
6350         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6351         // otherwise the conversion was undefined.
6352         MVT XLenVT = Subtarget.getXLenVT();
6353         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6354         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6355                                 DAG.getUNDEF(InterimIVT), SplatZero);
6356         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6357                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6358       } else {
6359         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6360                                           DstVT.getVectorElementCount());
6361 
6362         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6363 
6364         while (InterimIVT != DstVT) {
6365           SrcEltSize /= 2;
6366           Src = Result;
6367           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6368                                         DstVT.getVectorElementCount());
6369           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6370                                Src, Mask, VL);
6371         }
6372       }
6373     }
6374   }
6375 
6376   MVT VT = Op.getSimpleValueType();
6377   if (!VT.isFixedLengthVector())
6378     return Result;
6379   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6380 }
6381 
6382 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6383                                             unsigned MaskOpc,
6384                                             unsigned VecOpc) const {
6385   MVT VT = Op.getSimpleValueType();
6386   if (VT.getVectorElementType() != MVT::i1)
6387     return lowerVPOp(Op, DAG, VecOpc);
6388 
6389   // It is safe to drop mask parameter as masked-off elements are undef.
6390   SDValue Op1 = Op->getOperand(0);
6391   SDValue Op2 = Op->getOperand(1);
6392   SDValue VL = Op->getOperand(3);
6393 
6394   MVT ContainerVT = VT;
6395   const bool IsFixed = VT.isFixedLengthVector();
6396   if (IsFixed) {
6397     ContainerVT = getContainerForFixedLengthVector(VT);
6398     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6399     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6400   }
6401 
6402   SDLoc DL(Op);
6403   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6404   if (!IsFixed)
6405     return Val;
6406   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6407 }
6408 
6409 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6410 // matched to a RVV indexed load. The RVV indexed load instructions only
6411 // support the "unsigned unscaled" addressing mode; indices are implicitly
6412 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6413 // signed or scaled indexing is extended to the XLEN value type and scaled
6414 // accordingly.
6415 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6416                                                SelectionDAG &DAG) const {
6417   SDLoc DL(Op);
6418   MVT VT = Op.getSimpleValueType();
6419 
6420   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6421   EVT MemVT = MemSD->getMemoryVT();
6422   MachineMemOperand *MMO = MemSD->getMemOperand();
6423   SDValue Chain = MemSD->getChain();
6424   SDValue BasePtr = MemSD->getBasePtr();
6425 
6426   ISD::LoadExtType LoadExtType;
6427   SDValue Index, Mask, PassThru, VL;
6428 
6429   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6430     Index = VPGN->getIndex();
6431     Mask = VPGN->getMask();
6432     PassThru = DAG.getUNDEF(VT);
6433     VL = VPGN->getVectorLength();
6434     // VP doesn't support extending loads.
6435     LoadExtType = ISD::NON_EXTLOAD;
6436   } else {
6437     // Else it must be a MGATHER.
6438     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6439     Index = MGN->getIndex();
6440     Mask = MGN->getMask();
6441     PassThru = MGN->getPassThru();
6442     LoadExtType = MGN->getExtensionType();
6443   }
6444 
6445   MVT IndexVT = Index.getSimpleValueType();
6446   MVT XLenVT = Subtarget.getXLenVT();
6447 
6448   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6449          "Unexpected VTs!");
6450   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6451   // Targets have to explicitly opt-in for extending vector loads.
6452   assert(LoadExtType == ISD::NON_EXTLOAD &&
6453          "Unexpected extending MGATHER/VP_GATHER");
6454   (void)LoadExtType;
6455 
6456   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6457   // the selection of the masked intrinsics doesn't do this for us.
6458   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6459 
6460   MVT ContainerVT = VT;
6461   if (VT.isFixedLengthVector()) {
6462     ContainerVT = getContainerForFixedLengthVector(VT);
6463     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6464                                ContainerVT.getVectorElementCount());
6465 
6466     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6467 
6468     if (!IsUnmasked) {
6469       MVT MaskVT = getMaskTypeFor(ContainerVT);
6470       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6471       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6472     }
6473   }
6474 
6475   if (!VL)
6476     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6477 
6478   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6479     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6480     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6481                                    VL);
6482     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6483                         TrueMask, VL);
6484   }
6485 
6486   unsigned IntID =
6487       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6488   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6489   if (IsUnmasked)
6490     Ops.push_back(DAG.getUNDEF(ContainerVT));
6491   else
6492     Ops.push_back(PassThru);
6493   Ops.push_back(BasePtr);
6494   Ops.push_back(Index);
6495   if (!IsUnmasked)
6496     Ops.push_back(Mask);
6497   Ops.push_back(VL);
6498   if (!IsUnmasked)
6499     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6500 
6501   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6502   SDValue Result =
6503       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6504   Chain = Result.getValue(1);
6505 
6506   if (VT.isFixedLengthVector())
6507     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6508 
6509   return DAG.getMergeValues({Result, Chain}, DL);
6510 }
6511 
6512 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6513 // matched to a RVV indexed store. The RVV indexed store instructions only
6514 // support the "unsigned unscaled" addressing mode; indices are implicitly
6515 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6516 // signed or scaled indexing is extended to the XLEN value type and scaled
6517 // accordingly.
6518 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6519                                                 SelectionDAG &DAG) const {
6520   SDLoc DL(Op);
6521   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6522   EVT MemVT = MemSD->getMemoryVT();
6523   MachineMemOperand *MMO = MemSD->getMemOperand();
6524   SDValue Chain = MemSD->getChain();
6525   SDValue BasePtr = MemSD->getBasePtr();
6526 
6527   bool IsTruncatingStore = false;
6528   SDValue Index, Mask, Val, VL;
6529 
6530   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6531     Index = VPSN->getIndex();
6532     Mask = VPSN->getMask();
6533     Val = VPSN->getValue();
6534     VL = VPSN->getVectorLength();
6535     // VP doesn't support truncating stores.
6536     IsTruncatingStore = false;
6537   } else {
6538     // Else it must be a MSCATTER.
6539     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6540     Index = MSN->getIndex();
6541     Mask = MSN->getMask();
6542     Val = MSN->getValue();
6543     IsTruncatingStore = MSN->isTruncatingStore();
6544   }
6545 
6546   MVT VT = Val.getSimpleValueType();
6547   MVT IndexVT = Index.getSimpleValueType();
6548   MVT XLenVT = Subtarget.getXLenVT();
6549 
6550   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6551          "Unexpected VTs!");
6552   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6553   // Targets have to explicitly opt-in for extending vector loads and
6554   // truncating vector stores.
6555   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6556   (void)IsTruncatingStore;
6557 
6558   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6559   // the selection of the masked intrinsics doesn't do this for us.
6560   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6561 
6562   MVT ContainerVT = VT;
6563   if (VT.isFixedLengthVector()) {
6564     ContainerVT = getContainerForFixedLengthVector(VT);
6565     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6566                                ContainerVT.getVectorElementCount());
6567 
6568     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6569     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6570 
6571     if (!IsUnmasked) {
6572       MVT MaskVT = getMaskTypeFor(ContainerVT);
6573       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6574     }
6575   }
6576 
6577   if (!VL)
6578     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6579 
6580   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6581     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6582     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6583                                    VL);
6584     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6585                         TrueMask, VL);
6586   }
6587 
6588   unsigned IntID =
6589       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6590   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6591   Ops.push_back(Val);
6592   Ops.push_back(BasePtr);
6593   Ops.push_back(Index);
6594   if (!IsUnmasked)
6595     Ops.push_back(Mask);
6596   Ops.push_back(VL);
6597 
6598   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6599                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6600 }
6601 
6602 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6603                                                SelectionDAG &DAG) const {
6604   const MVT XLenVT = Subtarget.getXLenVT();
6605   SDLoc DL(Op);
6606   SDValue Chain = Op->getOperand(0);
6607   SDValue SysRegNo = DAG.getTargetConstant(
6608       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6609   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6610   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6611 
6612   // Encoding used for rounding mode in RISCV differs from that used in
6613   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6614   // table, which consists of a sequence of 4-bit fields, each representing
6615   // corresponding FLT_ROUNDS mode.
6616   static const int Table =
6617       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6618       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6619       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6620       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6621       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6622 
6623   SDValue Shift =
6624       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6625   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6626                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6627   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6628                                DAG.getConstant(7, DL, XLenVT));
6629 
6630   return DAG.getMergeValues({Masked, Chain}, DL);
6631 }
6632 
6633 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6634                                                SelectionDAG &DAG) const {
6635   const MVT XLenVT = Subtarget.getXLenVT();
6636   SDLoc DL(Op);
6637   SDValue Chain = Op->getOperand(0);
6638   SDValue RMValue = Op->getOperand(1);
6639   SDValue SysRegNo = DAG.getTargetConstant(
6640       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6641 
6642   // Encoding used for rounding mode in RISCV differs from that used in
6643   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6644   // a table, which consists of a sequence of 4-bit fields, each representing
6645   // corresponding RISCV mode.
6646   static const unsigned Table =
6647       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6648       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6649       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6650       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6651       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6652 
6653   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6654                               DAG.getConstant(2, DL, XLenVT));
6655   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6656                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6657   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6658                         DAG.getConstant(0x7, DL, XLenVT));
6659   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6660                      RMValue);
6661 }
6662 
6663 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6664                                                SelectionDAG &DAG) const {
6665   MachineFunction &MF = DAG.getMachineFunction();
6666 
6667   bool isRISCV64 = Subtarget.is64Bit();
6668   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6669 
6670   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6671   return DAG.getFrameIndex(FI, PtrVT);
6672 }
6673 
6674 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6675   switch (IntNo) {
6676   default:
6677     llvm_unreachable("Unexpected Intrinsic");
6678   case Intrinsic::riscv_bcompress:
6679     return RISCVISD::BCOMPRESSW;
6680   case Intrinsic::riscv_bdecompress:
6681     return RISCVISD::BDECOMPRESSW;
6682   case Intrinsic::riscv_bfp:
6683     return RISCVISD::BFPW;
6684   case Intrinsic::riscv_fsl:
6685     return RISCVISD::FSLW;
6686   case Intrinsic::riscv_fsr:
6687     return RISCVISD::FSRW;
6688   }
6689 }
6690 
6691 // Converts the given intrinsic to a i64 operation with any extension.
6692 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6693                                          unsigned IntNo) {
6694   SDLoc DL(N);
6695   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6696   // Deal with the Instruction Operands
6697   SmallVector<SDValue, 3> NewOps;
6698   for (SDValue Op : drop_begin(N->ops()))
6699     // Promote the operand to i64 type
6700     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6701   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6702   // ReplaceNodeResults requires we maintain the same type for the return value.
6703   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6704 }
6705 
6706 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6707 // form of the given Opcode.
6708 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6709   switch (Opcode) {
6710   default:
6711     llvm_unreachable("Unexpected opcode");
6712   case ISD::SHL:
6713     return RISCVISD::SLLW;
6714   case ISD::SRA:
6715     return RISCVISD::SRAW;
6716   case ISD::SRL:
6717     return RISCVISD::SRLW;
6718   case ISD::SDIV:
6719     return RISCVISD::DIVW;
6720   case ISD::UDIV:
6721     return RISCVISD::DIVUW;
6722   case ISD::UREM:
6723     return RISCVISD::REMUW;
6724   case ISD::ROTL:
6725     return RISCVISD::ROLW;
6726   case ISD::ROTR:
6727     return RISCVISD::RORW;
6728   }
6729 }
6730 
6731 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6732 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6733 // otherwise be promoted to i64, making it difficult to select the
6734 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6735 // type i8/i16/i32 is lost.
6736 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6737                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6738   SDLoc DL(N);
6739   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6740   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6741   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6742   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6743   // ReplaceNodeResults requires we maintain the same type for the return value.
6744   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6745 }
6746 
6747 // Converts the given 32-bit operation to a i64 operation with signed extension
6748 // semantic to reduce the signed extension instructions.
6749 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6750   SDLoc DL(N);
6751   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6752   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6753   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6754   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6755                                DAG.getValueType(MVT::i32));
6756   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6757 }
6758 
6759 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6760                                              SmallVectorImpl<SDValue> &Results,
6761                                              SelectionDAG &DAG) const {
6762   SDLoc DL(N);
6763   switch (N->getOpcode()) {
6764   default:
6765     llvm_unreachable("Don't know how to custom type legalize this operation!");
6766   case ISD::STRICT_FP_TO_SINT:
6767   case ISD::STRICT_FP_TO_UINT:
6768   case ISD::FP_TO_SINT:
6769   case ISD::FP_TO_UINT: {
6770     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6771            "Unexpected custom legalisation");
6772     bool IsStrict = N->isStrictFPOpcode();
6773     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6774                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6775     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6776     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6777         TargetLowering::TypeSoftenFloat) {
6778       if (!isTypeLegal(Op0.getValueType()))
6779         return;
6780       if (IsStrict) {
6781         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6782                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6783         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6784         SDValue Res = DAG.getNode(
6785             Opc, DL, VTs, N->getOperand(0), Op0,
6786             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6787         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6788         Results.push_back(Res.getValue(1));
6789         return;
6790       }
6791       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6792       SDValue Res =
6793           DAG.getNode(Opc, DL, MVT::i64, Op0,
6794                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6795       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6796       return;
6797     }
6798     // If the FP type needs to be softened, emit a library call using the 'si'
6799     // version. If we left it to default legalization we'd end up with 'di'. If
6800     // the FP type doesn't need to be softened just let generic type
6801     // legalization promote the result type.
6802     RTLIB::Libcall LC;
6803     if (IsSigned)
6804       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6805     else
6806       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6807     MakeLibCallOptions CallOptions;
6808     EVT OpVT = Op0.getValueType();
6809     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6810     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6811     SDValue Result;
6812     std::tie(Result, Chain) =
6813         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6814     Results.push_back(Result);
6815     if (IsStrict)
6816       Results.push_back(Chain);
6817     break;
6818   }
6819   case ISD::READCYCLECOUNTER: {
6820     assert(!Subtarget.is64Bit() &&
6821            "READCYCLECOUNTER only has custom type legalization on riscv32");
6822 
6823     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6824     SDValue RCW =
6825         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6826 
6827     Results.push_back(
6828         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6829     Results.push_back(RCW.getValue(2));
6830     break;
6831   }
6832   case ISD::MUL: {
6833     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6834     unsigned XLen = Subtarget.getXLen();
6835     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6836     if (Size > XLen) {
6837       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6838       SDValue LHS = N->getOperand(0);
6839       SDValue RHS = N->getOperand(1);
6840       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6841 
6842       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6843       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6844       // We need exactly one side to be unsigned.
6845       if (LHSIsU == RHSIsU)
6846         return;
6847 
6848       auto MakeMULPair = [&](SDValue S, SDValue U) {
6849         MVT XLenVT = Subtarget.getXLenVT();
6850         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6851         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6852         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6853         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6854         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6855       };
6856 
6857       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6858       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6859 
6860       // The other operand should be signed, but still prefer MULH when
6861       // possible.
6862       if (RHSIsU && LHSIsS && !RHSIsS)
6863         Results.push_back(MakeMULPair(LHS, RHS));
6864       else if (LHSIsU && RHSIsS && !LHSIsS)
6865         Results.push_back(MakeMULPair(RHS, LHS));
6866 
6867       return;
6868     }
6869     LLVM_FALLTHROUGH;
6870   }
6871   case ISD::ADD:
6872   case ISD::SUB:
6873     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6874            "Unexpected custom legalisation");
6875     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6876     break;
6877   case ISD::SHL:
6878   case ISD::SRA:
6879   case ISD::SRL:
6880     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6881            "Unexpected custom legalisation");
6882     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6883       // If we can use a BSET instruction, allow default promotion to apply.
6884       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6885           isOneConstant(N->getOperand(0)))
6886         break;
6887       Results.push_back(customLegalizeToWOp(N, DAG));
6888       break;
6889     }
6890 
6891     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6892     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6893     // shift amount.
6894     if (N->getOpcode() == ISD::SHL) {
6895       SDLoc DL(N);
6896       SDValue NewOp0 =
6897           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6898       SDValue NewOp1 =
6899           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6900       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6901       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6902                                    DAG.getValueType(MVT::i32));
6903       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6904     }
6905 
6906     break;
6907   case ISD::ROTL:
6908   case ISD::ROTR:
6909     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6910            "Unexpected custom legalisation");
6911     Results.push_back(customLegalizeToWOp(N, DAG));
6912     break;
6913   case ISD::CTTZ:
6914   case ISD::CTTZ_ZERO_UNDEF:
6915   case ISD::CTLZ:
6916   case ISD::CTLZ_ZERO_UNDEF: {
6917     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6918            "Unexpected custom legalisation");
6919 
6920     SDValue NewOp0 =
6921         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6922     bool IsCTZ =
6923         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6924     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6925     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6926     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6927     return;
6928   }
6929   case ISD::SDIV:
6930   case ISD::UDIV:
6931   case ISD::UREM: {
6932     MVT VT = N->getSimpleValueType(0);
6933     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6934            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6935            "Unexpected custom legalisation");
6936     // Don't promote division/remainder by constant since we should expand those
6937     // to multiply by magic constant.
6938     // FIXME: What if the expansion is disabled for minsize.
6939     if (N->getOperand(1).getOpcode() == ISD::Constant)
6940       return;
6941 
6942     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6943     // the upper 32 bits. For other types we need to sign or zero extend
6944     // based on the opcode.
6945     unsigned ExtOpc = ISD::ANY_EXTEND;
6946     if (VT != MVT::i32)
6947       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6948                                            : ISD::ZERO_EXTEND;
6949 
6950     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6951     break;
6952   }
6953   case ISD::UADDO:
6954   case ISD::USUBO: {
6955     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6956            "Unexpected custom legalisation");
6957     bool IsAdd = N->getOpcode() == ISD::UADDO;
6958     // Create an ADDW or SUBW.
6959     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6960     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6961     SDValue Res =
6962         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6963     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6964                       DAG.getValueType(MVT::i32));
6965 
6966     SDValue Overflow;
6967     if (IsAdd && isOneConstant(RHS)) {
6968       // Special case uaddo X, 1 overflowed if the addition result is 0.
6969       // The general case (X + C) < C is not necessarily beneficial. Although we
6970       // reduce the live range of X, we may introduce the materialization of
6971       // constant C, especially when the setcc result is used by branch. We have
6972       // no compare with constant and branch instructions.
6973       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6974                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6975     } else {
6976       // Sign extend the LHS and perform an unsigned compare with the ADDW
6977       // result. Since the inputs are sign extended from i32, this is equivalent
6978       // to comparing the lower 32 bits.
6979       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6980       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6981                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6982     }
6983 
6984     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6985     Results.push_back(Overflow);
6986     return;
6987   }
6988   case ISD::UADDSAT:
6989   case ISD::USUBSAT: {
6990     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6991            "Unexpected custom legalisation");
6992     if (Subtarget.hasStdExtZbb()) {
6993       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6994       // sign extend allows overflow of the lower 32 bits to be detected on
6995       // the promoted size.
6996       SDValue LHS =
6997           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6998       SDValue RHS =
6999           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
7000       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
7001       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7002       return;
7003     }
7004 
7005     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
7006     // promotion for UADDO/USUBO.
7007     Results.push_back(expandAddSubSat(N, DAG));
7008     return;
7009   }
7010   case ISD::ABS: {
7011     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7012            "Unexpected custom legalisation");
7013 
7014     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
7015 
7016     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7017 
7018     // Freeze the source so we can increase it's use count.
7019     Src = DAG.getFreeze(Src);
7020 
7021     // Copy sign bit to all bits using the sraiw pattern.
7022     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7023                                    DAG.getValueType(MVT::i32));
7024     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7025                            DAG.getConstant(31, DL, MVT::i64));
7026 
7027     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7028     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7029 
7030     // NOTE: The result is only required to be anyextended, but sext is
7031     // consistent with type legalization of sub.
7032     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7033                          DAG.getValueType(MVT::i32));
7034     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7035     return;
7036   }
7037   case ISD::BITCAST: {
7038     EVT VT = N->getValueType(0);
7039     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7040     SDValue Op0 = N->getOperand(0);
7041     EVT Op0VT = Op0.getValueType();
7042     MVT XLenVT = Subtarget.getXLenVT();
7043     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7044       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7045       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7046     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7047                Subtarget.hasStdExtF()) {
7048       SDValue FPConv =
7049           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7050       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7051     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7052                isTypeLegal(Op0VT)) {
7053       // Custom-legalize bitcasts from fixed-length vector types to illegal
7054       // scalar types in order to improve codegen. Bitcast the vector to a
7055       // one-element vector type whose element type is the same as the result
7056       // type, and extract the first element.
7057       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7058       if (isTypeLegal(BVT)) {
7059         SDValue BVec = DAG.getBitcast(BVT, Op0);
7060         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7061                                       DAG.getConstant(0, DL, XLenVT)));
7062       }
7063     }
7064     break;
7065   }
7066   case RISCVISD::GREV:
7067   case RISCVISD::GORC:
7068   case RISCVISD::SHFL: {
7069     MVT VT = N->getSimpleValueType(0);
7070     MVT XLenVT = Subtarget.getXLenVT();
7071     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7072            "Unexpected custom legalisation");
7073     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7074     assert((Subtarget.hasStdExtZbp() ||
7075             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7076              N->getConstantOperandVal(1) == 7)) &&
7077            "Unexpected extension");
7078     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7079     SDValue NewOp1 =
7080         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7081     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7082     // ReplaceNodeResults requires we maintain the same type for the return
7083     // value.
7084     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7085     break;
7086   }
7087   case ISD::BSWAP:
7088   case ISD::BITREVERSE: {
7089     MVT VT = N->getSimpleValueType(0);
7090     MVT XLenVT = Subtarget.getXLenVT();
7091     assert((VT == MVT::i8 || VT == MVT::i16 ||
7092             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7093            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7094     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7095     unsigned Imm = VT.getSizeInBits() - 1;
7096     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7097     if (N->getOpcode() == ISD::BSWAP)
7098       Imm &= ~0x7U;
7099     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7100                                 DAG.getConstant(Imm, DL, XLenVT));
7101     // ReplaceNodeResults requires we maintain the same type for the return
7102     // value.
7103     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7104     break;
7105   }
7106   case ISD::FSHL:
7107   case ISD::FSHR: {
7108     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7109            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7110     SDValue NewOp0 =
7111         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7112     SDValue NewOp1 =
7113         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7114     SDValue NewShAmt =
7115         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7116     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7117     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7118     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7119                            DAG.getConstant(0x1f, DL, MVT::i64));
7120     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7121     // instruction use different orders. fshl will return its first operand for
7122     // shift of zero, fshr will return its second operand. fsl and fsr both
7123     // return rs1 so the ISD nodes need to have different operand orders.
7124     // Shift amount is in rs2.
7125     unsigned Opc = RISCVISD::FSLW;
7126     if (N->getOpcode() == ISD::FSHR) {
7127       std::swap(NewOp0, NewOp1);
7128       Opc = RISCVISD::FSRW;
7129     }
7130     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7131     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7132     break;
7133   }
7134   case ISD::EXTRACT_VECTOR_ELT: {
7135     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7136     // type is illegal (currently only vXi64 RV32).
7137     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7138     // transferred to the destination register. We issue two of these from the
7139     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7140     // first element.
7141     SDValue Vec = N->getOperand(0);
7142     SDValue Idx = N->getOperand(1);
7143 
7144     // The vector type hasn't been legalized yet so we can't issue target
7145     // specific nodes if it needs legalization.
7146     // FIXME: We would manually legalize if it's important.
7147     if (!isTypeLegal(Vec.getValueType()))
7148       return;
7149 
7150     MVT VecVT = Vec.getSimpleValueType();
7151 
7152     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7153            VecVT.getVectorElementType() == MVT::i64 &&
7154            "Unexpected EXTRACT_VECTOR_ELT legalization");
7155 
7156     // If this is a fixed vector, we need to convert it to a scalable vector.
7157     MVT ContainerVT = VecVT;
7158     if (VecVT.isFixedLengthVector()) {
7159       ContainerVT = getContainerForFixedLengthVector(VecVT);
7160       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7161     }
7162 
7163     MVT XLenVT = Subtarget.getXLenVT();
7164 
7165     // Use a VL of 1 to avoid processing more elements than we need.
7166     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7167     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7168 
7169     // Unless the index is known to be 0, we must slide the vector down to get
7170     // the desired element into index 0.
7171     if (!isNullConstant(Idx)) {
7172       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7173                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7174     }
7175 
7176     // Extract the lower XLEN bits of the correct vector element.
7177     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7178 
7179     // To extract the upper XLEN bits of the vector element, shift the first
7180     // element right by 32 bits and re-extract the lower XLEN bits.
7181     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7182                                      DAG.getUNDEF(ContainerVT),
7183                                      DAG.getConstant(32, DL, XLenVT), VL);
7184     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7185                                  ThirtyTwoV, Mask, VL);
7186 
7187     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7188 
7189     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7190     break;
7191   }
7192   case ISD::INTRINSIC_WO_CHAIN: {
7193     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7194     switch (IntNo) {
7195     default:
7196       llvm_unreachable(
7197           "Don't know how to custom type legalize this intrinsic!");
7198     case Intrinsic::riscv_grev:
7199     case Intrinsic::riscv_gorc: {
7200       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7201              "Unexpected custom legalisation");
7202       SDValue NewOp1 =
7203           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7204       SDValue NewOp2 =
7205           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7206       unsigned Opc =
7207           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7208       // If the control is a constant, promote the node by clearing any extra
7209       // bits bits in the control. isel will form greviw/gorciw if the result is
7210       // sign extended.
7211       if (isa<ConstantSDNode>(NewOp2)) {
7212         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7213                              DAG.getConstant(0x1f, DL, MVT::i64));
7214         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7215       }
7216       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7217       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7218       break;
7219     }
7220     case Intrinsic::riscv_bcompress:
7221     case Intrinsic::riscv_bdecompress:
7222     case Intrinsic::riscv_bfp:
7223     case Intrinsic::riscv_fsl:
7224     case Intrinsic::riscv_fsr: {
7225       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7226              "Unexpected custom legalisation");
7227       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7228       break;
7229     }
7230     case Intrinsic::riscv_orc_b: {
7231       // Lower to the GORCI encoding for orc.b with the operand extended.
7232       SDValue NewOp =
7233           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7234       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7235                                 DAG.getConstant(7, DL, MVT::i64));
7236       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7237       return;
7238     }
7239     case Intrinsic::riscv_shfl:
7240     case Intrinsic::riscv_unshfl: {
7241       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7242              "Unexpected custom legalisation");
7243       SDValue NewOp1 =
7244           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7245       SDValue NewOp2 =
7246           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7247       unsigned Opc =
7248           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7249       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7250       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7251       // will be shuffled the same way as the lower 32 bit half, but the two
7252       // halves won't cross.
7253       if (isa<ConstantSDNode>(NewOp2)) {
7254         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7255                              DAG.getConstant(0xf, DL, MVT::i64));
7256         Opc =
7257             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7258       }
7259       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7260       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7261       break;
7262     }
7263     case Intrinsic::riscv_vmv_x_s: {
7264       EVT VT = N->getValueType(0);
7265       MVT XLenVT = Subtarget.getXLenVT();
7266       if (VT.bitsLT(XLenVT)) {
7267         // Simple case just extract using vmv.x.s and truncate.
7268         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7269                                       Subtarget.getXLenVT(), N->getOperand(1));
7270         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7271         return;
7272       }
7273 
7274       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7275              "Unexpected custom legalization");
7276 
7277       // We need to do the move in two steps.
7278       SDValue Vec = N->getOperand(1);
7279       MVT VecVT = Vec.getSimpleValueType();
7280 
7281       // First extract the lower XLEN bits of the element.
7282       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7283 
7284       // To extract the upper XLEN bits of the vector element, shift the first
7285       // element right by 32 bits and re-extract the lower XLEN bits.
7286       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7287       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7288 
7289       SDValue ThirtyTwoV =
7290           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7291                       DAG.getConstant(32, DL, XLenVT), VL);
7292       SDValue LShr32 =
7293           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7294       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7295 
7296       Results.push_back(
7297           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7298       break;
7299     }
7300     }
7301     break;
7302   }
7303   case ISD::VECREDUCE_ADD:
7304   case ISD::VECREDUCE_AND:
7305   case ISD::VECREDUCE_OR:
7306   case ISD::VECREDUCE_XOR:
7307   case ISD::VECREDUCE_SMAX:
7308   case ISD::VECREDUCE_UMAX:
7309   case ISD::VECREDUCE_SMIN:
7310   case ISD::VECREDUCE_UMIN:
7311     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7312       Results.push_back(V);
7313     break;
7314   case ISD::VP_REDUCE_ADD:
7315   case ISD::VP_REDUCE_AND:
7316   case ISD::VP_REDUCE_OR:
7317   case ISD::VP_REDUCE_XOR:
7318   case ISD::VP_REDUCE_SMAX:
7319   case ISD::VP_REDUCE_UMAX:
7320   case ISD::VP_REDUCE_SMIN:
7321   case ISD::VP_REDUCE_UMIN:
7322     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7323       Results.push_back(V);
7324     break;
7325   case ISD::FLT_ROUNDS_: {
7326     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7327     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7328     Results.push_back(Res.getValue(0));
7329     Results.push_back(Res.getValue(1));
7330     break;
7331   }
7332   }
7333 }
7334 
7335 // A structure to hold one of the bit-manipulation patterns below. Together, a
7336 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7337 //   (or (and (shl x, 1), 0xAAAAAAAA),
7338 //       (and (srl x, 1), 0x55555555))
7339 struct RISCVBitmanipPat {
7340   SDValue Op;
7341   unsigned ShAmt;
7342   bool IsSHL;
7343 
7344   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7345     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7346   }
7347 };
7348 
7349 // Matches patterns of the form
7350 //   (and (shl x, C2), (C1 << C2))
7351 //   (and (srl x, C2), C1)
7352 //   (shl (and x, C1), C2)
7353 //   (srl (and x, (C1 << C2)), C2)
7354 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7355 // The expected masks for each shift amount are specified in BitmanipMasks where
7356 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7357 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7358 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7359 // XLen is 64.
7360 static Optional<RISCVBitmanipPat>
7361 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7362   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7363          "Unexpected number of masks");
7364   Optional<uint64_t> Mask;
7365   // Optionally consume a mask around the shift operation.
7366   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7367     Mask = Op.getConstantOperandVal(1);
7368     Op = Op.getOperand(0);
7369   }
7370   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7371     return None;
7372   bool IsSHL = Op.getOpcode() == ISD::SHL;
7373 
7374   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7375     return None;
7376   uint64_t ShAmt = Op.getConstantOperandVal(1);
7377 
7378   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7379   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7380     return None;
7381   // If we don't have enough masks for 64 bit, then we must be trying to
7382   // match SHFL so we're only allowed to shift 1/4 of the width.
7383   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7384     return None;
7385 
7386   SDValue Src = Op.getOperand(0);
7387 
7388   // The expected mask is shifted left when the AND is found around SHL
7389   // patterns.
7390   //   ((x >> 1) & 0x55555555)
7391   //   ((x << 1) & 0xAAAAAAAA)
7392   bool SHLExpMask = IsSHL;
7393 
7394   if (!Mask) {
7395     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7396     // the mask is all ones: consume that now.
7397     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7398       Mask = Src.getConstantOperandVal(1);
7399       Src = Src.getOperand(0);
7400       // The expected mask is now in fact shifted left for SRL, so reverse the
7401       // decision.
7402       //   ((x & 0xAAAAAAAA) >> 1)
7403       //   ((x & 0x55555555) << 1)
7404       SHLExpMask = !SHLExpMask;
7405     } else {
7406       // Use a default shifted mask of all-ones if there's no AND, truncated
7407       // down to the expected width. This simplifies the logic later on.
7408       Mask = maskTrailingOnes<uint64_t>(Width);
7409       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7410     }
7411   }
7412 
7413   unsigned MaskIdx = Log2_32(ShAmt);
7414   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7415 
7416   if (SHLExpMask)
7417     ExpMask <<= ShAmt;
7418 
7419   if (Mask != ExpMask)
7420     return None;
7421 
7422   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7423 }
7424 
7425 // Matches any of the following bit-manipulation patterns:
7426 //   (and (shl x, 1), (0x55555555 << 1))
7427 //   (and (srl x, 1), 0x55555555)
7428 //   (shl (and x, 0x55555555), 1)
7429 //   (srl (and x, (0x55555555 << 1)), 1)
7430 // where the shift amount and mask may vary thus:
7431 //   [1]  = 0x55555555 / 0xAAAAAAAA
7432 //   [2]  = 0x33333333 / 0xCCCCCCCC
7433 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7434 //   [8]  = 0x00FF00FF / 0xFF00FF00
7435 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7436 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7437 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7438   // These are the unshifted masks which we use to match bit-manipulation
7439   // patterns. They may be shifted left in certain circumstances.
7440   static const uint64_t BitmanipMasks[] = {
7441       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7442       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7443 
7444   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7445 }
7446 
7447 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7448 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7449   auto BinOpToRVVReduce = [](unsigned Opc) {
7450     switch (Opc) {
7451     default:
7452       llvm_unreachable("Unhandled binary to transfrom reduction");
7453     case ISD::ADD:
7454       return RISCVISD::VECREDUCE_ADD_VL;
7455     case ISD::UMAX:
7456       return RISCVISD::VECREDUCE_UMAX_VL;
7457     case ISD::SMAX:
7458       return RISCVISD::VECREDUCE_SMAX_VL;
7459     case ISD::UMIN:
7460       return RISCVISD::VECREDUCE_UMIN_VL;
7461     case ISD::SMIN:
7462       return RISCVISD::VECREDUCE_SMIN_VL;
7463     case ISD::AND:
7464       return RISCVISD::VECREDUCE_AND_VL;
7465     case ISD::OR:
7466       return RISCVISD::VECREDUCE_OR_VL;
7467     case ISD::XOR:
7468       return RISCVISD::VECREDUCE_XOR_VL;
7469     case ISD::FADD:
7470       return RISCVISD::VECREDUCE_FADD_VL;
7471     case ISD::FMAXNUM:
7472       return RISCVISD::VECREDUCE_FMAX_VL;
7473     case ISD::FMINNUM:
7474       return RISCVISD::VECREDUCE_FMIN_VL;
7475     }
7476   };
7477 
7478   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7479     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7480            isNullConstant(V.getOperand(1)) &&
7481            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7482   };
7483 
7484   unsigned Opc = N->getOpcode();
7485   unsigned ReduceIdx;
7486   if (IsReduction(N->getOperand(0), Opc))
7487     ReduceIdx = 0;
7488   else if (IsReduction(N->getOperand(1), Opc))
7489     ReduceIdx = 1;
7490   else
7491     return SDValue();
7492 
7493   // Skip if FADD disallows reassociation but the combiner needs.
7494   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7495     return SDValue();
7496 
7497   SDValue Extract = N->getOperand(ReduceIdx);
7498   SDValue Reduce = Extract.getOperand(0);
7499   if (!Reduce.hasOneUse())
7500     return SDValue();
7501 
7502   SDValue ScalarV = Reduce.getOperand(2);
7503 
7504   // Make sure that ScalarV is a splat with VL=1.
7505   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7506       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7507       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7508     return SDValue();
7509 
7510   if (!isOneConstant(ScalarV.getOperand(2)))
7511     return SDValue();
7512 
7513   // TODO: Deal with value other than neutral element.
7514   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7515     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7516         isNullFPConstant(V))
7517       return true;
7518     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7519                                  N->getFlags()) == V;
7520   };
7521 
7522   // Check the scalar of ScalarV is neutral element
7523   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7524     return SDValue();
7525 
7526   if (!ScalarV.hasOneUse())
7527     return SDValue();
7528 
7529   EVT SplatVT = ScalarV.getValueType();
7530   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7531   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7532   if (SplatVT.isInteger()) {
7533     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7534     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7535       SplatOpc = RISCVISD::VMV_S_X_VL;
7536     else
7537       SplatOpc = RISCVISD::VMV_V_X_VL;
7538   }
7539 
7540   SDValue NewScalarV =
7541       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7542                   ScalarV.getOperand(2));
7543   SDValue NewReduce =
7544       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7545                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7546                   Reduce.getOperand(3), Reduce.getOperand(4));
7547   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7548                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7549 }
7550 
7551 // Match the following pattern as a GREVI(W) operation
7552 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7553 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7554                                const RISCVSubtarget &Subtarget) {
7555   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7556   EVT VT = Op.getValueType();
7557 
7558   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7559     auto LHS = matchGREVIPat(Op.getOperand(0));
7560     auto RHS = matchGREVIPat(Op.getOperand(1));
7561     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7562       SDLoc DL(Op);
7563       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7564                          DAG.getConstant(LHS->ShAmt, DL, VT));
7565     }
7566   }
7567   return SDValue();
7568 }
7569 
7570 // Matches any the following pattern as a GORCI(W) operation
7571 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7572 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7573 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7574 // Note that with the variant of 3.,
7575 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7576 // the inner pattern will first be matched as GREVI and then the outer
7577 // pattern will be matched to GORC via the first rule above.
7578 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7579 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7580                                const RISCVSubtarget &Subtarget) {
7581   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7582   EVT VT = Op.getValueType();
7583 
7584   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7585     SDLoc DL(Op);
7586     SDValue Op0 = Op.getOperand(0);
7587     SDValue Op1 = Op.getOperand(1);
7588 
7589     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7590       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7591           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7592           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7593         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7594       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7595       if ((Reverse.getOpcode() == ISD::ROTL ||
7596            Reverse.getOpcode() == ISD::ROTR) &&
7597           Reverse.getOperand(0) == X &&
7598           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7599         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7600         if (RotAmt == (VT.getSizeInBits() / 2))
7601           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7602                              DAG.getConstant(RotAmt, DL, VT));
7603       }
7604       return SDValue();
7605     };
7606 
7607     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7608     if (SDValue V = MatchOROfReverse(Op0, Op1))
7609       return V;
7610     if (SDValue V = MatchOROfReverse(Op1, Op0))
7611       return V;
7612 
7613     // OR is commutable so canonicalize its OR operand to the left
7614     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7615       std::swap(Op0, Op1);
7616     if (Op0.getOpcode() != ISD::OR)
7617       return SDValue();
7618     SDValue OrOp0 = Op0.getOperand(0);
7619     SDValue OrOp1 = Op0.getOperand(1);
7620     auto LHS = matchGREVIPat(OrOp0);
7621     // OR is commutable so swap the operands and try again: x might have been
7622     // on the left
7623     if (!LHS) {
7624       std::swap(OrOp0, OrOp1);
7625       LHS = matchGREVIPat(OrOp0);
7626     }
7627     auto RHS = matchGREVIPat(Op1);
7628     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7629       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7630                          DAG.getConstant(LHS->ShAmt, DL, VT));
7631     }
7632   }
7633   return SDValue();
7634 }
7635 
7636 // Matches any of the following bit-manipulation patterns:
7637 //   (and (shl x, 1), (0x22222222 << 1))
7638 //   (and (srl x, 1), 0x22222222)
7639 //   (shl (and x, 0x22222222), 1)
7640 //   (srl (and x, (0x22222222 << 1)), 1)
7641 // where the shift amount and mask may vary thus:
7642 //   [1]  = 0x22222222 / 0x44444444
7643 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7644 //   [4]  = 0x00F000F0 / 0x0F000F00
7645 //   [8]  = 0x0000FF00 / 0x00FF0000
7646 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7647 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7648   // These are the unshifted masks which we use to match bit-manipulation
7649   // patterns. They may be shifted left in certain circumstances.
7650   static const uint64_t BitmanipMasks[] = {
7651       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7652       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7653 
7654   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7655 }
7656 
7657 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7658 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7659                                const RISCVSubtarget &Subtarget) {
7660   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7661   EVT VT = Op.getValueType();
7662 
7663   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7664     return SDValue();
7665 
7666   SDValue Op0 = Op.getOperand(0);
7667   SDValue Op1 = Op.getOperand(1);
7668 
7669   // Or is commutable so canonicalize the second OR to the LHS.
7670   if (Op0.getOpcode() != ISD::OR)
7671     std::swap(Op0, Op1);
7672   if (Op0.getOpcode() != ISD::OR)
7673     return SDValue();
7674 
7675   // We found an inner OR, so our operands are the operands of the inner OR
7676   // and the other operand of the outer OR.
7677   SDValue A = Op0.getOperand(0);
7678   SDValue B = Op0.getOperand(1);
7679   SDValue C = Op1;
7680 
7681   auto Match1 = matchSHFLPat(A);
7682   auto Match2 = matchSHFLPat(B);
7683 
7684   // If neither matched, we failed.
7685   if (!Match1 && !Match2)
7686     return SDValue();
7687 
7688   // We had at least one match. if one failed, try the remaining C operand.
7689   if (!Match1) {
7690     std::swap(A, C);
7691     Match1 = matchSHFLPat(A);
7692     if (!Match1)
7693       return SDValue();
7694   } else if (!Match2) {
7695     std::swap(B, C);
7696     Match2 = matchSHFLPat(B);
7697     if (!Match2)
7698       return SDValue();
7699   }
7700   assert(Match1 && Match2);
7701 
7702   // Make sure our matches pair up.
7703   if (!Match1->formsPairWith(*Match2))
7704     return SDValue();
7705 
7706   // All the remains is to make sure C is an AND with the same input, that masks
7707   // out the bits that are being shuffled.
7708   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7709       C.getOperand(0) != Match1->Op)
7710     return SDValue();
7711 
7712   uint64_t Mask = C.getConstantOperandVal(1);
7713 
7714   static const uint64_t BitmanipMasks[] = {
7715       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7716       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7717   };
7718 
7719   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7720   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7721   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7722 
7723   if (Mask != ExpMask)
7724     return SDValue();
7725 
7726   SDLoc DL(Op);
7727   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7728                      DAG.getConstant(Match1->ShAmt, DL, VT));
7729 }
7730 
7731 // Optimize (add (shl x, c0), (shl y, c1)) ->
7732 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7733 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7734                                   const RISCVSubtarget &Subtarget) {
7735   // Perform this optimization only in the zba extension.
7736   if (!Subtarget.hasStdExtZba())
7737     return SDValue();
7738 
7739   // Skip for vector types and larger types.
7740   EVT VT = N->getValueType(0);
7741   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7742     return SDValue();
7743 
7744   // The two operand nodes must be SHL and have no other use.
7745   SDValue N0 = N->getOperand(0);
7746   SDValue N1 = N->getOperand(1);
7747   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7748       !N0->hasOneUse() || !N1->hasOneUse())
7749     return SDValue();
7750 
7751   // Check c0 and c1.
7752   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7753   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7754   if (!N0C || !N1C)
7755     return SDValue();
7756   int64_t C0 = N0C->getSExtValue();
7757   int64_t C1 = N1C->getSExtValue();
7758   if (C0 <= 0 || C1 <= 0)
7759     return SDValue();
7760 
7761   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7762   int64_t Bits = std::min(C0, C1);
7763   int64_t Diff = std::abs(C0 - C1);
7764   if (Diff != 1 && Diff != 2 && Diff != 3)
7765     return SDValue();
7766 
7767   // Build nodes.
7768   SDLoc DL(N);
7769   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7770   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7771   SDValue NA0 =
7772       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7773   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7774   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7775 }
7776 
7777 // Combine
7778 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7779 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7780 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7781 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7782 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7783 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7784 // The grev patterns represents BSWAP.
7785 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7786 // off the grev.
7787 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7788                                           const RISCVSubtarget &Subtarget) {
7789   bool IsWInstruction =
7790       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7791   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7792           IsWInstruction) &&
7793          "Unexpected opcode!");
7794   SDValue Src = N->getOperand(0);
7795   EVT VT = N->getValueType(0);
7796   SDLoc DL(N);
7797 
7798   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7799     return SDValue();
7800 
7801   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7802       !isa<ConstantSDNode>(Src.getOperand(1)))
7803     return SDValue();
7804 
7805   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7806   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7807 
7808   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7809   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7810   unsigned ShAmt1 = N->getConstantOperandVal(1);
7811   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7812   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7813     return SDValue();
7814 
7815   Src = Src.getOperand(0);
7816 
7817   // Toggle bit the MSB of the shift.
7818   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7819   if (CombinedShAmt == 0)
7820     return Src;
7821 
7822   SDValue Res = DAG.getNode(
7823       RISCVISD::GREV, DL, VT, Src,
7824       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7825   if (!IsWInstruction)
7826     return Res;
7827 
7828   // Sign extend the result to match the behavior of the rotate. This will be
7829   // selected to GREVIW in isel.
7830   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7831                      DAG.getValueType(MVT::i32));
7832 }
7833 
7834 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7835 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7836 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7837 // not undo itself, but they are redundant.
7838 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7839   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7840   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7841   SDValue Src = N->getOperand(0);
7842 
7843   if (Src.getOpcode() != N->getOpcode())
7844     return SDValue();
7845 
7846   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7847       !isa<ConstantSDNode>(Src.getOperand(1)))
7848     return SDValue();
7849 
7850   unsigned ShAmt1 = N->getConstantOperandVal(1);
7851   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7852   Src = Src.getOperand(0);
7853 
7854   unsigned CombinedShAmt;
7855   if (IsGORC)
7856     CombinedShAmt = ShAmt1 | ShAmt2;
7857   else
7858     CombinedShAmt = ShAmt1 ^ ShAmt2;
7859 
7860   if (CombinedShAmt == 0)
7861     return Src;
7862 
7863   SDLoc DL(N);
7864   return DAG.getNode(
7865       N->getOpcode(), DL, N->getValueType(0), Src,
7866       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7867 }
7868 
7869 // Combine a constant select operand into its use:
7870 //
7871 // (and (select cond, -1, c), x)
7872 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7873 // (or  (select cond, 0, c), x)
7874 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7875 // (xor (select cond, 0, c), x)
7876 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7877 // (add (select cond, 0, c), x)
7878 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7879 // (sub x, (select cond, 0, c))
7880 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7881 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7882                                    SelectionDAG &DAG, bool AllOnes) {
7883   EVT VT = N->getValueType(0);
7884 
7885   // Skip vectors.
7886   if (VT.isVector())
7887     return SDValue();
7888 
7889   if ((Slct.getOpcode() != ISD::SELECT &&
7890        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7891       !Slct.hasOneUse())
7892     return SDValue();
7893 
7894   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7895     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7896   };
7897 
7898   bool SwapSelectOps;
7899   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7900   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7901   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7902   SDValue NonConstantVal;
7903   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7904     SwapSelectOps = false;
7905     NonConstantVal = FalseVal;
7906   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7907     SwapSelectOps = true;
7908     NonConstantVal = TrueVal;
7909   } else
7910     return SDValue();
7911 
7912   // Slct is now know to be the desired identity constant when CC is true.
7913   TrueVal = OtherOp;
7914   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7915   // Unless SwapSelectOps says the condition should be false.
7916   if (SwapSelectOps)
7917     std::swap(TrueVal, FalseVal);
7918 
7919   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7920     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7921                        {Slct.getOperand(0), Slct.getOperand(1),
7922                         Slct.getOperand(2), TrueVal, FalseVal});
7923 
7924   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7925                      {Slct.getOperand(0), TrueVal, FalseVal});
7926 }
7927 
7928 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7929 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7930                                               bool AllOnes) {
7931   SDValue N0 = N->getOperand(0);
7932   SDValue N1 = N->getOperand(1);
7933   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7934     return Result;
7935   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7936     return Result;
7937   return SDValue();
7938 }
7939 
7940 // Transform (add (mul x, c0), c1) ->
7941 //           (add (mul (add x, c1/c0), c0), c1%c0).
7942 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7943 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7944 // to an infinite loop in DAGCombine if transformed.
7945 // Or transform (add (mul x, c0), c1) ->
7946 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7947 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7948 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7949 // lead to an infinite loop in DAGCombine if transformed.
7950 // Or transform (add (mul x, c0), c1) ->
7951 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7952 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7953 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7954 // lead to an infinite loop in DAGCombine if transformed.
7955 // Or transform (add (mul x, c0), c1) ->
7956 //              (mul (add x, c1/c0), c0).
7957 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7958 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7959                                      const RISCVSubtarget &Subtarget) {
7960   // Skip for vector types and larger types.
7961   EVT VT = N->getValueType(0);
7962   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7963     return SDValue();
7964   // The first operand node must be a MUL and has no other use.
7965   SDValue N0 = N->getOperand(0);
7966   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7967     return SDValue();
7968   // Check if c0 and c1 match above conditions.
7969   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7970   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7971   if (!N0C || !N1C)
7972     return SDValue();
7973   // If N0C has multiple uses it's possible one of the cases in
7974   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7975   // in an infinite loop.
7976   if (!N0C->hasOneUse())
7977     return SDValue();
7978   int64_t C0 = N0C->getSExtValue();
7979   int64_t C1 = N1C->getSExtValue();
7980   int64_t CA, CB;
7981   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7982     return SDValue();
7983   // Search for proper CA (non-zero) and CB that both are simm12.
7984   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7985       !isInt<12>(C0 * (C1 / C0))) {
7986     CA = C1 / C0;
7987     CB = C1 % C0;
7988   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7989              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7990     CA = C1 / C0 + 1;
7991     CB = C1 % C0 - C0;
7992   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7993              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7994     CA = C1 / C0 - 1;
7995     CB = C1 % C0 + C0;
7996   } else
7997     return SDValue();
7998   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7999   SDLoc DL(N);
8000   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
8001                              DAG.getConstant(CA, DL, VT));
8002   SDValue New1 =
8003       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
8004   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
8005 }
8006 
8007 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
8008                                  const RISCVSubtarget &Subtarget) {
8009   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
8010     return V;
8011   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
8012     return V;
8013   if (SDValue V = combineBinOpToReduce(N, DAG))
8014     return V;
8015   // fold (add (select lhs, rhs, cc, 0, y), x) ->
8016   //      (select lhs, rhs, cc, x, (add x, y))
8017   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8018 }
8019 
8020 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8021   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8022   //      (select lhs, rhs, cc, x, (sub x, y))
8023   SDValue N0 = N->getOperand(0);
8024   SDValue N1 = N->getOperand(1);
8025   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8026 }
8027 
8028 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8029                                  const RISCVSubtarget &Subtarget) {
8030   SDValue N0 = N->getOperand(0);
8031   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8032   // extending X. This is safe since we only need the LSB after the shift and
8033   // shift amounts larger than 31 would produce poison. If we wait until
8034   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8035   // to use a BEXT instruction.
8036   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8037       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8038       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8039       N0.hasOneUse()) {
8040     SDLoc DL(N);
8041     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8042     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8043     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8044     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8045                               DAG.getConstant(1, DL, MVT::i64));
8046     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8047   }
8048 
8049   if (SDValue V = combineBinOpToReduce(N, DAG))
8050     return V;
8051 
8052   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8053   //      (select lhs, rhs, cc, x, (and x, y))
8054   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8055 }
8056 
8057 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8058                                 const RISCVSubtarget &Subtarget) {
8059   if (Subtarget.hasStdExtZbp()) {
8060     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8061       return GREV;
8062     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8063       return GORC;
8064     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8065       return SHFL;
8066   }
8067 
8068   if (SDValue V = combineBinOpToReduce(N, DAG))
8069     return V;
8070   // fold (or (select cond, 0, y), x) ->
8071   //      (select cond, x, (or x, y))
8072   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8073 }
8074 
8075 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8076   SDValue N0 = N->getOperand(0);
8077   SDValue N1 = N->getOperand(1);
8078 
8079   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8080   // NOTE: Assumes ROL being legal means ROLW is legal.
8081   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8082   if (N0.getOpcode() == RISCVISD::SLLW &&
8083       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8084       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8085     SDLoc DL(N);
8086     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8087                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8088   }
8089 
8090   if (SDValue V = combineBinOpToReduce(N, DAG))
8091     return V;
8092   // fold (xor (select cond, 0, y), x) ->
8093   //      (select cond, x, (xor x, y))
8094   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8095 }
8096 
8097 static SDValue
8098 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8099                                 const RISCVSubtarget &Subtarget) {
8100   SDValue Src = N->getOperand(0);
8101   EVT VT = N->getValueType(0);
8102 
8103   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8104   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8105       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8106     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8107                        Src.getOperand(0));
8108 
8109   // Fold (i64 (sext_inreg (abs X), i32)) ->
8110   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8111   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8112   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8113   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8114   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8115   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8116   // may get combined into an earlier operation so we need to use
8117   // ComputeNumSignBits.
8118   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8119   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8120   // we can't assume that X has 33 sign bits. We must check.
8121   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8122       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8123       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8124       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8125     SDLoc DL(N);
8126     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8127     SDValue Neg =
8128         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8129     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8130                       DAG.getValueType(MVT::i32));
8131     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8132   }
8133 
8134   return SDValue();
8135 }
8136 
8137 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8138 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8139 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8140                                              bool Commute = false) {
8141   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8142           N->getOpcode() == RISCVISD::SUB_VL) &&
8143          "Unexpected opcode");
8144   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8145   SDValue Op0 = N->getOperand(0);
8146   SDValue Op1 = N->getOperand(1);
8147   if (Commute)
8148     std::swap(Op0, Op1);
8149 
8150   MVT VT = N->getSimpleValueType(0);
8151 
8152   // Determine the narrow size for a widening add/sub.
8153   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8154   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8155                                   VT.getVectorElementCount());
8156 
8157   SDValue Mask = N->getOperand(2);
8158   SDValue VL = N->getOperand(3);
8159 
8160   SDLoc DL(N);
8161 
8162   // If the RHS is a sext or zext, we can form a widening op.
8163   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8164        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8165       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8166     unsigned ExtOpc = Op1.getOpcode();
8167     Op1 = Op1.getOperand(0);
8168     // Re-introduce narrower extends if needed.
8169     if (Op1.getValueType() != NarrowVT)
8170       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8171 
8172     unsigned WOpc;
8173     if (ExtOpc == RISCVISD::VSEXT_VL)
8174       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8175     else
8176       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8177 
8178     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8179   }
8180 
8181   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8182   // sext/zext?
8183 
8184   return SDValue();
8185 }
8186 
8187 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8188 // vwsub(u).vv/vx.
8189 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8190   SDValue Op0 = N->getOperand(0);
8191   SDValue Op1 = N->getOperand(1);
8192   SDValue Mask = N->getOperand(2);
8193   SDValue VL = N->getOperand(3);
8194 
8195   MVT VT = N->getSimpleValueType(0);
8196   MVT NarrowVT = Op1.getSimpleValueType();
8197   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8198 
8199   unsigned VOpc;
8200   switch (N->getOpcode()) {
8201   default: llvm_unreachable("Unexpected opcode");
8202   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8203   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8204   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8205   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8206   }
8207 
8208   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8209                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8210 
8211   SDLoc DL(N);
8212 
8213   // If the LHS is a sext or zext, we can narrow this op to the same size as
8214   // the RHS.
8215   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8216        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8217       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8218     unsigned ExtOpc = Op0.getOpcode();
8219     Op0 = Op0.getOperand(0);
8220     // Re-introduce narrower extends if needed.
8221     if (Op0.getValueType() != NarrowVT)
8222       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8223     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8224   }
8225 
8226   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8227                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8228 
8229   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8230   // to commute and use a vwadd(u).vx instead.
8231   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8232       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8233     Op0 = Op0.getOperand(1);
8234 
8235     // See if have enough sign bits or zero bits in the scalar to use a
8236     // widening add/sub by splatting to smaller element size.
8237     unsigned EltBits = VT.getScalarSizeInBits();
8238     unsigned ScalarBits = Op0.getValueSizeInBits();
8239     // Make sure we're getting all element bits from the scalar register.
8240     // FIXME: Support implicit sign extension of vmv.v.x?
8241     if (ScalarBits < EltBits)
8242       return SDValue();
8243 
8244     if (IsSigned) {
8245       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8246         return SDValue();
8247     } else {
8248       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8249       if (!DAG.MaskedValueIsZero(Op0, Mask))
8250         return SDValue();
8251     }
8252 
8253     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8254                       DAG.getUNDEF(NarrowVT), Op0, VL);
8255     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8256   }
8257 
8258   return SDValue();
8259 }
8260 
8261 // Try to form VWMUL, VWMULU or VWMULSU.
8262 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8263 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8264                                        bool Commute) {
8265   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8266   SDValue Op0 = N->getOperand(0);
8267   SDValue Op1 = N->getOperand(1);
8268   if (Commute)
8269     std::swap(Op0, Op1);
8270 
8271   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8272   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8273   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8274   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8275     return SDValue();
8276 
8277   SDValue Mask = N->getOperand(2);
8278   SDValue VL = N->getOperand(3);
8279 
8280   // Make sure the mask and VL match.
8281   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8282     return SDValue();
8283 
8284   MVT VT = N->getSimpleValueType(0);
8285 
8286   // Determine the narrow size for a widening multiply.
8287   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8288   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8289                                   VT.getVectorElementCount());
8290 
8291   SDLoc DL(N);
8292 
8293   // See if the other operand is the same opcode.
8294   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8295     if (!Op1.hasOneUse())
8296       return SDValue();
8297 
8298     // Make sure the mask and VL match.
8299     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8300       return SDValue();
8301 
8302     Op1 = Op1.getOperand(0);
8303   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8304     // The operand is a splat of a scalar.
8305 
8306     // The pasthru must be undef for tail agnostic
8307     if (!Op1.getOperand(0).isUndef())
8308       return SDValue();
8309     // The VL must be the same.
8310     if (Op1.getOperand(2) != VL)
8311       return SDValue();
8312 
8313     // Get the scalar value.
8314     Op1 = Op1.getOperand(1);
8315 
8316     // See if have enough sign bits or zero bits in the scalar to use a
8317     // widening multiply by splatting to smaller element size.
8318     unsigned EltBits = VT.getScalarSizeInBits();
8319     unsigned ScalarBits = Op1.getValueSizeInBits();
8320     // Make sure we're getting all element bits from the scalar register.
8321     // FIXME: Support implicit sign extension of vmv.v.x?
8322     if (ScalarBits < EltBits)
8323       return SDValue();
8324 
8325     // If the LHS is a sign extend, try to use vwmul.
8326     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8327       // Can use vwmul.
8328     } else {
8329       // Otherwise try to use vwmulu or vwmulsu.
8330       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8331       if (DAG.MaskedValueIsZero(Op1, Mask))
8332         IsVWMULSU = IsSignExt;
8333       else
8334         return SDValue();
8335     }
8336 
8337     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8338                       DAG.getUNDEF(NarrowVT), Op1, VL);
8339   } else
8340     return SDValue();
8341 
8342   Op0 = Op0.getOperand(0);
8343 
8344   // Re-introduce narrower extends if needed.
8345   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8346   if (Op0.getValueType() != NarrowVT)
8347     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8348   // vwmulsu requires second operand to be zero extended.
8349   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8350   if (Op1.getValueType() != NarrowVT)
8351     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8352 
8353   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8354   if (!IsVWMULSU)
8355     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8356   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8357 }
8358 
8359 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8360   switch (Op.getOpcode()) {
8361   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8362   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8363   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8364   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8365   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8366   }
8367 
8368   return RISCVFPRndMode::Invalid;
8369 }
8370 
8371 // Fold
8372 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8373 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8374 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8375 //   (fp_to_int (fceil X))      -> fcvt X, rup
8376 //   (fp_to_int (fround X))     -> fcvt X, rmm
8377 static SDValue performFP_TO_INTCombine(SDNode *N,
8378                                        TargetLowering::DAGCombinerInfo &DCI,
8379                                        const RISCVSubtarget &Subtarget) {
8380   SelectionDAG &DAG = DCI.DAG;
8381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8382   MVT XLenVT = Subtarget.getXLenVT();
8383 
8384   // Only handle XLen or i32 types. Other types narrower than XLen will
8385   // eventually be legalized to XLenVT.
8386   EVT VT = N->getValueType(0);
8387   if (VT != MVT::i32 && VT != XLenVT)
8388     return SDValue();
8389 
8390   SDValue Src = N->getOperand(0);
8391 
8392   // Ensure the FP type is also legal.
8393   if (!TLI.isTypeLegal(Src.getValueType()))
8394     return SDValue();
8395 
8396   // Don't do this for f16 with Zfhmin and not Zfh.
8397   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8398     return SDValue();
8399 
8400   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8401   if (FRM == RISCVFPRndMode::Invalid)
8402     return SDValue();
8403 
8404   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8405 
8406   unsigned Opc;
8407   if (VT == XLenVT)
8408     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8409   else
8410     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8411 
8412   SDLoc DL(N);
8413   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8414                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8415   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8416 }
8417 
8418 // Fold
8419 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8420 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8421 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8422 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8423 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8424 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8425                                        TargetLowering::DAGCombinerInfo &DCI,
8426                                        const RISCVSubtarget &Subtarget) {
8427   SelectionDAG &DAG = DCI.DAG;
8428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8429   MVT XLenVT = Subtarget.getXLenVT();
8430 
8431   // Only handle XLen types. Other types narrower than XLen will eventually be
8432   // legalized to XLenVT.
8433   EVT DstVT = N->getValueType(0);
8434   if (DstVT != XLenVT)
8435     return SDValue();
8436 
8437   SDValue Src = N->getOperand(0);
8438 
8439   // Ensure the FP type is also legal.
8440   if (!TLI.isTypeLegal(Src.getValueType()))
8441     return SDValue();
8442 
8443   // Don't do this for f16 with Zfhmin and not Zfh.
8444   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8445     return SDValue();
8446 
8447   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8448 
8449   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8450   if (FRM == RISCVFPRndMode::Invalid)
8451     return SDValue();
8452 
8453   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8454 
8455   unsigned Opc;
8456   if (SatVT == DstVT)
8457     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8458   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8459     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8460   else
8461     return SDValue();
8462   // FIXME: Support other SatVTs by clamping before or after the conversion.
8463 
8464   Src = Src.getOperand(0);
8465 
8466   SDLoc DL(N);
8467   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8468                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8469 
8470   // RISCV FP-to-int conversions saturate to the destination register size, but
8471   // don't produce 0 for nan.
8472   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8473   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8474 }
8475 
8476 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8477 // smaller than XLenVT.
8478 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8479                                         const RISCVSubtarget &Subtarget) {
8480   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8481 
8482   SDValue Src = N->getOperand(0);
8483   if (Src.getOpcode() != ISD::BSWAP)
8484     return SDValue();
8485 
8486   EVT VT = N->getValueType(0);
8487   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8488       !isPowerOf2_32(VT.getSizeInBits()))
8489     return SDValue();
8490 
8491   SDLoc DL(N);
8492   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8493                      DAG.getConstant(7, DL, VT));
8494 }
8495 
8496 // Convert from one FMA opcode to another based on whether we are negating the
8497 // multiply result and/or the accumulator.
8498 // NOTE: Only supports RVV operations with VL.
8499 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
8500   assert((NegMul || NegAcc) && "Not negating anything?");
8501 
8502   // Negating the multiply result changes ADD<->SUB and toggles 'N'.
8503   if (NegMul) {
8504     // clang-format off
8505     switch (Opcode) {
8506     default: llvm_unreachable("Unexpected opcode");
8507     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFNMSUB_VL; break;
8508     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL;  break;
8509     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL;  break;
8510     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFNMADD_VL; break;
8511     }
8512     // clang-format on
8513   }
8514 
8515   // Negating the accumulator changes ADD<->SUB.
8516   if (NegAcc) {
8517     // clang-format off
8518     switch (Opcode) {
8519     default: llvm_unreachable("Unexpected opcode");
8520     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFMSUB_VL;  break;
8521     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFMADD_VL;  break;
8522     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
8523     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
8524     }
8525     // clang-format on
8526   }
8527 
8528   return Opcode;
8529 }
8530 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8531                                                DAGCombinerInfo &DCI) const {
8532   SelectionDAG &DAG = DCI.DAG;
8533 
8534   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8535   // bits are demanded. N will be added to the Worklist if it was not deleted.
8536   // Caller should return SDValue(N, 0) if this returns true.
8537   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8538     SDValue Op = N->getOperand(OpNo);
8539     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8540     if (!SimplifyDemandedBits(Op, Mask, DCI))
8541       return false;
8542 
8543     if (N->getOpcode() != ISD::DELETED_NODE)
8544       DCI.AddToWorklist(N);
8545     return true;
8546   };
8547 
8548   switch (N->getOpcode()) {
8549   default:
8550     break;
8551   case RISCVISD::SplitF64: {
8552     SDValue Op0 = N->getOperand(0);
8553     // If the input to SplitF64 is just BuildPairF64 then the operation is
8554     // redundant. Instead, use BuildPairF64's operands directly.
8555     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8556       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8557 
8558     if (Op0->isUndef()) {
8559       SDValue Lo = DAG.getUNDEF(MVT::i32);
8560       SDValue Hi = DAG.getUNDEF(MVT::i32);
8561       return DCI.CombineTo(N, Lo, Hi);
8562     }
8563 
8564     SDLoc DL(N);
8565 
8566     // It's cheaper to materialise two 32-bit integers than to load a double
8567     // from the constant pool and transfer it to integer registers through the
8568     // stack.
8569     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8570       APInt V = C->getValueAPF().bitcastToAPInt();
8571       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8572       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8573       return DCI.CombineTo(N, Lo, Hi);
8574     }
8575 
8576     // This is a target-specific version of a DAGCombine performed in
8577     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8578     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8579     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8580     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8581         !Op0.getNode()->hasOneUse())
8582       break;
8583     SDValue NewSplitF64 =
8584         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8585                     Op0.getOperand(0));
8586     SDValue Lo = NewSplitF64.getValue(0);
8587     SDValue Hi = NewSplitF64.getValue(1);
8588     APInt SignBit = APInt::getSignMask(32);
8589     if (Op0.getOpcode() == ISD::FNEG) {
8590       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8591                                   DAG.getConstant(SignBit, DL, MVT::i32));
8592       return DCI.CombineTo(N, Lo, NewHi);
8593     }
8594     assert(Op0.getOpcode() == ISD::FABS);
8595     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8596                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8597     return DCI.CombineTo(N, Lo, NewHi);
8598   }
8599   case RISCVISD::SLLW:
8600   case RISCVISD::SRAW:
8601   case RISCVISD::SRLW: {
8602     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8603     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8604         SimplifyDemandedLowBitsHelper(1, 5))
8605       return SDValue(N, 0);
8606 
8607     break;
8608   }
8609   case ISD::ROTR:
8610   case ISD::ROTL:
8611   case RISCVISD::RORW:
8612   case RISCVISD::ROLW: {
8613     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8614       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8615       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8616           SimplifyDemandedLowBitsHelper(1, 5))
8617         return SDValue(N, 0);
8618     }
8619 
8620     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8621   }
8622   case RISCVISD::CLZW:
8623   case RISCVISD::CTZW: {
8624     // Only the lower 32 bits of the first operand are read
8625     if (SimplifyDemandedLowBitsHelper(0, 32))
8626       return SDValue(N, 0);
8627     break;
8628   }
8629   case RISCVISD::GREV:
8630   case RISCVISD::GORC: {
8631     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8632     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8633     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8634     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8635       return SDValue(N, 0);
8636 
8637     return combineGREVI_GORCI(N, DAG);
8638   }
8639   case RISCVISD::GREVW:
8640   case RISCVISD::GORCW: {
8641     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8642     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8643         SimplifyDemandedLowBitsHelper(1, 5))
8644       return SDValue(N, 0);
8645 
8646     break;
8647   }
8648   case RISCVISD::SHFL:
8649   case RISCVISD::UNSHFL: {
8650     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8651     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8652     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8653     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8654       return SDValue(N, 0);
8655 
8656     break;
8657   }
8658   case RISCVISD::SHFLW:
8659   case RISCVISD::UNSHFLW: {
8660     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8661     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8662         SimplifyDemandedLowBitsHelper(1, 4))
8663       return SDValue(N, 0);
8664 
8665     break;
8666   }
8667   case RISCVISD::BCOMPRESSW:
8668   case RISCVISD::BDECOMPRESSW: {
8669     // Only the lower 32 bits of LHS and RHS are read.
8670     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8671         SimplifyDemandedLowBitsHelper(1, 32))
8672       return SDValue(N, 0);
8673 
8674     break;
8675   }
8676   case RISCVISD::FSR:
8677   case RISCVISD::FSL:
8678   case RISCVISD::FSRW:
8679   case RISCVISD::FSLW: {
8680     bool IsWInstruction =
8681         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8682     unsigned BitWidth =
8683         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8684     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8685     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8686     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8687       return SDValue(N, 0);
8688 
8689     break;
8690   }
8691   case RISCVISD::FMV_X_ANYEXTH:
8692   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8693     SDLoc DL(N);
8694     SDValue Op0 = N->getOperand(0);
8695     MVT VT = N->getSimpleValueType(0);
8696     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8697     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8698     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8699     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8700          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8701         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8702          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8703       assert(Op0.getOperand(0).getValueType() == VT &&
8704              "Unexpected value type!");
8705       return Op0.getOperand(0);
8706     }
8707 
8708     // This is a target-specific version of a DAGCombine performed in
8709     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8710     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8711     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8712     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8713         !Op0.getNode()->hasOneUse())
8714       break;
8715     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8716     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8717     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8718     if (Op0.getOpcode() == ISD::FNEG)
8719       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8720                          DAG.getConstant(SignBit, DL, VT));
8721 
8722     assert(Op0.getOpcode() == ISD::FABS);
8723     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8724                        DAG.getConstant(~SignBit, DL, VT));
8725   }
8726   case ISD::ADD:
8727     return performADDCombine(N, DAG, Subtarget);
8728   case ISD::SUB:
8729     return performSUBCombine(N, DAG);
8730   case ISD::AND:
8731     return performANDCombine(N, DAG, Subtarget);
8732   case ISD::OR:
8733     return performORCombine(N, DAG, Subtarget);
8734   case ISD::XOR:
8735     return performXORCombine(N, DAG);
8736   case ISD::FADD:
8737   case ISD::UMAX:
8738   case ISD::UMIN:
8739   case ISD::SMAX:
8740   case ISD::SMIN:
8741   case ISD::FMAXNUM:
8742   case ISD::FMINNUM:
8743     return combineBinOpToReduce(N, DAG);
8744   case ISD::SIGN_EXTEND_INREG:
8745     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8746   case ISD::ZERO_EXTEND:
8747     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8748     // type legalization. This is safe because fp_to_uint produces poison if
8749     // it overflows.
8750     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8751       SDValue Src = N->getOperand(0);
8752       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8753           isTypeLegal(Src.getOperand(0).getValueType()))
8754         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8755                            Src.getOperand(0));
8756       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8757           isTypeLegal(Src.getOperand(1).getValueType())) {
8758         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8759         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8760                                   Src.getOperand(0), Src.getOperand(1));
8761         DCI.CombineTo(N, Res);
8762         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8763         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8764         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8765       }
8766     }
8767     return SDValue();
8768   case RISCVISD::SELECT_CC: {
8769     // Transform
8770     SDValue LHS = N->getOperand(0);
8771     SDValue RHS = N->getOperand(1);
8772     SDValue TrueV = N->getOperand(3);
8773     SDValue FalseV = N->getOperand(4);
8774 
8775     // If the True and False values are the same, we don't need a select_cc.
8776     if (TrueV == FalseV)
8777       return TrueV;
8778 
8779     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8780     if (!ISD::isIntEqualitySetCC(CCVal))
8781       break;
8782 
8783     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8784     //      (select_cc X, Y, lt, trueV, falseV)
8785     // Sometimes the setcc is introduced after select_cc has been formed.
8786     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8787         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8788       // If we're looking for eq 0 instead of ne 0, we need to invert the
8789       // condition.
8790       bool Invert = CCVal == ISD::SETEQ;
8791       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8792       if (Invert)
8793         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8794 
8795       SDLoc DL(N);
8796       RHS = LHS.getOperand(1);
8797       LHS = LHS.getOperand(0);
8798       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8799 
8800       SDValue TargetCC = DAG.getCondCode(CCVal);
8801       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8802                          {LHS, RHS, TargetCC, TrueV, FalseV});
8803     }
8804 
8805     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8806     //      (select_cc X, Y, eq/ne, trueV, falseV)
8807     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8808       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8809                          {LHS.getOperand(0), LHS.getOperand(1),
8810                           N->getOperand(2), TrueV, FalseV});
8811     // (select_cc X, 1, setne, trueV, falseV) ->
8812     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8813     // This can occur when legalizing some floating point comparisons.
8814     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8815     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8816       SDLoc DL(N);
8817       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8818       SDValue TargetCC = DAG.getCondCode(CCVal);
8819       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8820       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8821                          {LHS, RHS, TargetCC, TrueV, FalseV});
8822     }
8823 
8824     break;
8825   }
8826   case RISCVISD::BR_CC: {
8827     SDValue LHS = N->getOperand(1);
8828     SDValue RHS = N->getOperand(2);
8829     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8830     if (!ISD::isIntEqualitySetCC(CCVal))
8831       break;
8832 
8833     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8834     //      (br_cc X, Y, lt, dest)
8835     // Sometimes the setcc is introduced after br_cc has been formed.
8836     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8837         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8838       // If we're looking for eq 0 instead of ne 0, we need to invert the
8839       // condition.
8840       bool Invert = CCVal == ISD::SETEQ;
8841       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8842       if (Invert)
8843         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8844 
8845       SDLoc DL(N);
8846       RHS = LHS.getOperand(1);
8847       LHS = LHS.getOperand(0);
8848       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8849 
8850       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8851                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8852                          N->getOperand(4));
8853     }
8854 
8855     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8856     //      (br_cc X, Y, eq/ne, trueV, falseV)
8857     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8858       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8859                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8860                          N->getOperand(3), N->getOperand(4));
8861 
8862     // (br_cc X, 1, setne, br_cc) ->
8863     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8864     // This can occur when legalizing some floating point comparisons.
8865     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8866     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8867       SDLoc DL(N);
8868       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8869       SDValue TargetCC = DAG.getCondCode(CCVal);
8870       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8871       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8872                          N->getOperand(0), LHS, RHS, TargetCC,
8873                          N->getOperand(4));
8874     }
8875     break;
8876   }
8877   case ISD::BITREVERSE:
8878     return performBITREVERSECombine(N, DAG, Subtarget);
8879   case ISD::FP_TO_SINT:
8880   case ISD::FP_TO_UINT:
8881     return performFP_TO_INTCombine(N, DCI, Subtarget);
8882   case ISD::FP_TO_SINT_SAT:
8883   case ISD::FP_TO_UINT_SAT:
8884     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8885   case ISD::FCOPYSIGN: {
8886     EVT VT = N->getValueType(0);
8887     if (!VT.isVector())
8888       break;
8889     // There is a form of VFSGNJ which injects the negated sign of its second
8890     // operand. Try and bubble any FNEG up after the extend/round to produce
8891     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8892     // TRUNC=1.
8893     SDValue In2 = N->getOperand(1);
8894     // Avoid cases where the extend/round has multiple uses, as duplicating
8895     // those is typically more expensive than removing a fneg.
8896     if (!In2.hasOneUse())
8897       break;
8898     if (In2.getOpcode() != ISD::FP_EXTEND &&
8899         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8900       break;
8901     In2 = In2.getOperand(0);
8902     if (In2.getOpcode() != ISD::FNEG)
8903       break;
8904     SDLoc DL(N);
8905     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8906     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8907                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8908   }
8909   case ISD::MGATHER:
8910   case ISD::MSCATTER:
8911   case ISD::VP_GATHER:
8912   case ISD::VP_SCATTER: {
8913     if (!DCI.isBeforeLegalize())
8914       break;
8915     SDValue Index, ScaleOp;
8916     bool IsIndexScaled = false;
8917     bool IsIndexSigned = false;
8918     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8919       Index = VPGSN->getIndex();
8920       ScaleOp = VPGSN->getScale();
8921       IsIndexScaled = VPGSN->isIndexScaled();
8922       IsIndexSigned = VPGSN->isIndexSigned();
8923     } else {
8924       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8925       Index = MGSN->getIndex();
8926       ScaleOp = MGSN->getScale();
8927       IsIndexScaled = MGSN->isIndexScaled();
8928       IsIndexSigned = MGSN->isIndexSigned();
8929     }
8930     EVT IndexVT = Index.getValueType();
8931     MVT XLenVT = Subtarget.getXLenVT();
8932     // RISCV indexed loads only support the "unsigned unscaled" addressing
8933     // mode, so anything else must be manually legalized.
8934     bool NeedsIdxLegalization =
8935         IsIndexScaled ||
8936         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8937     if (!NeedsIdxLegalization)
8938       break;
8939 
8940     SDLoc DL(N);
8941 
8942     // Any index legalization should first promote to XLenVT, so we don't lose
8943     // bits when scaling. This may create an illegal index type so we let
8944     // LLVM's legalization take care of the splitting.
8945     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8946     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8947       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8948       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8949                           DL, IndexVT, Index);
8950     }
8951 
8952     if (IsIndexScaled) {
8953       // Manually scale the indices.
8954       // TODO: Sanitize the scale operand here?
8955       // TODO: For VP nodes, should we use VP_SHL here?
8956       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8957       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8958       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8959       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8960       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
8961     }
8962 
8963     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
8964     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8965       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8966                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8967                               ScaleOp, VPGN->getMask(),
8968                               VPGN->getVectorLength()},
8969                              VPGN->getMemOperand(), NewIndexTy);
8970     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8971       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8972                               {VPSN->getChain(), VPSN->getValue(),
8973                                VPSN->getBasePtr(), Index, ScaleOp,
8974                                VPSN->getMask(), VPSN->getVectorLength()},
8975                               VPSN->getMemOperand(), NewIndexTy);
8976     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8977       return DAG.getMaskedGather(
8978           N->getVTList(), MGN->getMemoryVT(), DL,
8979           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8980            MGN->getBasePtr(), Index, ScaleOp},
8981           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8982     const auto *MSN = cast<MaskedScatterSDNode>(N);
8983     return DAG.getMaskedScatter(
8984         N->getVTList(), MSN->getMemoryVT(), DL,
8985         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8986          Index, ScaleOp},
8987         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8988   }
8989   case RISCVISD::SRA_VL:
8990   case RISCVISD::SRL_VL:
8991   case RISCVISD::SHL_VL: {
8992     SDValue ShAmt = N->getOperand(1);
8993     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8994       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8995       SDLoc DL(N);
8996       SDValue VL = N->getOperand(3);
8997       EVT VT = N->getValueType(0);
8998       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8999                           ShAmt.getOperand(1), VL);
9000       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
9001                          N->getOperand(2), N->getOperand(3));
9002     }
9003     break;
9004   }
9005   case ISD::SRA:
9006   case ISD::SRL:
9007   case ISD::SHL: {
9008     SDValue ShAmt = N->getOperand(1);
9009     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9010       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9011       SDLoc DL(N);
9012       EVT VT = N->getValueType(0);
9013       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9014                           ShAmt.getOperand(1),
9015                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
9016       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
9017     }
9018     break;
9019   }
9020   case RISCVISD::ADD_VL:
9021     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
9022       return V;
9023     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
9024   case RISCVISD::SUB_VL:
9025     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
9026   case RISCVISD::VWADD_W_VL:
9027   case RISCVISD::VWADDU_W_VL:
9028   case RISCVISD::VWSUB_W_VL:
9029   case RISCVISD::VWSUBU_W_VL:
9030     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
9031   case RISCVISD::MUL_VL:
9032     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
9033       return V;
9034     // Mul is commutative.
9035     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
9036   case RISCVISD::VFMADD_VL:
9037   case RISCVISD::VFNMADD_VL:
9038   case RISCVISD::VFMSUB_VL:
9039   case RISCVISD::VFNMSUB_VL: {
9040     // Fold FNEG_VL into FMA opcodes.
9041     SDValue A = N->getOperand(0);
9042     SDValue B = N->getOperand(1);
9043     SDValue C = N->getOperand(2);
9044     SDValue Mask = N->getOperand(3);
9045     SDValue VL = N->getOperand(4);
9046 
9047     auto invertIfNegative = [&Mask, &VL](SDValue &V) {
9048       if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask &&
9049           V.getOperand(2) == VL) {
9050         // Return the negated input.
9051         V = V.getOperand(0);
9052         return true;
9053       }
9054 
9055       return false;
9056     };
9057 
9058     bool NegA = invertIfNegative(A);
9059     bool NegB = invertIfNegative(B);
9060     bool NegC = invertIfNegative(C);
9061 
9062     // If no operands are negated, we're done.
9063     if (!NegA && !NegB && !NegC)
9064       return SDValue();
9065 
9066     unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
9067     return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask,
9068                        VL);
9069   }
9070   case ISD::STORE: {
9071     auto *Store = cast<StoreSDNode>(N);
9072     SDValue Val = Store->getValue();
9073     // Combine store of vmv.x.s to vse with VL of 1.
9074     // FIXME: Support FP.
9075     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
9076       SDValue Src = Val.getOperand(0);
9077       EVT VecVT = Src.getValueType();
9078       EVT MemVT = Store->getMemoryVT();
9079       // The memory VT and the element type must match.
9080       if (VecVT.getVectorElementType() == MemVT) {
9081         SDLoc DL(N);
9082         MVT MaskVT = getMaskTypeFor(VecVT);
9083         return DAG.getStoreVP(
9084             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
9085             DAG.getConstant(1, DL, MaskVT),
9086             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
9087             Store->getMemOperand(), Store->getAddressingMode(),
9088             Store->isTruncatingStore(), /*IsCompress*/ false);
9089       }
9090     }
9091 
9092     break;
9093   }
9094   case ISD::SPLAT_VECTOR: {
9095     EVT VT = N->getValueType(0);
9096     // Only perform this combine on legal MVT types.
9097     if (!isTypeLegal(VT))
9098       break;
9099     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9100                                          DAG, Subtarget))
9101       return Gather;
9102     break;
9103   }
9104   case RISCVISD::VMV_V_X_VL: {
9105     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9106     // scalar input.
9107     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9108     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9109     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9110       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9111         return SDValue(N, 0);
9112 
9113     break;
9114   }
9115   case ISD::INTRINSIC_WO_CHAIN: {
9116     unsigned IntNo = N->getConstantOperandVal(0);
9117     switch (IntNo) {
9118       // By default we do not combine any intrinsic.
9119     default:
9120       return SDValue();
9121     case Intrinsic::riscv_vcpop:
9122     case Intrinsic::riscv_vcpop_mask:
9123     case Intrinsic::riscv_vfirst:
9124     case Intrinsic::riscv_vfirst_mask: {
9125       SDValue VL = N->getOperand(2);
9126       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9127           IntNo == Intrinsic::riscv_vfirst_mask)
9128         VL = N->getOperand(3);
9129       if (!isNullConstant(VL))
9130         return SDValue();
9131       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9132       SDLoc DL(N);
9133       EVT VT = N->getValueType(0);
9134       if (IntNo == Intrinsic::riscv_vfirst ||
9135           IntNo == Intrinsic::riscv_vfirst_mask)
9136         return DAG.getConstant(-1, DL, VT);
9137       return DAG.getConstant(0, DL, VT);
9138     }
9139     }
9140   }
9141   case ISD::BITCAST: {
9142     assert(Subtarget.useRVVForFixedLengthVectors());
9143     SDValue N0 = N->getOperand(0);
9144     EVT VT = N->getValueType(0);
9145     EVT SrcVT = N0.getValueType();
9146     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9147     // type, widen both sides to avoid a trip through memory.
9148     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9149         VT.isScalarInteger()) {
9150       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9151       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9152       Ops[0] = N0;
9153       SDLoc DL(N);
9154       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9155       N0 = DAG.getBitcast(MVT::i8, N0);
9156       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9157     }
9158 
9159     return SDValue();
9160   }
9161   }
9162 
9163   return SDValue();
9164 }
9165 
9166 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9167     const SDNode *N, CombineLevel Level) const {
9168   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9169   // materialised in fewer instructions than `(OP _, c1)`:
9170   //
9171   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9172   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9173   SDValue N0 = N->getOperand(0);
9174   EVT Ty = N0.getValueType();
9175   if (Ty.isScalarInteger() &&
9176       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9177     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9178     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9179     if (C1 && C2) {
9180       const APInt &C1Int = C1->getAPIntValue();
9181       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9182 
9183       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9184       // and the combine should happen, to potentially allow further combines
9185       // later.
9186       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9187           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9188         return true;
9189 
9190       // We can materialise `c1` in an add immediate, so it's "free", and the
9191       // combine should be prevented.
9192       if (C1Int.getMinSignedBits() <= 64 &&
9193           isLegalAddImmediate(C1Int.getSExtValue()))
9194         return false;
9195 
9196       // Neither constant will fit into an immediate, so find materialisation
9197       // costs.
9198       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9199                                               Subtarget.getFeatureBits(),
9200                                               /*CompressionCost*/true);
9201       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9202           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9203           /*CompressionCost*/true);
9204 
9205       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9206       // combine should be prevented.
9207       if (C1Cost < ShiftedC1Cost)
9208         return false;
9209     }
9210   }
9211   return true;
9212 }
9213 
9214 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9215     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9216     TargetLoweringOpt &TLO) const {
9217   // Delay this optimization as late as possible.
9218   if (!TLO.LegalOps)
9219     return false;
9220 
9221   EVT VT = Op.getValueType();
9222   if (VT.isVector())
9223     return false;
9224 
9225   // Only handle AND for now.
9226   if (Op.getOpcode() != ISD::AND)
9227     return false;
9228 
9229   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9230   if (!C)
9231     return false;
9232 
9233   const APInt &Mask = C->getAPIntValue();
9234 
9235   // Clear all non-demanded bits initially.
9236   APInt ShrunkMask = Mask & DemandedBits;
9237 
9238   // Try to make a smaller immediate by setting undemanded bits.
9239 
9240   APInt ExpandedMask = Mask | ~DemandedBits;
9241 
9242   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9243     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9244   };
9245   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9246     if (NewMask == Mask)
9247       return true;
9248     SDLoc DL(Op);
9249     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9250     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9251     return TLO.CombineTo(Op, NewOp);
9252   };
9253 
9254   // If the shrunk mask fits in sign extended 12 bits, let the target
9255   // independent code apply it.
9256   if (ShrunkMask.isSignedIntN(12))
9257     return false;
9258 
9259   // Preserve (and X, 0xffff) when zext.h is supported.
9260   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9261     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9262     if (IsLegalMask(NewMask))
9263       return UseMask(NewMask);
9264   }
9265 
9266   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9267   if (VT == MVT::i64) {
9268     APInt NewMask = APInt(64, 0xffffffff);
9269     if (IsLegalMask(NewMask))
9270       return UseMask(NewMask);
9271   }
9272 
9273   // For the remaining optimizations, we need to be able to make a negative
9274   // number through a combination of mask and undemanded bits.
9275   if (!ExpandedMask.isNegative())
9276     return false;
9277 
9278   // What is the fewest number of bits we need to represent the negative number.
9279   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9280 
9281   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9282   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9283   APInt NewMask = ShrunkMask;
9284   if (MinSignedBits <= 12)
9285     NewMask.setBitsFrom(11);
9286   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9287     NewMask.setBitsFrom(31);
9288   else
9289     return false;
9290 
9291   // Check that our new mask is a subset of the demanded mask.
9292   assert(IsLegalMask(NewMask));
9293   return UseMask(NewMask);
9294 }
9295 
9296 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9297   static const uint64_t GREVMasks[] = {
9298       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9299       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9300 
9301   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9302     unsigned Shift = 1 << Stage;
9303     if (ShAmt & Shift) {
9304       uint64_t Mask = GREVMasks[Stage];
9305       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9306       if (IsGORC)
9307         Res |= x;
9308       x = Res;
9309     }
9310   }
9311 
9312   return x;
9313 }
9314 
9315 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9316                                                         KnownBits &Known,
9317                                                         const APInt &DemandedElts,
9318                                                         const SelectionDAG &DAG,
9319                                                         unsigned Depth) const {
9320   unsigned BitWidth = Known.getBitWidth();
9321   unsigned Opc = Op.getOpcode();
9322   assert((Opc >= ISD::BUILTIN_OP_END ||
9323           Opc == ISD::INTRINSIC_WO_CHAIN ||
9324           Opc == ISD::INTRINSIC_W_CHAIN ||
9325           Opc == ISD::INTRINSIC_VOID) &&
9326          "Should use MaskedValueIsZero if you don't know whether Op"
9327          " is a target node!");
9328 
9329   Known.resetAll();
9330   switch (Opc) {
9331   default: break;
9332   case RISCVISD::SELECT_CC: {
9333     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9334     // If we don't know any bits, early out.
9335     if (Known.isUnknown())
9336       break;
9337     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9338 
9339     // Only known if known in both the LHS and RHS.
9340     Known = KnownBits::commonBits(Known, Known2);
9341     break;
9342   }
9343   case RISCVISD::REMUW: {
9344     KnownBits Known2;
9345     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9346     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9347     // We only care about the lower 32 bits.
9348     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9349     // Restore the original width by sign extending.
9350     Known = Known.sext(BitWidth);
9351     break;
9352   }
9353   case RISCVISD::DIVUW: {
9354     KnownBits Known2;
9355     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9356     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9357     // We only care about the lower 32 bits.
9358     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9359     // Restore the original width by sign extending.
9360     Known = Known.sext(BitWidth);
9361     break;
9362   }
9363   case RISCVISD::CTZW: {
9364     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9365     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9366     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9367     Known.Zero.setBitsFrom(LowBits);
9368     break;
9369   }
9370   case RISCVISD::CLZW: {
9371     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9372     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9373     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9374     Known.Zero.setBitsFrom(LowBits);
9375     break;
9376   }
9377   case RISCVISD::GREV:
9378   case RISCVISD::GORC: {
9379     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9380       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9381       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9382       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9383       // To compute zeros, we need to invert the value and invert it back after.
9384       Known.Zero =
9385           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9386       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9387     }
9388     break;
9389   }
9390   case RISCVISD::READ_VLENB: {
9391     // We can use the minimum and maximum VLEN values to bound VLENB.  We
9392     // know VLEN must be a power of two.
9393     const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8;
9394     const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8;
9395     assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?");
9396     Known.Zero.setLowBits(Log2_32(MinVLenB));
9397     Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1);
9398     if (MaxVLenB == MinVLenB)
9399       Known.One.setBit(Log2_32(MinVLenB));
9400     break;
9401   }
9402   case ISD::INTRINSIC_W_CHAIN:
9403   case ISD::INTRINSIC_WO_CHAIN: {
9404     unsigned IntNo =
9405         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9406     switch (IntNo) {
9407     default:
9408       // We can't do anything for most intrinsics.
9409       break;
9410     case Intrinsic::riscv_vsetvli:
9411     case Intrinsic::riscv_vsetvlimax:
9412     case Intrinsic::riscv_vsetvli_opt:
9413     case Intrinsic::riscv_vsetvlimax_opt:
9414       // Assume that VL output is positive and would fit in an int32_t.
9415       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9416       if (BitWidth >= 32)
9417         Known.Zero.setBitsFrom(31);
9418       break;
9419     }
9420     break;
9421   }
9422   }
9423 }
9424 
9425 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9426     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9427     unsigned Depth) const {
9428   switch (Op.getOpcode()) {
9429   default:
9430     break;
9431   case RISCVISD::SELECT_CC: {
9432     unsigned Tmp =
9433         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9434     if (Tmp == 1) return 1;  // Early out.
9435     unsigned Tmp2 =
9436         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9437     return std::min(Tmp, Tmp2);
9438   }
9439   case RISCVISD::SLLW:
9440   case RISCVISD::SRAW:
9441   case RISCVISD::SRLW:
9442   case RISCVISD::DIVW:
9443   case RISCVISD::DIVUW:
9444   case RISCVISD::REMUW:
9445   case RISCVISD::ROLW:
9446   case RISCVISD::RORW:
9447   case RISCVISD::GREVW:
9448   case RISCVISD::GORCW:
9449   case RISCVISD::FSLW:
9450   case RISCVISD::FSRW:
9451   case RISCVISD::SHFLW:
9452   case RISCVISD::UNSHFLW:
9453   case RISCVISD::BCOMPRESSW:
9454   case RISCVISD::BDECOMPRESSW:
9455   case RISCVISD::BFPW:
9456   case RISCVISD::FCVT_W_RV64:
9457   case RISCVISD::FCVT_WU_RV64:
9458   case RISCVISD::STRICT_FCVT_W_RV64:
9459   case RISCVISD::STRICT_FCVT_WU_RV64:
9460     // TODO: As the result is sign-extended, this is conservatively correct. A
9461     // more precise answer could be calculated for SRAW depending on known
9462     // bits in the shift amount.
9463     return 33;
9464   case RISCVISD::SHFL:
9465   case RISCVISD::UNSHFL: {
9466     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9467     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9468     // will stay within the upper 32 bits. If there were more than 32 sign bits
9469     // before there will be at least 33 sign bits after.
9470     if (Op.getValueType() == MVT::i64 &&
9471         isa<ConstantSDNode>(Op.getOperand(1)) &&
9472         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9473       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9474       if (Tmp > 32)
9475         return 33;
9476     }
9477     break;
9478   }
9479   case RISCVISD::VMV_X_S: {
9480     // The number of sign bits of the scalar result is computed by obtaining the
9481     // element type of the input vector operand, subtracting its width from the
9482     // XLEN, and then adding one (sign bit within the element type). If the
9483     // element type is wider than XLen, the least-significant XLEN bits are
9484     // taken.
9485     unsigned XLen = Subtarget.getXLen();
9486     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9487     if (EltBits <= XLen)
9488       return XLen - EltBits + 1;
9489     break;
9490   }
9491   }
9492 
9493   return 1;
9494 }
9495 
9496 const Constant *
9497 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9498   assert(Ld && "Unexpected null LoadSDNode");
9499   if (!ISD::isNormalLoad(Ld))
9500     return nullptr;
9501 
9502   SDValue Ptr = Ld->getBasePtr();
9503 
9504   // Only constant pools with no offset are supported.
9505   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9506     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9507     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9508         CNode->getOffset() != 0)
9509       return nullptr;
9510 
9511     return CNode;
9512   };
9513 
9514   // Simple case, LLA.
9515   if (Ptr.getOpcode() == RISCVISD::LLA) {
9516     auto *CNode = GetSupportedConstantPool(Ptr);
9517     if (!CNode || CNode->getTargetFlags() != 0)
9518       return nullptr;
9519 
9520     return CNode->getConstVal();
9521   }
9522 
9523   // Look for a HI and ADD_LO pair.
9524   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9525       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9526     return nullptr;
9527 
9528   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9529   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9530 
9531   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9532       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9533     return nullptr;
9534 
9535   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9536     return nullptr;
9537 
9538   return CNodeLo->getConstVal();
9539 }
9540 
9541 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9542                                                   MachineBasicBlock *BB) {
9543   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9544 
9545   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9546   // Should the count have wrapped while it was being read, we need to try
9547   // again.
9548   // ...
9549   // read:
9550   // rdcycleh x3 # load high word of cycle
9551   // rdcycle  x2 # load low word of cycle
9552   // rdcycleh x4 # load high word of cycle
9553   // bne x3, x4, read # check if high word reads match, otherwise try again
9554   // ...
9555 
9556   MachineFunction &MF = *BB->getParent();
9557   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9558   MachineFunction::iterator It = ++BB->getIterator();
9559 
9560   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9561   MF.insert(It, LoopMBB);
9562 
9563   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9564   MF.insert(It, DoneMBB);
9565 
9566   // Transfer the remainder of BB and its successor edges to DoneMBB.
9567   DoneMBB->splice(DoneMBB->begin(), BB,
9568                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9569   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9570 
9571   BB->addSuccessor(LoopMBB);
9572 
9573   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9574   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9575   Register LoReg = MI.getOperand(0).getReg();
9576   Register HiReg = MI.getOperand(1).getReg();
9577   DebugLoc DL = MI.getDebugLoc();
9578 
9579   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9580   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9581       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9582       .addReg(RISCV::X0);
9583   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9584       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9585       .addReg(RISCV::X0);
9586   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9587       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9588       .addReg(RISCV::X0);
9589 
9590   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9591       .addReg(HiReg)
9592       .addReg(ReadAgainReg)
9593       .addMBB(LoopMBB);
9594 
9595   LoopMBB->addSuccessor(LoopMBB);
9596   LoopMBB->addSuccessor(DoneMBB);
9597 
9598   MI.eraseFromParent();
9599 
9600   return DoneMBB;
9601 }
9602 
9603 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9604                                              MachineBasicBlock *BB) {
9605   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9606 
9607   MachineFunction &MF = *BB->getParent();
9608   DebugLoc DL = MI.getDebugLoc();
9609   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9610   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9611   Register LoReg = MI.getOperand(0).getReg();
9612   Register HiReg = MI.getOperand(1).getReg();
9613   Register SrcReg = MI.getOperand(2).getReg();
9614   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9615   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9616 
9617   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9618                           RI);
9619   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9620   MachineMemOperand *MMOLo =
9621       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9622   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9623       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9624   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9625       .addFrameIndex(FI)
9626       .addImm(0)
9627       .addMemOperand(MMOLo);
9628   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9629       .addFrameIndex(FI)
9630       .addImm(4)
9631       .addMemOperand(MMOHi);
9632   MI.eraseFromParent(); // The pseudo instruction is gone now.
9633   return BB;
9634 }
9635 
9636 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9637                                                  MachineBasicBlock *BB) {
9638   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9639          "Unexpected instruction");
9640 
9641   MachineFunction &MF = *BB->getParent();
9642   DebugLoc DL = MI.getDebugLoc();
9643   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9644   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9645   Register DstReg = MI.getOperand(0).getReg();
9646   Register LoReg = MI.getOperand(1).getReg();
9647   Register HiReg = MI.getOperand(2).getReg();
9648   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9649   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9650 
9651   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9652   MachineMemOperand *MMOLo =
9653       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9654   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9655       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9656   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9657       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9658       .addFrameIndex(FI)
9659       .addImm(0)
9660       .addMemOperand(MMOLo);
9661   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9662       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9663       .addFrameIndex(FI)
9664       .addImm(4)
9665       .addMemOperand(MMOHi);
9666   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9667   MI.eraseFromParent(); // The pseudo instruction is gone now.
9668   return BB;
9669 }
9670 
9671 static bool isSelectPseudo(MachineInstr &MI) {
9672   switch (MI.getOpcode()) {
9673   default:
9674     return false;
9675   case RISCV::Select_GPR_Using_CC_GPR:
9676   case RISCV::Select_FPR16_Using_CC_GPR:
9677   case RISCV::Select_FPR32_Using_CC_GPR:
9678   case RISCV::Select_FPR64_Using_CC_GPR:
9679     return true;
9680   }
9681 }
9682 
9683 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9684                                         unsigned RelOpcode, unsigned EqOpcode,
9685                                         const RISCVSubtarget &Subtarget) {
9686   DebugLoc DL = MI.getDebugLoc();
9687   Register DstReg = MI.getOperand(0).getReg();
9688   Register Src1Reg = MI.getOperand(1).getReg();
9689   Register Src2Reg = MI.getOperand(2).getReg();
9690   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9691   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9692   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9693 
9694   // Save the current FFLAGS.
9695   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9696 
9697   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9698                  .addReg(Src1Reg)
9699                  .addReg(Src2Reg);
9700   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9701     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9702 
9703   // Restore the FFLAGS.
9704   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9705       .addReg(SavedFFlags, RegState::Kill);
9706 
9707   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9708   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9709                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9710                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9711   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9712     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9713 
9714   // Erase the pseudoinstruction.
9715   MI.eraseFromParent();
9716   return BB;
9717 }
9718 
9719 static MachineBasicBlock *
9720 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second,
9721                           MachineBasicBlock *ThisMBB,
9722                           const RISCVSubtarget &Subtarget) {
9723   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)
9724   // Without this, custom-inserter would have generated:
9725   //
9726   //   A
9727   //   | \
9728   //   |  B
9729   //   | /
9730   //   C
9731   //   | \
9732   //   |  D
9733   //   | /
9734   //   E
9735   //
9736   // A: X = ...; Y = ...
9737   // B: empty
9738   // C: Z = PHI [X, A], [Y, B]
9739   // D: empty
9740   // E: PHI [X, C], [Z, D]
9741   //
9742   // If we lower both Select_FPRX_ in a single step, we can instead generate:
9743   //
9744   //   A
9745   //   | \
9746   //   |  C
9747   //   | /|
9748   //   |/ |
9749   //   |  |
9750   //   |  D
9751   //   | /
9752   //   E
9753   //
9754   // A: X = ...; Y = ...
9755   // D: empty
9756   // E: PHI [X, A], [X, C], [Y, D]
9757 
9758   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9759   const DebugLoc &DL = First.getDebugLoc();
9760   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
9761   MachineFunction *F = ThisMBB->getParent();
9762   MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB);
9763   MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB);
9764   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9765   MachineFunction::iterator It = ++ThisMBB->getIterator();
9766   F->insert(It, FirstMBB);
9767   F->insert(It, SecondMBB);
9768   F->insert(It, SinkMBB);
9769 
9770   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
9771   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
9772                   std::next(MachineBasicBlock::iterator(First)),
9773                   ThisMBB->end());
9774   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
9775 
9776   // Fallthrough block for ThisMBB.
9777   ThisMBB->addSuccessor(FirstMBB);
9778   // Fallthrough block for FirstMBB.
9779   FirstMBB->addSuccessor(SecondMBB);
9780   ThisMBB->addSuccessor(SinkMBB);
9781   FirstMBB->addSuccessor(SinkMBB);
9782   // This is fallthrough.
9783   SecondMBB->addSuccessor(SinkMBB);
9784 
9785   auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm());
9786   Register FLHS = First.getOperand(1).getReg();
9787   Register FRHS = First.getOperand(2).getReg();
9788   // Insert appropriate branch.
9789   BuildMI(ThisMBB, DL, TII.getBrCond(FirstCC))
9790       .addReg(FLHS)
9791       .addReg(FRHS)
9792       .addMBB(SinkMBB);
9793 
9794   Register SLHS = Second.getOperand(1).getReg();
9795   Register SRHS = Second.getOperand(2).getReg();
9796   Register Op1Reg4 = First.getOperand(4).getReg();
9797   Register Op1Reg5 = First.getOperand(5).getReg();
9798 
9799   auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm());
9800   // Insert appropriate branch.
9801   BuildMI(FirstMBB, DL, TII.getBrCond(SecondCC))
9802       .addReg(SLHS)
9803       .addReg(SRHS)
9804       .addMBB(SinkMBB);
9805 
9806   Register DestReg = Second.getOperand(0).getReg();
9807   Register Op2Reg4 = Second.getOperand(4).getReg();
9808   BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg)
9809       .addReg(Op1Reg4)
9810       .addMBB(ThisMBB)
9811       .addReg(Op2Reg4)
9812       .addMBB(FirstMBB)
9813       .addReg(Op1Reg5)
9814       .addMBB(SecondMBB);
9815 
9816   // Now remove the Select_FPRX_s.
9817   First.eraseFromParent();
9818   Second.eraseFromParent();
9819   return SinkMBB;
9820 }
9821 
9822 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9823                                            MachineBasicBlock *BB,
9824                                            const RISCVSubtarget &Subtarget) {
9825   // To "insert" Select_* instructions, we actually have to insert the triangle
9826   // control-flow pattern.  The incoming instructions know the destination vreg
9827   // to set, the condition code register to branch on, the true/false values to
9828   // select between, and the condcode to use to select the appropriate branch.
9829   //
9830   // We produce the following control flow:
9831   //     HeadMBB
9832   //     |  \
9833   //     |  IfFalseMBB
9834   //     | /
9835   //    TailMBB
9836   //
9837   // When we find a sequence of selects we attempt to optimize their emission
9838   // by sharing the control flow. Currently we only handle cases where we have
9839   // multiple selects with the exact same condition (same LHS, RHS and CC).
9840   // The selects may be interleaved with other instructions if the other
9841   // instructions meet some requirements we deem safe:
9842   // - They are debug instructions. Otherwise,
9843   // - They do not have side-effects, do not access memory and their inputs do
9844   //   not depend on the results of the select pseudo-instructions.
9845   // The TrueV/FalseV operands of the selects cannot depend on the result of
9846   // previous selects in the sequence.
9847   // These conditions could be further relaxed. See the X86 target for a
9848   // related approach and more information.
9849   //
9850   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5))
9851   // is checked here and handled by a separate function -
9852   // EmitLoweredCascadedSelect.
9853   Register LHS = MI.getOperand(1).getReg();
9854   Register RHS = MI.getOperand(2).getReg();
9855   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9856 
9857   SmallVector<MachineInstr *, 4> SelectDebugValues;
9858   SmallSet<Register, 4> SelectDests;
9859   SelectDests.insert(MI.getOperand(0).getReg());
9860 
9861   MachineInstr *LastSelectPseudo = &MI;
9862   auto Next = next_nodbg(MI.getIterator(), BB->instr_end());
9863   if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() &&
9864       Next->getOpcode() == MI.getOpcode() &&
9865       Next->getOperand(5).getReg() == MI.getOperand(0).getReg() &&
9866       Next->getOperand(5).isKill()) {
9867     return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget);
9868   }
9869 
9870   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9871        SequenceMBBI != E; ++SequenceMBBI) {
9872     if (SequenceMBBI->isDebugInstr())
9873       continue;
9874     if (isSelectPseudo(*SequenceMBBI)) {
9875       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9876           SequenceMBBI->getOperand(2).getReg() != RHS ||
9877           SequenceMBBI->getOperand(3).getImm() != CC ||
9878           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9879           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9880         break;
9881       LastSelectPseudo = &*SequenceMBBI;
9882       SequenceMBBI->collectDebugValues(SelectDebugValues);
9883       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9884     } else {
9885       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9886           SequenceMBBI->mayLoadOrStore())
9887         break;
9888       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9889             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9890           }))
9891         break;
9892     }
9893   }
9894 
9895   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9896   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9897   DebugLoc DL = MI.getDebugLoc();
9898   MachineFunction::iterator I = ++BB->getIterator();
9899 
9900   MachineBasicBlock *HeadMBB = BB;
9901   MachineFunction *F = BB->getParent();
9902   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9904 
9905   F->insert(I, IfFalseMBB);
9906   F->insert(I, TailMBB);
9907 
9908   // Transfer debug instructions associated with the selects to TailMBB.
9909   for (MachineInstr *DebugInstr : SelectDebugValues) {
9910     TailMBB->push_back(DebugInstr->removeFromParent());
9911   }
9912 
9913   // Move all instructions after the sequence to TailMBB.
9914   TailMBB->splice(TailMBB->end(), HeadMBB,
9915                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9916   // Update machine-CFG edges by transferring all successors of the current
9917   // block to the new block which will contain the Phi nodes for the selects.
9918   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9919   // Set the successors for HeadMBB.
9920   HeadMBB->addSuccessor(IfFalseMBB);
9921   HeadMBB->addSuccessor(TailMBB);
9922 
9923   // Insert appropriate branch.
9924   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9925     .addReg(LHS)
9926     .addReg(RHS)
9927     .addMBB(TailMBB);
9928 
9929   // IfFalseMBB just falls through to TailMBB.
9930   IfFalseMBB->addSuccessor(TailMBB);
9931 
9932   // Create PHIs for all of the select pseudo-instructions.
9933   auto SelectMBBI = MI.getIterator();
9934   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9935   auto InsertionPoint = TailMBB->begin();
9936   while (SelectMBBI != SelectEnd) {
9937     auto Next = std::next(SelectMBBI);
9938     if (isSelectPseudo(*SelectMBBI)) {
9939       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9940       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9941               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9942           .addReg(SelectMBBI->getOperand(4).getReg())
9943           .addMBB(HeadMBB)
9944           .addReg(SelectMBBI->getOperand(5).getReg())
9945           .addMBB(IfFalseMBB);
9946       SelectMBBI->eraseFromParent();
9947     }
9948     SelectMBBI = Next;
9949   }
9950 
9951   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9952   return TailMBB;
9953 }
9954 
9955 MachineBasicBlock *
9956 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9957                                                  MachineBasicBlock *BB) const {
9958   switch (MI.getOpcode()) {
9959   default:
9960     llvm_unreachable("Unexpected instr type to insert");
9961   case RISCV::ReadCycleWide:
9962     assert(!Subtarget.is64Bit() &&
9963            "ReadCycleWrite is only to be used on riscv32");
9964     return emitReadCycleWidePseudo(MI, BB);
9965   case RISCV::Select_GPR_Using_CC_GPR:
9966   case RISCV::Select_FPR16_Using_CC_GPR:
9967   case RISCV::Select_FPR32_Using_CC_GPR:
9968   case RISCV::Select_FPR64_Using_CC_GPR:
9969     return emitSelectPseudo(MI, BB, Subtarget);
9970   case RISCV::BuildPairF64Pseudo:
9971     return emitBuildPairF64Pseudo(MI, BB);
9972   case RISCV::SplitF64Pseudo:
9973     return emitSplitF64Pseudo(MI, BB);
9974   case RISCV::PseudoQuietFLE_H:
9975     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9976   case RISCV::PseudoQuietFLT_H:
9977     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9978   case RISCV::PseudoQuietFLE_S:
9979     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9980   case RISCV::PseudoQuietFLT_S:
9981     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9982   case RISCV::PseudoQuietFLE_D:
9983     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9984   case RISCV::PseudoQuietFLT_D:
9985     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9986   }
9987 }
9988 
9989 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9990                                                         SDNode *Node) const {
9991   // Add FRM dependency to any instructions with dynamic rounding mode.
9992   unsigned Opc = MI.getOpcode();
9993   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9994   if (Idx < 0)
9995     return;
9996   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9997     return;
9998   // If the instruction already reads FRM, don't add another read.
9999   if (MI.readsRegister(RISCV::FRM))
10000     return;
10001   MI.addOperand(
10002       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
10003 }
10004 
10005 // Calling Convention Implementation.
10006 // The expectations for frontend ABI lowering vary from target to target.
10007 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
10008 // details, but this is a longer term goal. For now, we simply try to keep the
10009 // role of the frontend as simple and well-defined as possible. The rules can
10010 // be summarised as:
10011 // * Never split up large scalar arguments. We handle them here.
10012 // * If a hardfloat calling convention is being used, and the struct may be
10013 // passed in a pair of registers (fp+fp, int+fp), and both registers are
10014 // available, then pass as two separate arguments. If either the GPRs or FPRs
10015 // are exhausted, then pass according to the rule below.
10016 // * If a struct could never be passed in registers or directly in a stack
10017 // slot (as it is larger than 2*XLEN and the floating point rules don't
10018 // apply), then pass it using a pointer with the byval attribute.
10019 // * If a struct is less than 2*XLEN, then coerce to either a two-element
10020 // word-sized array or a 2*XLEN scalar (depending on alignment).
10021 // * The frontend can determine whether a struct is returned by reference or
10022 // not based on its size and fields. If it will be returned by reference, the
10023 // frontend must modify the prototype so a pointer with the sret annotation is
10024 // passed as the first argument. This is not necessary for large scalar
10025 // returns.
10026 // * Struct return values and varargs should be coerced to structs containing
10027 // register-size fields in the same situations they would be for fixed
10028 // arguments.
10029 
10030 static const MCPhysReg ArgGPRs[] = {
10031   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
10032   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
10033 };
10034 static const MCPhysReg ArgFPR16s[] = {
10035   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
10036   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
10037 };
10038 static const MCPhysReg ArgFPR32s[] = {
10039   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
10040   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
10041 };
10042 static const MCPhysReg ArgFPR64s[] = {
10043   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
10044   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
10045 };
10046 // This is an interim calling convention and it may be changed in the future.
10047 static const MCPhysReg ArgVRs[] = {
10048     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
10049     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
10050     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
10051 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
10052                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
10053                                      RISCV::V20M2, RISCV::V22M2};
10054 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
10055                                      RISCV::V20M4};
10056 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
10057 
10058 // Pass a 2*XLEN argument that has been split into two XLEN values through
10059 // registers or the stack as necessary.
10060 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
10061                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
10062                                 MVT ValVT2, MVT LocVT2,
10063                                 ISD::ArgFlagsTy ArgFlags2) {
10064   unsigned XLenInBytes = XLen / 8;
10065   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10066     // At least one half can be passed via register.
10067     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
10068                                      VA1.getLocVT(), CCValAssign::Full));
10069   } else {
10070     // Both halves must be passed on the stack, with proper alignment.
10071     Align StackAlign =
10072         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
10073     State.addLoc(
10074         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
10075                             State.AllocateStack(XLenInBytes, StackAlign),
10076                             VA1.getLocVT(), CCValAssign::Full));
10077     State.addLoc(CCValAssign::getMem(
10078         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10079         LocVT2, CCValAssign::Full));
10080     return false;
10081   }
10082 
10083   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10084     // The second half can also be passed via register.
10085     State.addLoc(
10086         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
10087   } else {
10088     // The second half is passed via the stack, without additional alignment.
10089     State.addLoc(CCValAssign::getMem(
10090         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10091         LocVT2, CCValAssign::Full));
10092   }
10093 
10094   return false;
10095 }
10096 
10097 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
10098                                Optional<unsigned> FirstMaskArgument,
10099                                CCState &State, const RISCVTargetLowering &TLI) {
10100   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
10101   if (RC == &RISCV::VRRegClass) {
10102     // Assign the first mask argument to V0.
10103     // This is an interim calling convention and it may be changed in the
10104     // future.
10105     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
10106       return State.AllocateReg(RISCV::V0);
10107     return State.AllocateReg(ArgVRs);
10108   }
10109   if (RC == &RISCV::VRM2RegClass)
10110     return State.AllocateReg(ArgVRM2s);
10111   if (RC == &RISCV::VRM4RegClass)
10112     return State.AllocateReg(ArgVRM4s);
10113   if (RC == &RISCV::VRM8RegClass)
10114     return State.AllocateReg(ArgVRM8s);
10115   llvm_unreachable("Unhandled register class for ValueType");
10116 }
10117 
10118 // Implements the RISC-V calling convention. Returns true upon failure.
10119 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
10120                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
10121                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
10122                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
10123                      Optional<unsigned> FirstMaskArgument) {
10124   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
10125   assert(XLen == 32 || XLen == 64);
10126   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
10127 
10128   // Any return value split in to more than two values can't be returned
10129   // directly. Vectors are returned via the available vector registers.
10130   if (!LocVT.isVector() && IsRet && ValNo > 1)
10131     return true;
10132 
10133   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
10134   // variadic argument, or if no F16/F32 argument registers are available.
10135   bool UseGPRForF16_F32 = true;
10136   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
10137   // variadic argument, or if no F64 argument registers are available.
10138   bool UseGPRForF64 = true;
10139 
10140   switch (ABI) {
10141   default:
10142     llvm_unreachable("Unexpected ABI");
10143   case RISCVABI::ABI_ILP32:
10144   case RISCVABI::ABI_LP64:
10145     break;
10146   case RISCVABI::ABI_ILP32F:
10147   case RISCVABI::ABI_LP64F:
10148     UseGPRForF16_F32 = !IsFixed;
10149     break;
10150   case RISCVABI::ABI_ILP32D:
10151   case RISCVABI::ABI_LP64D:
10152     UseGPRForF16_F32 = !IsFixed;
10153     UseGPRForF64 = !IsFixed;
10154     break;
10155   }
10156 
10157   // FPR16, FPR32, and FPR64 alias each other.
10158   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
10159     UseGPRForF16_F32 = true;
10160     UseGPRForF64 = true;
10161   }
10162 
10163   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
10164   // similar local variables rather than directly checking against the target
10165   // ABI.
10166 
10167   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
10168     LocVT = XLenVT;
10169     LocInfo = CCValAssign::BCvt;
10170   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
10171     LocVT = MVT::i64;
10172     LocInfo = CCValAssign::BCvt;
10173   }
10174 
10175   // If this is a variadic argument, the RISC-V calling convention requires
10176   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
10177   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
10178   // be used regardless of whether the original argument was split during
10179   // legalisation or not. The argument will not be passed by registers if the
10180   // original type is larger than 2*XLEN, so the register alignment rule does
10181   // not apply.
10182   unsigned TwoXLenInBytes = (2 * XLen) / 8;
10183   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
10184       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
10185     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10186     // Skip 'odd' register if necessary.
10187     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
10188       State.AllocateReg(ArgGPRs);
10189   }
10190 
10191   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10192   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10193       State.getPendingArgFlags();
10194 
10195   assert(PendingLocs.size() == PendingArgFlags.size() &&
10196          "PendingLocs and PendingArgFlags out of sync");
10197 
10198   // Handle passing f64 on RV32D with a soft float ABI or when floating point
10199   // registers are exhausted.
10200   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
10201     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
10202            "Can't lower f64 if it is split");
10203     // Depending on available argument GPRS, f64 may be passed in a pair of
10204     // GPRs, split between a GPR and the stack, or passed completely on the
10205     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10206     // cases.
10207     Register Reg = State.AllocateReg(ArgGPRs);
10208     LocVT = MVT::i32;
10209     if (!Reg) {
10210       unsigned StackOffset = State.AllocateStack(8, Align(8));
10211       State.addLoc(
10212           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10213       return false;
10214     }
10215     if (!State.AllocateReg(ArgGPRs))
10216       State.AllocateStack(4, Align(4));
10217     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10218     return false;
10219   }
10220 
10221   // Fixed-length vectors are located in the corresponding scalable-vector
10222   // container types.
10223   if (ValVT.isFixedLengthVector())
10224     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10225 
10226   // Split arguments might be passed indirectly, so keep track of the pending
10227   // values. Split vectors are passed via a mix of registers and indirectly, so
10228   // treat them as we would any other argument.
10229   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10230     LocVT = XLenVT;
10231     LocInfo = CCValAssign::Indirect;
10232     PendingLocs.push_back(
10233         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10234     PendingArgFlags.push_back(ArgFlags);
10235     if (!ArgFlags.isSplitEnd()) {
10236       return false;
10237     }
10238   }
10239 
10240   // If the split argument only had two elements, it should be passed directly
10241   // in registers or on the stack.
10242   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10243       PendingLocs.size() <= 2) {
10244     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10245     // Apply the normal calling convention rules to the first half of the
10246     // split argument.
10247     CCValAssign VA = PendingLocs[0];
10248     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10249     PendingLocs.clear();
10250     PendingArgFlags.clear();
10251     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10252                                ArgFlags);
10253   }
10254 
10255   // Allocate to a register if possible, or else a stack slot.
10256   Register Reg;
10257   unsigned StoreSizeBytes = XLen / 8;
10258   Align StackAlign = Align(XLen / 8);
10259 
10260   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10261     Reg = State.AllocateReg(ArgFPR16s);
10262   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10263     Reg = State.AllocateReg(ArgFPR32s);
10264   else if (ValVT == MVT::f64 && !UseGPRForF64)
10265     Reg = State.AllocateReg(ArgFPR64s);
10266   else if (ValVT.isVector()) {
10267     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10268     if (!Reg) {
10269       // For return values, the vector must be passed fully via registers or
10270       // via the stack.
10271       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10272       // but we're using all of them.
10273       if (IsRet)
10274         return true;
10275       // Try using a GPR to pass the address
10276       if ((Reg = State.AllocateReg(ArgGPRs))) {
10277         LocVT = XLenVT;
10278         LocInfo = CCValAssign::Indirect;
10279       } else if (ValVT.isScalableVector()) {
10280         LocVT = XLenVT;
10281         LocInfo = CCValAssign::Indirect;
10282       } else {
10283         // Pass fixed-length vectors on the stack.
10284         LocVT = ValVT;
10285         StoreSizeBytes = ValVT.getStoreSize();
10286         // Align vectors to their element sizes, being careful for vXi1
10287         // vectors.
10288         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10289       }
10290     }
10291   } else {
10292     Reg = State.AllocateReg(ArgGPRs);
10293   }
10294 
10295   unsigned StackOffset =
10296       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10297 
10298   // If we reach this point and PendingLocs is non-empty, we must be at the
10299   // end of a split argument that must be passed indirectly.
10300   if (!PendingLocs.empty()) {
10301     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10302     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10303 
10304     for (auto &It : PendingLocs) {
10305       if (Reg)
10306         It.convertToReg(Reg);
10307       else
10308         It.convertToMem(StackOffset);
10309       State.addLoc(It);
10310     }
10311     PendingLocs.clear();
10312     PendingArgFlags.clear();
10313     return false;
10314   }
10315 
10316   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10317           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10318          "Expected an XLenVT or vector types at this stage");
10319 
10320   if (Reg) {
10321     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10322     return false;
10323   }
10324 
10325   // When a floating-point value is passed on the stack, no bit-conversion is
10326   // needed.
10327   if (ValVT.isFloatingPoint()) {
10328     LocVT = ValVT;
10329     LocInfo = CCValAssign::Full;
10330   }
10331   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10332   return false;
10333 }
10334 
10335 template <typename ArgTy>
10336 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10337   for (const auto &ArgIdx : enumerate(Args)) {
10338     MVT ArgVT = ArgIdx.value().VT;
10339     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10340       return ArgIdx.index();
10341   }
10342   return None;
10343 }
10344 
10345 void RISCVTargetLowering::analyzeInputArgs(
10346     MachineFunction &MF, CCState &CCInfo,
10347     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10348     RISCVCCAssignFn Fn) const {
10349   unsigned NumArgs = Ins.size();
10350   FunctionType *FType = MF.getFunction().getFunctionType();
10351 
10352   Optional<unsigned> FirstMaskArgument;
10353   if (Subtarget.hasVInstructions())
10354     FirstMaskArgument = preAssignMask(Ins);
10355 
10356   for (unsigned i = 0; i != NumArgs; ++i) {
10357     MVT ArgVT = Ins[i].VT;
10358     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10359 
10360     Type *ArgTy = nullptr;
10361     if (IsRet)
10362       ArgTy = FType->getReturnType();
10363     else if (Ins[i].isOrigArg())
10364       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10365 
10366     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10367     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10368            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10369            FirstMaskArgument)) {
10370       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10371                         << EVT(ArgVT).getEVTString() << '\n');
10372       llvm_unreachable(nullptr);
10373     }
10374   }
10375 }
10376 
10377 void RISCVTargetLowering::analyzeOutputArgs(
10378     MachineFunction &MF, CCState &CCInfo,
10379     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10380     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10381   unsigned NumArgs = Outs.size();
10382 
10383   Optional<unsigned> FirstMaskArgument;
10384   if (Subtarget.hasVInstructions())
10385     FirstMaskArgument = preAssignMask(Outs);
10386 
10387   for (unsigned i = 0; i != NumArgs; i++) {
10388     MVT ArgVT = Outs[i].VT;
10389     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10390     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10391 
10392     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10393     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10394            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10395            FirstMaskArgument)) {
10396       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10397                         << EVT(ArgVT).getEVTString() << "\n");
10398       llvm_unreachable(nullptr);
10399     }
10400   }
10401 }
10402 
10403 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10404 // values.
10405 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10406                                    const CCValAssign &VA, const SDLoc &DL,
10407                                    const RISCVSubtarget &Subtarget) {
10408   switch (VA.getLocInfo()) {
10409   default:
10410     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10411   case CCValAssign::Full:
10412     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10413       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10414     break;
10415   case CCValAssign::BCvt:
10416     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10417       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10418     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10419       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10420     else
10421       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10422     break;
10423   }
10424   return Val;
10425 }
10426 
10427 // The caller is responsible for loading the full value if the argument is
10428 // passed with CCValAssign::Indirect.
10429 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10430                                 const CCValAssign &VA, const SDLoc &DL,
10431                                 const RISCVTargetLowering &TLI) {
10432   MachineFunction &MF = DAG.getMachineFunction();
10433   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10434   EVT LocVT = VA.getLocVT();
10435   SDValue Val;
10436   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10437   Register VReg = RegInfo.createVirtualRegister(RC);
10438   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10439   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10440 
10441   if (VA.getLocInfo() == CCValAssign::Indirect)
10442     return Val;
10443 
10444   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10445 }
10446 
10447 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10448                                    const CCValAssign &VA, const SDLoc &DL,
10449                                    const RISCVSubtarget &Subtarget) {
10450   EVT LocVT = VA.getLocVT();
10451 
10452   switch (VA.getLocInfo()) {
10453   default:
10454     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10455   case CCValAssign::Full:
10456     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10457       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10458     break;
10459   case CCValAssign::BCvt:
10460     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10461       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10462     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10463       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10464     else
10465       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10466     break;
10467   }
10468   return Val;
10469 }
10470 
10471 // The caller is responsible for loading the full value if the argument is
10472 // passed with CCValAssign::Indirect.
10473 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10474                                 const CCValAssign &VA, const SDLoc &DL) {
10475   MachineFunction &MF = DAG.getMachineFunction();
10476   MachineFrameInfo &MFI = MF.getFrameInfo();
10477   EVT LocVT = VA.getLocVT();
10478   EVT ValVT = VA.getValVT();
10479   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10480   if (ValVT.isScalableVector()) {
10481     // When the value is a scalable vector, we save the pointer which points to
10482     // the scalable vector value in the stack. The ValVT will be the pointer
10483     // type, instead of the scalable vector type.
10484     ValVT = LocVT;
10485   }
10486   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10487                                  /*IsImmutable=*/true);
10488   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10489   SDValue Val;
10490 
10491   ISD::LoadExtType ExtType;
10492   switch (VA.getLocInfo()) {
10493   default:
10494     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10495   case CCValAssign::Full:
10496   case CCValAssign::Indirect:
10497   case CCValAssign::BCvt:
10498     ExtType = ISD::NON_EXTLOAD;
10499     break;
10500   }
10501   Val = DAG.getExtLoad(
10502       ExtType, DL, LocVT, Chain, FIN,
10503       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10504   return Val;
10505 }
10506 
10507 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10508                                        const CCValAssign &VA, const SDLoc &DL) {
10509   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10510          "Unexpected VA");
10511   MachineFunction &MF = DAG.getMachineFunction();
10512   MachineFrameInfo &MFI = MF.getFrameInfo();
10513   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10514 
10515   if (VA.isMemLoc()) {
10516     // f64 is passed on the stack.
10517     int FI =
10518         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10519     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10520     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10521                        MachinePointerInfo::getFixedStack(MF, FI));
10522   }
10523 
10524   assert(VA.isRegLoc() && "Expected register VA assignment");
10525 
10526   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10527   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10528   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10529   SDValue Hi;
10530   if (VA.getLocReg() == RISCV::X17) {
10531     // Second half of f64 is passed on the stack.
10532     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10533     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10534     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10535                      MachinePointerInfo::getFixedStack(MF, FI));
10536   } else {
10537     // Second half of f64 is passed in another GPR.
10538     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10539     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10540     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10541   }
10542   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10543 }
10544 
10545 // FastCC has less than 1% performance improvement for some particular
10546 // benchmark. But theoretically, it may has benenfit for some cases.
10547 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10548                             unsigned ValNo, MVT ValVT, MVT LocVT,
10549                             CCValAssign::LocInfo LocInfo,
10550                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10551                             bool IsFixed, bool IsRet, Type *OrigTy,
10552                             const RISCVTargetLowering &TLI,
10553                             Optional<unsigned> FirstMaskArgument) {
10554 
10555   // X5 and X6 might be used for save-restore libcall.
10556   static const MCPhysReg GPRList[] = {
10557       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10558       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10559       RISCV::X29, RISCV::X30, RISCV::X31};
10560 
10561   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10562     if (unsigned Reg = State.AllocateReg(GPRList)) {
10563       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10564       return false;
10565     }
10566   }
10567 
10568   if (LocVT == MVT::f16) {
10569     static const MCPhysReg FPR16List[] = {
10570         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10571         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10572         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10573         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10574     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10575       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10576       return false;
10577     }
10578   }
10579 
10580   if (LocVT == MVT::f32) {
10581     static const MCPhysReg FPR32List[] = {
10582         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10583         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10584         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10585         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10586     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10587       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10588       return false;
10589     }
10590   }
10591 
10592   if (LocVT == MVT::f64) {
10593     static const MCPhysReg FPR64List[] = {
10594         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10595         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10596         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10597         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10598     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10599       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10600       return false;
10601     }
10602   }
10603 
10604   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10605     unsigned Offset4 = State.AllocateStack(4, Align(4));
10606     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10607     return false;
10608   }
10609 
10610   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10611     unsigned Offset5 = State.AllocateStack(8, Align(8));
10612     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10613     return false;
10614   }
10615 
10616   if (LocVT.isVector()) {
10617     if (unsigned Reg =
10618             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10619       // Fixed-length vectors are located in the corresponding scalable-vector
10620       // container types.
10621       if (ValVT.isFixedLengthVector())
10622         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10623       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10624     } else {
10625       // Try and pass the address via a "fast" GPR.
10626       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10627         LocInfo = CCValAssign::Indirect;
10628         LocVT = TLI.getSubtarget().getXLenVT();
10629         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10630       } else if (ValVT.isFixedLengthVector()) {
10631         auto StackAlign =
10632             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10633         unsigned StackOffset =
10634             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10635         State.addLoc(
10636             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10637       } else {
10638         // Can't pass scalable vectors on the stack.
10639         return true;
10640       }
10641     }
10642 
10643     return false;
10644   }
10645 
10646   return true; // CC didn't match.
10647 }
10648 
10649 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10650                          CCValAssign::LocInfo LocInfo,
10651                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10652 
10653   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10654     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10655     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10656     static const MCPhysReg GPRList[] = {
10657         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10658         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10659     if (unsigned Reg = State.AllocateReg(GPRList)) {
10660       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10661       return false;
10662     }
10663   }
10664 
10665   if (LocVT == MVT::f32) {
10666     // Pass in STG registers: F1, ..., F6
10667     //                        fs0 ... fs5
10668     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10669                                           RISCV::F18_F, RISCV::F19_F,
10670                                           RISCV::F20_F, RISCV::F21_F};
10671     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10672       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10673       return false;
10674     }
10675   }
10676 
10677   if (LocVT == MVT::f64) {
10678     // Pass in STG registers: D1, ..., D6
10679     //                        fs6 ... fs11
10680     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10681                                           RISCV::F24_D, RISCV::F25_D,
10682                                           RISCV::F26_D, RISCV::F27_D};
10683     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10684       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10685       return false;
10686     }
10687   }
10688 
10689   report_fatal_error("No registers left in GHC calling convention");
10690   return true;
10691 }
10692 
10693 // Transform physical registers into virtual registers.
10694 SDValue RISCVTargetLowering::LowerFormalArguments(
10695     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10696     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10697     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10698 
10699   MachineFunction &MF = DAG.getMachineFunction();
10700 
10701   switch (CallConv) {
10702   default:
10703     report_fatal_error("Unsupported calling convention");
10704   case CallingConv::C:
10705   case CallingConv::Fast:
10706     break;
10707   case CallingConv::GHC:
10708     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10709         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10710       report_fatal_error(
10711         "GHC calling convention requires the F and D instruction set extensions");
10712   }
10713 
10714   const Function &Func = MF.getFunction();
10715   if (Func.hasFnAttribute("interrupt")) {
10716     if (!Func.arg_empty())
10717       report_fatal_error(
10718         "Functions with the interrupt attribute cannot have arguments!");
10719 
10720     StringRef Kind =
10721       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10722 
10723     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10724       report_fatal_error(
10725         "Function interrupt attribute argument not supported!");
10726   }
10727 
10728   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10729   MVT XLenVT = Subtarget.getXLenVT();
10730   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10731   // Used with vargs to acumulate store chains.
10732   std::vector<SDValue> OutChains;
10733 
10734   // Assign locations to all of the incoming arguments.
10735   SmallVector<CCValAssign, 16> ArgLocs;
10736   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10737 
10738   if (CallConv == CallingConv::GHC)
10739     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10740   else
10741     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10742                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10743                                                    : CC_RISCV);
10744 
10745   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10746     CCValAssign &VA = ArgLocs[i];
10747     SDValue ArgValue;
10748     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10749     // case.
10750     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10751       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10752     else if (VA.isRegLoc())
10753       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10754     else
10755       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10756 
10757     if (VA.getLocInfo() == CCValAssign::Indirect) {
10758       // If the original argument was split and passed by reference (e.g. i128
10759       // on RV32), we need to load all parts of it here (using the same
10760       // address). Vectors may be partly split to registers and partly to the
10761       // stack, in which case the base address is partly offset and subsequent
10762       // stores are relative to that.
10763       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10764                                    MachinePointerInfo()));
10765       unsigned ArgIndex = Ins[i].OrigArgIndex;
10766       unsigned ArgPartOffset = Ins[i].PartOffset;
10767       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10768       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10769         CCValAssign &PartVA = ArgLocs[i + 1];
10770         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10771         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10772         if (PartVA.getValVT().isScalableVector())
10773           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10774         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10775         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10776                                      MachinePointerInfo()));
10777         ++i;
10778       }
10779       continue;
10780     }
10781     InVals.push_back(ArgValue);
10782   }
10783 
10784   if (IsVarArg) {
10785     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10786     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10787     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10788     MachineFrameInfo &MFI = MF.getFrameInfo();
10789     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10790     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10791 
10792     // Offset of the first variable argument from stack pointer, and size of
10793     // the vararg save area. For now, the varargs save area is either zero or
10794     // large enough to hold a0-a7.
10795     int VaArgOffset, VarArgsSaveSize;
10796 
10797     // If all registers are allocated, then all varargs must be passed on the
10798     // stack and we don't need to save any argregs.
10799     if (ArgRegs.size() == Idx) {
10800       VaArgOffset = CCInfo.getNextStackOffset();
10801       VarArgsSaveSize = 0;
10802     } else {
10803       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10804       VaArgOffset = -VarArgsSaveSize;
10805     }
10806 
10807     // Record the frame index of the first variable argument
10808     // which is a value necessary to VASTART.
10809     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10810     RVFI->setVarArgsFrameIndex(FI);
10811 
10812     // If saving an odd number of registers then create an extra stack slot to
10813     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10814     // offsets to even-numbered registered remain 2*XLEN-aligned.
10815     if (Idx % 2) {
10816       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10817       VarArgsSaveSize += XLenInBytes;
10818     }
10819 
10820     // Copy the integer registers that may have been used for passing varargs
10821     // to the vararg save area.
10822     for (unsigned I = Idx; I < ArgRegs.size();
10823          ++I, VaArgOffset += XLenInBytes) {
10824       const Register Reg = RegInfo.createVirtualRegister(RC);
10825       RegInfo.addLiveIn(ArgRegs[I], Reg);
10826       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10827       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10828       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10829       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10830                                    MachinePointerInfo::getFixedStack(MF, FI));
10831       cast<StoreSDNode>(Store.getNode())
10832           ->getMemOperand()
10833           ->setValue((Value *)nullptr);
10834       OutChains.push_back(Store);
10835     }
10836     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10837   }
10838 
10839   // All stores are grouped in one node to allow the matching between
10840   // the size of Ins and InVals. This only happens for vararg functions.
10841   if (!OutChains.empty()) {
10842     OutChains.push_back(Chain);
10843     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10844   }
10845 
10846   return Chain;
10847 }
10848 
10849 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10850 /// for tail call optimization.
10851 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10852 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10853     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10854     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10855 
10856   auto &Callee = CLI.Callee;
10857   auto CalleeCC = CLI.CallConv;
10858   auto &Outs = CLI.Outs;
10859   auto &Caller = MF.getFunction();
10860   auto CallerCC = Caller.getCallingConv();
10861 
10862   // Exception-handling functions need a special set of instructions to
10863   // indicate a return to the hardware. Tail-calling another function would
10864   // probably break this.
10865   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10866   // should be expanded as new function attributes are introduced.
10867   if (Caller.hasFnAttribute("interrupt"))
10868     return false;
10869 
10870   // Do not tail call opt if the stack is used to pass parameters.
10871   if (CCInfo.getNextStackOffset() != 0)
10872     return false;
10873 
10874   // Do not tail call opt if any parameters need to be passed indirectly.
10875   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10876   // passed indirectly. So the address of the value will be passed in a
10877   // register, or if not available, then the address is put on the stack. In
10878   // order to pass indirectly, space on the stack often needs to be allocated
10879   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10880   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10881   // are passed CCValAssign::Indirect.
10882   for (auto &VA : ArgLocs)
10883     if (VA.getLocInfo() == CCValAssign::Indirect)
10884       return false;
10885 
10886   // Do not tail call opt if either caller or callee uses struct return
10887   // semantics.
10888   auto IsCallerStructRet = Caller.hasStructRetAttr();
10889   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10890   if (IsCallerStructRet || IsCalleeStructRet)
10891     return false;
10892 
10893   // Externally-defined functions with weak linkage should not be
10894   // tail-called. The behaviour of branch instructions in this situation (as
10895   // used for tail calls) is implementation-defined, so we cannot rely on the
10896   // linker replacing the tail call with a return.
10897   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10898     const GlobalValue *GV = G->getGlobal();
10899     if (GV->hasExternalWeakLinkage())
10900       return false;
10901   }
10902 
10903   // The callee has to preserve all registers the caller needs to preserve.
10904   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10905   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10906   if (CalleeCC != CallerCC) {
10907     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10908     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10909       return false;
10910   }
10911 
10912   // Byval parameters hand the function a pointer directly into the stack area
10913   // we want to reuse during a tail call. Working around this *is* possible
10914   // but less efficient and uglier in LowerCall.
10915   for (auto &Arg : Outs)
10916     if (Arg.Flags.isByVal())
10917       return false;
10918 
10919   return true;
10920 }
10921 
10922 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10923   return DAG.getDataLayout().getPrefTypeAlign(
10924       VT.getTypeForEVT(*DAG.getContext()));
10925 }
10926 
10927 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10928 // and output parameter nodes.
10929 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10930                                        SmallVectorImpl<SDValue> &InVals) const {
10931   SelectionDAG &DAG = CLI.DAG;
10932   SDLoc &DL = CLI.DL;
10933   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10934   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10935   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10936   SDValue Chain = CLI.Chain;
10937   SDValue Callee = CLI.Callee;
10938   bool &IsTailCall = CLI.IsTailCall;
10939   CallingConv::ID CallConv = CLI.CallConv;
10940   bool IsVarArg = CLI.IsVarArg;
10941   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10942   MVT XLenVT = Subtarget.getXLenVT();
10943 
10944   MachineFunction &MF = DAG.getMachineFunction();
10945 
10946   // Analyze the operands of the call, assigning locations to each operand.
10947   SmallVector<CCValAssign, 16> ArgLocs;
10948   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10949 
10950   if (CallConv == CallingConv::GHC)
10951     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10952   else
10953     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10954                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10955                                                     : CC_RISCV);
10956 
10957   // Check if it's really possible to do a tail call.
10958   if (IsTailCall)
10959     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10960 
10961   if (IsTailCall)
10962     ++NumTailCalls;
10963   else if (CLI.CB && CLI.CB->isMustTailCall())
10964     report_fatal_error("failed to perform tail call elimination on a call "
10965                        "site marked musttail");
10966 
10967   // Get a count of how many bytes are to be pushed on the stack.
10968   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10969 
10970   // Create local copies for byval args
10971   SmallVector<SDValue, 8> ByValArgs;
10972   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10973     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10974     if (!Flags.isByVal())
10975       continue;
10976 
10977     SDValue Arg = OutVals[i];
10978     unsigned Size = Flags.getByValSize();
10979     Align Alignment = Flags.getNonZeroByValAlign();
10980 
10981     int FI =
10982         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10983     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10984     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10985 
10986     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10987                           /*IsVolatile=*/false,
10988                           /*AlwaysInline=*/false, IsTailCall,
10989                           MachinePointerInfo(), MachinePointerInfo());
10990     ByValArgs.push_back(FIPtr);
10991   }
10992 
10993   if (!IsTailCall)
10994     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10995 
10996   // Copy argument values to their designated locations.
10997   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10998   SmallVector<SDValue, 8> MemOpChains;
10999   SDValue StackPtr;
11000   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
11001     CCValAssign &VA = ArgLocs[i];
11002     SDValue ArgValue = OutVals[i];
11003     ISD::ArgFlagsTy Flags = Outs[i].Flags;
11004 
11005     // Handle passing f64 on RV32D with a soft float ABI as a special case.
11006     bool IsF64OnRV32DSoftABI =
11007         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
11008     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
11009       SDValue SplitF64 = DAG.getNode(
11010           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
11011       SDValue Lo = SplitF64.getValue(0);
11012       SDValue Hi = SplitF64.getValue(1);
11013 
11014       Register RegLo = VA.getLocReg();
11015       RegsToPass.push_back(std::make_pair(RegLo, Lo));
11016 
11017       if (RegLo == RISCV::X17) {
11018         // Second half of f64 is passed on the stack.
11019         // Work out the address of the stack slot.
11020         if (!StackPtr.getNode())
11021           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11022         // Emit the store.
11023         MemOpChains.push_back(
11024             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
11025       } else {
11026         // Second half of f64 is passed in another GPR.
11027         assert(RegLo < RISCV::X31 && "Invalid register pair");
11028         Register RegHigh = RegLo + 1;
11029         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
11030       }
11031       continue;
11032     }
11033 
11034     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
11035     // as any other MemLoc.
11036 
11037     // Promote the value if needed.
11038     // For now, only handle fully promoted and indirect arguments.
11039     if (VA.getLocInfo() == CCValAssign::Indirect) {
11040       // Store the argument in a stack slot and pass its address.
11041       Align StackAlign =
11042           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
11043                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
11044       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
11045       // If the original argument was split (e.g. i128), we need
11046       // to store the required parts of it here (and pass just one address).
11047       // Vectors may be partly split to registers and partly to the stack, in
11048       // which case the base address is partly offset and subsequent stores are
11049       // relative to that.
11050       unsigned ArgIndex = Outs[i].OrigArgIndex;
11051       unsigned ArgPartOffset = Outs[i].PartOffset;
11052       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
11053       // Calculate the total size to store. We don't have access to what we're
11054       // actually storing other than performing the loop and collecting the
11055       // info.
11056       SmallVector<std::pair<SDValue, SDValue>> Parts;
11057       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
11058         SDValue PartValue = OutVals[i + 1];
11059         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
11060         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11061         EVT PartVT = PartValue.getValueType();
11062         if (PartVT.isScalableVector())
11063           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
11064         StoredSize += PartVT.getStoreSize();
11065         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
11066         Parts.push_back(std::make_pair(PartValue, Offset));
11067         ++i;
11068       }
11069       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
11070       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
11071       MemOpChains.push_back(
11072           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
11073                        MachinePointerInfo::getFixedStack(MF, FI)));
11074       for (const auto &Part : Parts) {
11075         SDValue PartValue = Part.first;
11076         SDValue PartOffset = Part.second;
11077         SDValue Address =
11078             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
11079         MemOpChains.push_back(
11080             DAG.getStore(Chain, DL, PartValue, Address,
11081                          MachinePointerInfo::getFixedStack(MF, FI)));
11082       }
11083       ArgValue = SpillSlot;
11084     } else {
11085       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
11086     }
11087 
11088     // Use local copy if it is a byval arg.
11089     if (Flags.isByVal())
11090       ArgValue = ByValArgs[j++];
11091 
11092     if (VA.isRegLoc()) {
11093       // Queue up the argument copies and emit them at the end.
11094       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
11095     } else {
11096       assert(VA.isMemLoc() && "Argument not register or memory");
11097       assert(!IsTailCall && "Tail call not allowed if stack is used "
11098                             "for passing parameters");
11099 
11100       // Work out the address of the stack slot.
11101       if (!StackPtr.getNode())
11102         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11103       SDValue Address =
11104           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11105                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
11106 
11107       // Emit the store.
11108       MemOpChains.push_back(
11109           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
11110     }
11111   }
11112 
11113   // Join the stores, which are independent of one another.
11114   if (!MemOpChains.empty())
11115     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
11116 
11117   SDValue Glue;
11118 
11119   // Build a sequence of copy-to-reg nodes, chained and glued together.
11120   for (auto &Reg : RegsToPass) {
11121     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11122     Glue = Chain.getValue(1);
11123   }
11124 
11125   // Validate that none of the argument registers have been marked as
11126   // reserved, if so report an error. Do the same for the return address if this
11127   // is not a tailcall.
11128   validateCCReservedRegs(RegsToPass, MF);
11129   if (!IsTailCall &&
11130       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
11131     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11132         MF.getFunction(),
11133         "Return address register required, but has been reserved."});
11134 
11135   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11136   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11137   // split it and then direct call can be matched by PseudoCALL.
11138   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
11139     const GlobalValue *GV = S->getGlobal();
11140 
11141     unsigned OpFlags = RISCVII::MO_CALL;
11142     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
11143       OpFlags = RISCVII::MO_PLT;
11144 
11145     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
11146   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11147     unsigned OpFlags = RISCVII::MO_CALL;
11148 
11149     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
11150                                                  nullptr))
11151       OpFlags = RISCVII::MO_PLT;
11152 
11153     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11154   }
11155 
11156   // The first call operand is the chain and the second is the target address.
11157   SmallVector<SDValue, 8> Ops;
11158   Ops.push_back(Chain);
11159   Ops.push_back(Callee);
11160 
11161   // Add argument registers to the end of the list so that they are
11162   // known live into the call.
11163   for (auto &Reg : RegsToPass)
11164     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11165 
11166   if (!IsTailCall) {
11167     // Add a register mask operand representing the call-preserved registers.
11168     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11169     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11170     assert(Mask && "Missing call preserved mask for calling convention");
11171     Ops.push_back(DAG.getRegisterMask(Mask));
11172   }
11173 
11174   // Glue the call to the argument copies, if any.
11175   if (Glue.getNode())
11176     Ops.push_back(Glue);
11177 
11178   // Emit the call.
11179   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11180 
11181   if (IsTailCall) {
11182     MF.getFrameInfo().setHasTailCall();
11183     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
11184   }
11185 
11186   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
11187   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11188   Glue = Chain.getValue(1);
11189 
11190   // Mark the end of the call, which is glued to the call itself.
11191   Chain = DAG.getCALLSEQ_END(Chain,
11192                              DAG.getConstant(NumBytes, DL, PtrVT, true),
11193                              DAG.getConstant(0, DL, PtrVT, true),
11194                              Glue, DL);
11195   Glue = Chain.getValue(1);
11196 
11197   // Assign locations to each value returned by this call.
11198   SmallVector<CCValAssign, 16> RVLocs;
11199   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11200   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
11201 
11202   // Copy all of the result registers out of their specified physreg.
11203   for (auto &VA : RVLocs) {
11204     // Copy the value out
11205     SDValue RetValue =
11206         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11207     // Glue the RetValue to the end of the call sequence
11208     Chain = RetValue.getValue(1);
11209     Glue = RetValue.getValue(2);
11210 
11211     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11212       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11213       SDValue RetValue2 =
11214           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11215       Chain = RetValue2.getValue(1);
11216       Glue = RetValue2.getValue(2);
11217       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11218                              RetValue2);
11219     }
11220 
11221     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11222 
11223     InVals.push_back(RetValue);
11224   }
11225 
11226   return Chain;
11227 }
11228 
11229 bool RISCVTargetLowering::CanLowerReturn(
11230     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11231     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11232   SmallVector<CCValAssign, 16> RVLocs;
11233   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11234 
11235   Optional<unsigned> FirstMaskArgument;
11236   if (Subtarget.hasVInstructions())
11237     FirstMaskArgument = preAssignMask(Outs);
11238 
11239   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11240     MVT VT = Outs[i].VT;
11241     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11242     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11243     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11244                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11245                  *this, FirstMaskArgument))
11246       return false;
11247   }
11248   return true;
11249 }
11250 
11251 SDValue
11252 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11253                                  bool IsVarArg,
11254                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11255                                  const SmallVectorImpl<SDValue> &OutVals,
11256                                  const SDLoc &DL, SelectionDAG &DAG) const {
11257   const MachineFunction &MF = DAG.getMachineFunction();
11258   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11259 
11260   // Stores the assignment of the return value to a location.
11261   SmallVector<CCValAssign, 16> RVLocs;
11262 
11263   // Info about the registers and stack slot.
11264   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11265                  *DAG.getContext());
11266 
11267   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11268                     nullptr, CC_RISCV);
11269 
11270   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11271     report_fatal_error("GHC functions return void only");
11272 
11273   SDValue Glue;
11274   SmallVector<SDValue, 4> RetOps(1, Chain);
11275 
11276   // Copy the result values into the output registers.
11277   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11278     SDValue Val = OutVals[i];
11279     CCValAssign &VA = RVLocs[i];
11280     assert(VA.isRegLoc() && "Can only return in registers!");
11281 
11282     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11283       // Handle returning f64 on RV32D with a soft float ABI.
11284       assert(VA.isRegLoc() && "Expected return via registers");
11285       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11286                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11287       SDValue Lo = SplitF64.getValue(0);
11288       SDValue Hi = SplitF64.getValue(1);
11289       Register RegLo = VA.getLocReg();
11290       assert(RegLo < RISCV::X31 && "Invalid register pair");
11291       Register RegHi = RegLo + 1;
11292 
11293       if (STI.isRegisterReservedByUser(RegLo) ||
11294           STI.isRegisterReservedByUser(RegHi))
11295         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11296             MF.getFunction(),
11297             "Return value register required, but has been reserved."});
11298 
11299       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11300       Glue = Chain.getValue(1);
11301       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11302       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11303       Glue = Chain.getValue(1);
11304       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11305     } else {
11306       // Handle a 'normal' return.
11307       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11308       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11309 
11310       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11311         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11312             MF.getFunction(),
11313             "Return value register required, but has been reserved."});
11314 
11315       // Guarantee that all emitted copies are stuck together.
11316       Glue = Chain.getValue(1);
11317       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11318     }
11319   }
11320 
11321   RetOps[0] = Chain; // Update chain.
11322 
11323   // Add the glue node if we have it.
11324   if (Glue.getNode()) {
11325     RetOps.push_back(Glue);
11326   }
11327 
11328   unsigned RetOpc = RISCVISD::RET_FLAG;
11329   // Interrupt service routines use different return instructions.
11330   const Function &Func = DAG.getMachineFunction().getFunction();
11331   if (Func.hasFnAttribute("interrupt")) {
11332     if (!Func.getReturnType()->isVoidTy())
11333       report_fatal_error(
11334           "Functions with the interrupt attribute must have void return type!");
11335 
11336     MachineFunction &MF = DAG.getMachineFunction();
11337     StringRef Kind =
11338       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11339 
11340     if (Kind == "user")
11341       RetOpc = RISCVISD::URET_FLAG;
11342     else if (Kind == "supervisor")
11343       RetOpc = RISCVISD::SRET_FLAG;
11344     else
11345       RetOpc = RISCVISD::MRET_FLAG;
11346   }
11347 
11348   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11349 }
11350 
11351 void RISCVTargetLowering::validateCCReservedRegs(
11352     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11353     MachineFunction &MF) const {
11354   const Function &F = MF.getFunction();
11355   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11356 
11357   if (llvm::any_of(Regs, [&STI](auto Reg) {
11358         return STI.isRegisterReservedByUser(Reg.first);
11359       }))
11360     F.getContext().diagnose(DiagnosticInfoUnsupported{
11361         F, "Argument register required, but has been reserved."});
11362 }
11363 
11364 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11365   return CI->isTailCall();
11366 }
11367 
11368 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11369 #define NODE_NAME_CASE(NODE)                                                   \
11370   case RISCVISD::NODE:                                                         \
11371     return "RISCVISD::" #NODE;
11372   // clang-format off
11373   switch ((RISCVISD::NodeType)Opcode) {
11374   case RISCVISD::FIRST_NUMBER:
11375     break;
11376   NODE_NAME_CASE(RET_FLAG)
11377   NODE_NAME_CASE(URET_FLAG)
11378   NODE_NAME_CASE(SRET_FLAG)
11379   NODE_NAME_CASE(MRET_FLAG)
11380   NODE_NAME_CASE(CALL)
11381   NODE_NAME_CASE(SELECT_CC)
11382   NODE_NAME_CASE(BR_CC)
11383   NODE_NAME_CASE(BuildPairF64)
11384   NODE_NAME_CASE(SplitF64)
11385   NODE_NAME_CASE(TAIL)
11386   NODE_NAME_CASE(ADD_LO)
11387   NODE_NAME_CASE(HI)
11388   NODE_NAME_CASE(LLA)
11389   NODE_NAME_CASE(ADD_TPREL)
11390   NODE_NAME_CASE(LA)
11391   NODE_NAME_CASE(LA_TLS_IE)
11392   NODE_NAME_CASE(LA_TLS_GD)
11393   NODE_NAME_CASE(MULHSU)
11394   NODE_NAME_CASE(SLLW)
11395   NODE_NAME_CASE(SRAW)
11396   NODE_NAME_CASE(SRLW)
11397   NODE_NAME_CASE(DIVW)
11398   NODE_NAME_CASE(DIVUW)
11399   NODE_NAME_CASE(REMUW)
11400   NODE_NAME_CASE(ROLW)
11401   NODE_NAME_CASE(RORW)
11402   NODE_NAME_CASE(CLZW)
11403   NODE_NAME_CASE(CTZW)
11404   NODE_NAME_CASE(FSLW)
11405   NODE_NAME_CASE(FSRW)
11406   NODE_NAME_CASE(FSL)
11407   NODE_NAME_CASE(FSR)
11408   NODE_NAME_CASE(FMV_H_X)
11409   NODE_NAME_CASE(FMV_X_ANYEXTH)
11410   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11411   NODE_NAME_CASE(FMV_W_X_RV64)
11412   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11413   NODE_NAME_CASE(FCVT_X)
11414   NODE_NAME_CASE(FCVT_XU)
11415   NODE_NAME_CASE(FCVT_W_RV64)
11416   NODE_NAME_CASE(FCVT_WU_RV64)
11417   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11418   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11419   NODE_NAME_CASE(READ_CYCLE_WIDE)
11420   NODE_NAME_CASE(GREV)
11421   NODE_NAME_CASE(GREVW)
11422   NODE_NAME_CASE(GORC)
11423   NODE_NAME_CASE(GORCW)
11424   NODE_NAME_CASE(SHFL)
11425   NODE_NAME_CASE(SHFLW)
11426   NODE_NAME_CASE(UNSHFL)
11427   NODE_NAME_CASE(UNSHFLW)
11428   NODE_NAME_CASE(BFP)
11429   NODE_NAME_CASE(BFPW)
11430   NODE_NAME_CASE(BCOMPRESS)
11431   NODE_NAME_CASE(BCOMPRESSW)
11432   NODE_NAME_CASE(BDECOMPRESS)
11433   NODE_NAME_CASE(BDECOMPRESSW)
11434   NODE_NAME_CASE(VMV_V_X_VL)
11435   NODE_NAME_CASE(VFMV_V_F_VL)
11436   NODE_NAME_CASE(VMV_X_S)
11437   NODE_NAME_CASE(VMV_S_X_VL)
11438   NODE_NAME_CASE(VFMV_S_F_VL)
11439   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11440   NODE_NAME_CASE(READ_VLENB)
11441   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11442   NODE_NAME_CASE(VSLIDEUP_VL)
11443   NODE_NAME_CASE(VSLIDE1UP_VL)
11444   NODE_NAME_CASE(VSLIDEDOWN_VL)
11445   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11446   NODE_NAME_CASE(VID_VL)
11447   NODE_NAME_CASE(VFNCVT_ROD_VL)
11448   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11449   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11450   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11451   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11452   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11453   NODE_NAME_CASE(VECREDUCE_AND_VL)
11454   NODE_NAME_CASE(VECREDUCE_OR_VL)
11455   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11456   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11457   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11458   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11459   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11460   NODE_NAME_CASE(ADD_VL)
11461   NODE_NAME_CASE(AND_VL)
11462   NODE_NAME_CASE(MUL_VL)
11463   NODE_NAME_CASE(OR_VL)
11464   NODE_NAME_CASE(SDIV_VL)
11465   NODE_NAME_CASE(SHL_VL)
11466   NODE_NAME_CASE(SREM_VL)
11467   NODE_NAME_CASE(SRA_VL)
11468   NODE_NAME_CASE(SRL_VL)
11469   NODE_NAME_CASE(SUB_VL)
11470   NODE_NAME_CASE(UDIV_VL)
11471   NODE_NAME_CASE(UREM_VL)
11472   NODE_NAME_CASE(XOR_VL)
11473   NODE_NAME_CASE(SADDSAT_VL)
11474   NODE_NAME_CASE(UADDSAT_VL)
11475   NODE_NAME_CASE(SSUBSAT_VL)
11476   NODE_NAME_CASE(USUBSAT_VL)
11477   NODE_NAME_CASE(FADD_VL)
11478   NODE_NAME_CASE(FSUB_VL)
11479   NODE_NAME_CASE(FMUL_VL)
11480   NODE_NAME_CASE(FDIV_VL)
11481   NODE_NAME_CASE(FNEG_VL)
11482   NODE_NAME_CASE(FABS_VL)
11483   NODE_NAME_CASE(FSQRT_VL)
11484   NODE_NAME_CASE(VFMADD_VL)
11485   NODE_NAME_CASE(VFNMADD_VL)
11486   NODE_NAME_CASE(VFMSUB_VL)
11487   NODE_NAME_CASE(VFNMSUB_VL)
11488   NODE_NAME_CASE(FCOPYSIGN_VL)
11489   NODE_NAME_CASE(SMIN_VL)
11490   NODE_NAME_CASE(SMAX_VL)
11491   NODE_NAME_CASE(UMIN_VL)
11492   NODE_NAME_CASE(UMAX_VL)
11493   NODE_NAME_CASE(FMINNUM_VL)
11494   NODE_NAME_CASE(FMAXNUM_VL)
11495   NODE_NAME_CASE(MULHS_VL)
11496   NODE_NAME_CASE(MULHU_VL)
11497   NODE_NAME_CASE(FP_TO_SINT_VL)
11498   NODE_NAME_CASE(FP_TO_UINT_VL)
11499   NODE_NAME_CASE(SINT_TO_FP_VL)
11500   NODE_NAME_CASE(UINT_TO_FP_VL)
11501   NODE_NAME_CASE(FP_EXTEND_VL)
11502   NODE_NAME_CASE(FP_ROUND_VL)
11503   NODE_NAME_CASE(VWMUL_VL)
11504   NODE_NAME_CASE(VWMULU_VL)
11505   NODE_NAME_CASE(VWMULSU_VL)
11506   NODE_NAME_CASE(VWADD_VL)
11507   NODE_NAME_CASE(VWADDU_VL)
11508   NODE_NAME_CASE(VWSUB_VL)
11509   NODE_NAME_CASE(VWSUBU_VL)
11510   NODE_NAME_CASE(VWADD_W_VL)
11511   NODE_NAME_CASE(VWADDU_W_VL)
11512   NODE_NAME_CASE(VWSUB_W_VL)
11513   NODE_NAME_CASE(VWSUBU_W_VL)
11514   NODE_NAME_CASE(SETCC_VL)
11515   NODE_NAME_CASE(VSELECT_VL)
11516   NODE_NAME_CASE(VP_MERGE_VL)
11517   NODE_NAME_CASE(VMAND_VL)
11518   NODE_NAME_CASE(VMOR_VL)
11519   NODE_NAME_CASE(VMXOR_VL)
11520   NODE_NAME_CASE(VMCLR_VL)
11521   NODE_NAME_CASE(VMSET_VL)
11522   NODE_NAME_CASE(VRGATHER_VX_VL)
11523   NODE_NAME_CASE(VRGATHER_VV_VL)
11524   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11525   NODE_NAME_CASE(VSEXT_VL)
11526   NODE_NAME_CASE(VZEXT_VL)
11527   NODE_NAME_CASE(VCPOP_VL)
11528   NODE_NAME_CASE(READ_CSR)
11529   NODE_NAME_CASE(WRITE_CSR)
11530   NODE_NAME_CASE(SWAP_CSR)
11531   }
11532   // clang-format on
11533   return nullptr;
11534 #undef NODE_NAME_CASE
11535 }
11536 
11537 /// getConstraintType - Given a constraint letter, return the type of
11538 /// constraint it is for this target.
11539 RISCVTargetLowering::ConstraintType
11540 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11541   if (Constraint.size() == 1) {
11542     switch (Constraint[0]) {
11543     default:
11544       break;
11545     case 'f':
11546       return C_RegisterClass;
11547     case 'I':
11548     case 'J':
11549     case 'K':
11550       return C_Immediate;
11551     case 'A':
11552       return C_Memory;
11553     case 'S': // A symbolic address
11554       return C_Other;
11555     }
11556   } else {
11557     if (Constraint == "vr" || Constraint == "vm")
11558       return C_RegisterClass;
11559   }
11560   return TargetLowering::getConstraintType(Constraint);
11561 }
11562 
11563 std::pair<unsigned, const TargetRegisterClass *>
11564 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11565                                                   StringRef Constraint,
11566                                                   MVT VT) const {
11567   // First, see if this is a constraint that directly corresponds to a
11568   // RISCV register class.
11569   if (Constraint.size() == 1) {
11570     switch (Constraint[0]) {
11571     case 'r':
11572       // TODO: Support fixed vectors up to XLen for P extension?
11573       if (VT.isVector())
11574         break;
11575       return std::make_pair(0U, &RISCV::GPRRegClass);
11576     case 'f':
11577       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11578         return std::make_pair(0U, &RISCV::FPR16RegClass);
11579       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11580         return std::make_pair(0U, &RISCV::FPR32RegClass);
11581       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11582         return std::make_pair(0U, &RISCV::FPR64RegClass);
11583       break;
11584     default:
11585       break;
11586     }
11587   } else if (Constraint == "vr") {
11588     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11589                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11590       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11591         return std::make_pair(0U, RC);
11592     }
11593   } else if (Constraint == "vm") {
11594     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11595       return std::make_pair(0U, &RISCV::VMV0RegClass);
11596   }
11597 
11598   // Clang will correctly decode the usage of register name aliases into their
11599   // official names. However, other frontends like `rustc` do not. This allows
11600   // users of these frontends to use the ABI names for registers in LLVM-style
11601   // register constraints.
11602   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11603                                .Case("{zero}", RISCV::X0)
11604                                .Case("{ra}", RISCV::X1)
11605                                .Case("{sp}", RISCV::X2)
11606                                .Case("{gp}", RISCV::X3)
11607                                .Case("{tp}", RISCV::X4)
11608                                .Case("{t0}", RISCV::X5)
11609                                .Case("{t1}", RISCV::X6)
11610                                .Case("{t2}", RISCV::X7)
11611                                .Cases("{s0}", "{fp}", RISCV::X8)
11612                                .Case("{s1}", RISCV::X9)
11613                                .Case("{a0}", RISCV::X10)
11614                                .Case("{a1}", RISCV::X11)
11615                                .Case("{a2}", RISCV::X12)
11616                                .Case("{a3}", RISCV::X13)
11617                                .Case("{a4}", RISCV::X14)
11618                                .Case("{a5}", RISCV::X15)
11619                                .Case("{a6}", RISCV::X16)
11620                                .Case("{a7}", RISCV::X17)
11621                                .Case("{s2}", RISCV::X18)
11622                                .Case("{s3}", RISCV::X19)
11623                                .Case("{s4}", RISCV::X20)
11624                                .Case("{s5}", RISCV::X21)
11625                                .Case("{s6}", RISCV::X22)
11626                                .Case("{s7}", RISCV::X23)
11627                                .Case("{s8}", RISCV::X24)
11628                                .Case("{s9}", RISCV::X25)
11629                                .Case("{s10}", RISCV::X26)
11630                                .Case("{s11}", RISCV::X27)
11631                                .Case("{t3}", RISCV::X28)
11632                                .Case("{t4}", RISCV::X29)
11633                                .Case("{t5}", RISCV::X30)
11634                                .Case("{t6}", RISCV::X31)
11635                                .Default(RISCV::NoRegister);
11636   if (XRegFromAlias != RISCV::NoRegister)
11637     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11638 
11639   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11640   // TableGen record rather than the AsmName to choose registers for InlineAsm
11641   // constraints, plus we want to match those names to the widest floating point
11642   // register type available, manually select floating point registers here.
11643   //
11644   // The second case is the ABI name of the register, so that frontends can also
11645   // use the ABI names in register constraint lists.
11646   if (Subtarget.hasStdExtF()) {
11647     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11648                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11649                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11650                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11651                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11652                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11653                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11654                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11655                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11656                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11657                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11658                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11659                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11660                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11661                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11662                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11663                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11664                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11665                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11666                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11667                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11668                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11669                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11670                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11671                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11672                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11673                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11674                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11675                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11676                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11677                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11678                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11679                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11680                         .Default(RISCV::NoRegister);
11681     if (FReg != RISCV::NoRegister) {
11682       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11683       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11684         unsigned RegNo = FReg - RISCV::F0_F;
11685         unsigned DReg = RISCV::F0_D + RegNo;
11686         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11687       }
11688       if (VT == MVT::f32 || VT == MVT::Other)
11689         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11690       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11691         unsigned RegNo = FReg - RISCV::F0_F;
11692         unsigned HReg = RISCV::F0_H + RegNo;
11693         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11694       }
11695     }
11696   }
11697 
11698   if (Subtarget.hasVInstructions()) {
11699     Register VReg = StringSwitch<Register>(Constraint.lower())
11700                         .Case("{v0}", RISCV::V0)
11701                         .Case("{v1}", RISCV::V1)
11702                         .Case("{v2}", RISCV::V2)
11703                         .Case("{v3}", RISCV::V3)
11704                         .Case("{v4}", RISCV::V4)
11705                         .Case("{v5}", RISCV::V5)
11706                         .Case("{v6}", RISCV::V6)
11707                         .Case("{v7}", RISCV::V7)
11708                         .Case("{v8}", RISCV::V8)
11709                         .Case("{v9}", RISCV::V9)
11710                         .Case("{v10}", RISCV::V10)
11711                         .Case("{v11}", RISCV::V11)
11712                         .Case("{v12}", RISCV::V12)
11713                         .Case("{v13}", RISCV::V13)
11714                         .Case("{v14}", RISCV::V14)
11715                         .Case("{v15}", RISCV::V15)
11716                         .Case("{v16}", RISCV::V16)
11717                         .Case("{v17}", RISCV::V17)
11718                         .Case("{v18}", RISCV::V18)
11719                         .Case("{v19}", RISCV::V19)
11720                         .Case("{v20}", RISCV::V20)
11721                         .Case("{v21}", RISCV::V21)
11722                         .Case("{v22}", RISCV::V22)
11723                         .Case("{v23}", RISCV::V23)
11724                         .Case("{v24}", RISCV::V24)
11725                         .Case("{v25}", RISCV::V25)
11726                         .Case("{v26}", RISCV::V26)
11727                         .Case("{v27}", RISCV::V27)
11728                         .Case("{v28}", RISCV::V28)
11729                         .Case("{v29}", RISCV::V29)
11730                         .Case("{v30}", RISCV::V30)
11731                         .Case("{v31}", RISCV::V31)
11732                         .Default(RISCV::NoRegister);
11733     if (VReg != RISCV::NoRegister) {
11734       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11735         return std::make_pair(VReg, &RISCV::VMRegClass);
11736       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11737         return std::make_pair(VReg, &RISCV::VRRegClass);
11738       for (const auto *RC :
11739            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11740         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11741           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11742           return std::make_pair(VReg, RC);
11743         }
11744       }
11745     }
11746   }
11747 
11748   std::pair<Register, const TargetRegisterClass *> Res =
11749       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11750 
11751   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11752   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11753   // Subtarget into account.
11754   if (Res.second == &RISCV::GPRF16RegClass ||
11755       Res.second == &RISCV::GPRF32RegClass ||
11756       Res.second == &RISCV::GPRF64RegClass)
11757     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11758 
11759   return Res;
11760 }
11761 
11762 unsigned
11763 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11764   // Currently only support length 1 constraints.
11765   if (ConstraintCode.size() == 1) {
11766     switch (ConstraintCode[0]) {
11767     case 'A':
11768       return InlineAsm::Constraint_A;
11769     default:
11770       break;
11771     }
11772   }
11773 
11774   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11775 }
11776 
11777 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11778     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11779     SelectionDAG &DAG) const {
11780   // Currently only support length 1 constraints.
11781   if (Constraint.length() == 1) {
11782     switch (Constraint[0]) {
11783     case 'I':
11784       // Validate & create a 12-bit signed immediate operand.
11785       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11786         uint64_t CVal = C->getSExtValue();
11787         if (isInt<12>(CVal))
11788           Ops.push_back(
11789               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11790       }
11791       return;
11792     case 'J':
11793       // Validate & create an integer zero operand.
11794       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11795         if (C->getZExtValue() == 0)
11796           Ops.push_back(
11797               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11798       return;
11799     case 'K':
11800       // Validate & create a 5-bit unsigned immediate operand.
11801       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11802         uint64_t CVal = C->getZExtValue();
11803         if (isUInt<5>(CVal))
11804           Ops.push_back(
11805               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11806       }
11807       return;
11808     case 'S':
11809       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11810         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11811                                                  GA->getValueType(0)));
11812       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11813         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11814                                                 BA->getValueType(0)));
11815       }
11816       return;
11817     default:
11818       break;
11819     }
11820   }
11821   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11822 }
11823 
11824 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11825                                                    Instruction *Inst,
11826                                                    AtomicOrdering Ord) const {
11827   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11828     return Builder.CreateFence(Ord);
11829   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11830     return Builder.CreateFence(AtomicOrdering::Release);
11831   return nullptr;
11832 }
11833 
11834 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11835                                                     Instruction *Inst,
11836                                                     AtomicOrdering Ord) const {
11837   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11838     return Builder.CreateFence(AtomicOrdering::Acquire);
11839   return nullptr;
11840 }
11841 
11842 TargetLowering::AtomicExpansionKind
11843 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11844   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11845   // point operations can't be used in an lr/sc sequence without breaking the
11846   // forward-progress guarantee.
11847   if (AI->isFloatingPointOperation())
11848     return AtomicExpansionKind::CmpXChg;
11849 
11850   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11851   if (Size == 8 || Size == 16)
11852     return AtomicExpansionKind::MaskedIntrinsic;
11853   return AtomicExpansionKind::None;
11854 }
11855 
11856 static Intrinsic::ID
11857 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11858   if (XLen == 32) {
11859     switch (BinOp) {
11860     default:
11861       llvm_unreachable("Unexpected AtomicRMW BinOp");
11862     case AtomicRMWInst::Xchg:
11863       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11864     case AtomicRMWInst::Add:
11865       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11866     case AtomicRMWInst::Sub:
11867       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11868     case AtomicRMWInst::Nand:
11869       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11870     case AtomicRMWInst::Max:
11871       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11872     case AtomicRMWInst::Min:
11873       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11874     case AtomicRMWInst::UMax:
11875       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11876     case AtomicRMWInst::UMin:
11877       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11878     }
11879   }
11880 
11881   if (XLen == 64) {
11882     switch (BinOp) {
11883     default:
11884       llvm_unreachable("Unexpected AtomicRMW BinOp");
11885     case AtomicRMWInst::Xchg:
11886       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11887     case AtomicRMWInst::Add:
11888       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11889     case AtomicRMWInst::Sub:
11890       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11891     case AtomicRMWInst::Nand:
11892       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11893     case AtomicRMWInst::Max:
11894       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11895     case AtomicRMWInst::Min:
11896       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11897     case AtomicRMWInst::UMax:
11898       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11899     case AtomicRMWInst::UMin:
11900       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11901     }
11902   }
11903 
11904   llvm_unreachable("Unexpected XLen\n");
11905 }
11906 
11907 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11908     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11909     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11910   unsigned XLen = Subtarget.getXLen();
11911   Value *Ordering =
11912       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11913   Type *Tys[] = {AlignedAddr->getType()};
11914   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11915       AI->getModule(),
11916       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11917 
11918   if (XLen == 64) {
11919     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11920     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11921     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11922   }
11923 
11924   Value *Result;
11925 
11926   // Must pass the shift amount needed to sign extend the loaded value prior
11927   // to performing a signed comparison for min/max. ShiftAmt is the number of
11928   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11929   // is the number of bits to left+right shift the value in order to
11930   // sign-extend.
11931   if (AI->getOperation() == AtomicRMWInst::Min ||
11932       AI->getOperation() == AtomicRMWInst::Max) {
11933     const DataLayout &DL = AI->getModule()->getDataLayout();
11934     unsigned ValWidth =
11935         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11936     Value *SextShamt =
11937         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11938     Result = Builder.CreateCall(LrwOpScwLoop,
11939                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11940   } else {
11941     Result =
11942         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11943   }
11944 
11945   if (XLen == 64)
11946     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11947   return Result;
11948 }
11949 
11950 TargetLowering::AtomicExpansionKind
11951 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11952     AtomicCmpXchgInst *CI) const {
11953   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11954   if (Size == 8 || Size == 16)
11955     return AtomicExpansionKind::MaskedIntrinsic;
11956   return AtomicExpansionKind::None;
11957 }
11958 
11959 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11960     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11961     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11962   unsigned XLen = Subtarget.getXLen();
11963   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11964   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11965   if (XLen == 64) {
11966     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11967     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11968     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11969     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11970   }
11971   Type *Tys[] = {AlignedAddr->getType()};
11972   Function *MaskedCmpXchg =
11973       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11974   Value *Result = Builder.CreateCall(
11975       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11976   if (XLen == 64)
11977     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11978   return Result;
11979 }
11980 
11981 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
11982                                                         EVT DataVT) const {
11983   return false;
11984 }
11985 
11986 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11987                                                EVT VT) const {
11988   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11989     return false;
11990 
11991   switch (FPVT.getSimpleVT().SimpleTy) {
11992   case MVT::f16:
11993     return Subtarget.hasStdExtZfh();
11994   case MVT::f32:
11995     return Subtarget.hasStdExtF();
11996   case MVT::f64:
11997     return Subtarget.hasStdExtD();
11998   default:
11999     return false;
12000   }
12001 }
12002 
12003 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
12004   // If we are using the small code model, we can reduce size of jump table
12005   // entry to 4 bytes.
12006   if (Subtarget.is64Bit() && !isPositionIndependent() &&
12007       getTargetMachine().getCodeModel() == CodeModel::Small) {
12008     return MachineJumpTableInfo::EK_Custom32;
12009   }
12010   return TargetLowering::getJumpTableEncoding();
12011 }
12012 
12013 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
12014     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
12015     unsigned uid, MCContext &Ctx) const {
12016   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
12017          getTargetMachine().getCodeModel() == CodeModel::Small);
12018   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
12019 }
12020 
12021 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
12022                                                      EVT VT) const {
12023   VT = VT.getScalarType();
12024 
12025   if (!VT.isSimple())
12026     return false;
12027 
12028   switch (VT.getSimpleVT().SimpleTy) {
12029   case MVT::f16:
12030     return Subtarget.hasStdExtZfh();
12031   case MVT::f32:
12032     return Subtarget.hasStdExtF();
12033   case MVT::f64:
12034     return Subtarget.hasStdExtD();
12035   default:
12036     break;
12037   }
12038 
12039   return false;
12040 }
12041 
12042 Register RISCVTargetLowering::getExceptionPointerRegister(
12043     const Constant *PersonalityFn) const {
12044   return RISCV::X10;
12045 }
12046 
12047 Register RISCVTargetLowering::getExceptionSelectorRegister(
12048     const Constant *PersonalityFn) const {
12049   return RISCV::X11;
12050 }
12051 
12052 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
12053   // Return false to suppress the unnecessary extensions if the LibCall
12054   // arguments or return value is f32 type for LP64 ABI.
12055   RISCVABI::ABI ABI = Subtarget.getTargetABI();
12056   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
12057     return false;
12058 
12059   return true;
12060 }
12061 
12062 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
12063   if (Subtarget.is64Bit() && Type == MVT::i32)
12064     return true;
12065 
12066   return IsSigned;
12067 }
12068 
12069 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
12070                                                  SDValue C) const {
12071   // Check integral scalar types.
12072   if (VT.isScalarInteger()) {
12073     // Omit the optimization if the sub target has the M extension and the data
12074     // size exceeds XLen.
12075     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
12076       return false;
12077     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
12078       // Break the MUL to a SLLI and an ADD/SUB.
12079       const APInt &Imm = ConstNode->getAPIntValue();
12080       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
12081           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
12082         return true;
12083       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
12084       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
12085           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
12086            (Imm - 8).isPowerOf2()))
12087         return true;
12088       // Omit the following optimization if the sub target has the M extension
12089       // and the data size >= XLen.
12090       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
12091         return false;
12092       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
12093       // a pair of LUI/ADDI.
12094       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
12095         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
12096         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
12097             (1 - ImmS).isPowerOf2())
12098           return true;
12099       }
12100     }
12101   }
12102 
12103   return false;
12104 }
12105 
12106 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
12107                                                       SDValue ConstNode) const {
12108   // Let the DAGCombiner decide for vectors.
12109   EVT VT = AddNode.getValueType();
12110   if (VT.isVector())
12111     return true;
12112 
12113   // Let the DAGCombiner decide for larger types.
12114   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
12115     return true;
12116 
12117   // It is worse if c1 is simm12 while c1*c2 is not.
12118   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12119   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12120   const APInt &C1 = C1Node->getAPIntValue();
12121   const APInt &C2 = C2Node->getAPIntValue();
12122   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
12123     return false;
12124 
12125   // Default to true and let the DAGCombiner decide.
12126   return true;
12127 }
12128 
12129 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
12130     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
12131     bool *Fast) const {
12132   if (!VT.isVector()) {
12133     if (Fast)
12134       *Fast = false;
12135     return Subtarget.enableUnalignedScalarMem();
12136   }
12137 
12138   // All vector implementations must support element alignment
12139   EVT ElemVT = VT.getVectorElementType();
12140   if (Alignment >= ElemVT.getStoreSize()) {
12141     if (Fast)
12142       *Fast = true;
12143     return true;
12144   }
12145 
12146   return false;
12147 }
12148 
12149 bool RISCVTargetLowering::splitValueIntoRegisterParts(
12150     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12151     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
12152   bool IsABIRegCopy = CC.has_value();
12153   EVT ValueVT = Val.getValueType();
12154   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12155     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
12156     // and cast to f32.
12157     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12158     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12159     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12160                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12161     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12162     Parts[0] = Val;
12163     return true;
12164   }
12165 
12166   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12167     LLVMContext &Context = *DAG.getContext();
12168     EVT ValueEltVT = ValueVT.getVectorElementType();
12169     EVT PartEltVT = PartVT.getVectorElementType();
12170     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12171     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12172     if (PartVTBitSize % ValueVTBitSize == 0) {
12173       assert(PartVTBitSize >= ValueVTBitSize);
12174       // If the element types are different, bitcast to the same element type of
12175       // PartVT first.
12176       // Give an example here, we want copy a <vscale x 1 x i8> value to
12177       // <vscale x 4 x i16>.
12178       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
12179       // subvector, then we can bitcast to <vscale x 4 x i16>.
12180       if (ValueEltVT != PartEltVT) {
12181         if (PartVTBitSize > ValueVTBitSize) {
12182           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12183           assert(Count != 0 && "The number of element should not be zero.");
12184           EVT SameEltTypeVT =
12185               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12186           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
12187                             DAG.getUNDEF(SameEltTypeVT), Val,
12188                             DAG.getVectorIdxConstant(0, DL));
12189         }
12190         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
12191       } else {
12192         Val =
12193             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
12194                         Val, DAG.getVectorIdxConstant(0, DL));
12195       }
12196       Parts[0] = Val;
12197       return true;
12198     }
12199   }
12200   return false;
12201 }
12202 
12203 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
12204     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12205     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
12206   bool IsABIRegCopy = CC.has_value();
12207   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12208     SDValue Val = Parts[0];
12209 
12210     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12211     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12212     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12213     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12214     return Val;
12215   }
12216 
12217   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12218     LLVMContext &Context = *DAG.getContext();
12219     SDValue Val = Parts[0];
12220     EVT ValueEltVT = ValueVT.getVectorElementType();
12221     EVT PartEltVT = PartVT.getVectorElementType();
12222     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12223     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12224     if (PartVTBitSize % ValueVTBitSize == 0) {
12225       assert(PartVTBitSize >= ValueVTBitSize);
12226       EVT SameEltTypeVT = ValueVT;
12227       // If the element types are different, convert it to the same element type
12228       // of PartVT.
12229       // Give an example here, we want copy a <vscale x 1 x i8> value from
12230       // <vscale x 4 x i16>.
12231       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12232       // then we can extract <vscale x 1 x i8>.
12233       if (ValueEltVT != PartEltVT) {
12234         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12235         assert(Count != 0 && "The number of element should not be zero.");
12236         SameEltTypeVT =
12237             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12238         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12239       }
12240       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12241                         DAG.getVectorIdxConstant(0, DL));
12242       return Val;
12243     }
12244   }
12245   return SDValue();
12246 }
12247 
12248 SDValue
12249 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12250                                    SelectionDAG &DAG,
12251                                    SmallVectorImpl<SDNode *> &Created) const {
12252   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12253   if (isIntDivCheap(N->getValueType(0), Attr))
12254     return SDValue(N, 0); // Lower SDIV as SDIV
12255 
12256   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12257          "Unexpected divisor!");
12258 
12259   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12260   if (!Subtarget.hasStdExtZbt())
12261     return SDValue();
12262 
12263   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12264   // Besides, more critical path instructions will be generated when dividing
12265   // by 2. So we keep using the original DAGs for these cases.
12266   unsigned Lg2 = Divisor.countTrailingZeros();
12267   if (Lg2 == 1 || Lg2 >= 12)
12268     return SDValue();
12269 
12270   // fold (sdiv X, pow2)
12271   EVT VT = N->getValueType(0);
12272   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12273     return SDValue();
12274 
12275   SDLoc DL(N);
12276   SDValue N0 = N->getOperand(0);
12277   SDValue Zero = DAG.getConstant(0, DL, VT);
12278   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12279 
12280   // Add (N0 < 0) ? Pow2 - 1 : 0;
12281   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12282   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12283   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12284 
12285   Created.push_back(Cmp.getNode());
12286   Created.push_back(Add.getNode());
12287   Created.push_back(Sel.getNode());
12288 
12289   // Divide by pow2.
12290   SDValue SRA =
12291       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12292 
12293   // If we're dividing by a positive value, we're done.  Otherwise, we must
12294   // negate the result.
12295   if (Divisor.isNonNegative())
12296     return SRA;
12297 
12298   Created.push_back(SRA.getNode());
12299   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12300 }
12301 
12302 #define GET_REGISTER_MATCHER
12303 #include "RISCVGenAsmMatcher.inc"
12304 
12305 Register
12306 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12307                                        const MachineFunction &MF) const {
12308   Register Reg = MatchRegisterAltName(RegName);
12309   if (Reg == RISCV::NoRegister)
12310     Reg = MatchRegisterName(RegName);
12311   if (Reg == RISCV::NoRegister)
12312     report_fatal_error(
12313         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12314   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12315   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12316     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12317                              StringRef(RegName) + "\"."));
12318   return Reg;
12319 }
12320 
12321 namespace llvm {
12322 namespace RISCVVIntrinsicsTable {
12323 
12324 #define GET_RISCVVIntrinsicsTable_IMPL
12325 #include "RISCVGenSearchableTables.inc"
12326 
12327 } // namespace RISCVVIntrinsicsTable
12328 
12329 } // namespace llvm
12330