1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       const TargetRegisterClass *RC;
117       if (Size <= RISCV::RVVBitsPerBlock)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 2 * RISCV::RVVBitsPerBlock)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 4 * RISCV::RVVBitsPerBlock)
122         RC = &RISCV::VRM4RegClass;
123       else if (Size == 8 * RISCV::RVVBitsPerBlock)
124         RC = &RISCV::VRM8RegClass;
125       else
126         llvm_unreachable("Unexpected size");
127 
128       addRegisterClass(VT, RC);
129     };
130 
131     for (MVT VT : BoolVecVTs)
132       addRegClassForRVV(VT);
133     for (MVT VT : IntVecVTs) {
134       if (VT.getVectorElementType() == MVT::i64 &&
135           !Subtarget.hasVInstructionsI64())
136         continue;
137       addRegClassForRVV(VT);
138     }
139 
140     if (Subtarget.hasVInstructionsF16())
141       for (MVT VT : F16VecVTs)
142         addRegClassForRVV(VT);
143 
144     if (Subtarget.hasVInstructionsF32())
145       for (MVT VT : F32VecVTs)
146         addRegClassForRVV(VT);
147 
148     if (Subtarget.hasVInstructionsF64())
149       for (MVT VT : F64VecVTs)
150         addRegClassForRVV(VT);
151 
152     if (Subtarget.useRVVForFixedLengthVectors()) {
153       auto addRegClassForFixedVectors = [this](MVT VT) {
154         MVT ContainerVT = getContainerForFixedLengthVector(VT);
155         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
156         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
157         addRegisterClass(VT, TRI.getRegClass(RCID));
158       };
159       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
160         if (useRVVForFixedLengthVectorVT(VT))
161           addRegClassForFixedVectors(VT);
162 
163       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
164         if (useRVVForFixedLengthVectorVT(VT))
165           addRegClassForFixedVectors(VT);
166     }
167   }
168 
169   // Compute derived properties from the register classes.
170   computeRegisterProperties(STI.getRegisterInfo());
171 
172   setStackPointerRegisterToSaveRestore(RISCV::X2);
173 
174   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
175                    MVT::i1, Promote);
176 
177   // TODO: add all necessary setOperationAction calls.
178   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
179 
180   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
181   setOperationAction(ISD::BR_CC, XLenVT, Expand);
182   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
183   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
184 
185   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
189 
190   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
191 
192   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
193 
194   if (!Subtarget.hasStdExtZbb())
195     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
196 
197   if (Subtarget.is64Bit()) {
198     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
199 
200     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
201                        MVT::i32, Custom);
202 
203     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
204                        MVT::i32, Custom);
205   } else {
206     setLibcallName(
207         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
208         nullptr);
209     setLibcallName(RTLIB::MULO_I64, nullptr);
210   }
211 
212   if (!Subtarget.hasStdExtM()) {
213     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
214                         ISD::SREM, ISD::UREM},
215                        XLenVT, Expand);
216   } else {
217     if (Subtarget.is64Bit()) {
218       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
219 
220       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
221                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
222     } else {
223       setOperationAction(ISD::MUL, MVT::i64, Custom);
224     }
225   }
226 
227   setOperationAction(
228       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
229       Expand);
230 
231   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
232                      Custom);
233 
234   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
235       Subtarget.hasStdExtZbkb()) {
236     if (Subtarget.is64Bit())
237       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
238   } else {
239     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
240   }
241 
242   if (Subtarget.hasStdExtZbp()) {
243     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
244     // more combining.
245     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
246 
247     // BSWAP i8 doesn't exist.
248     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
249 
250     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
251 
252     if (Subtarget.is64Bit())
253       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
254   } else {
255     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
256     // pattern match it directly in isel.
257     setOperationAction(ISD::BSWAP, XLenVT,
258                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
259                            ? Legal
260                            : Expand);
261     // Zbkb can use rev8+brev8 to implement bitreverse.
262     setOperationAction(ISD::BITREVERSE, XLenVT,
263                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
264   }
265 
266   if (Subtarget.hasStdExtZbb()) {
267     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
268                        Legal);
269 
270     if (Subtarget.is64Bit())
271       setOperationAction(
272           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
273           MVT::i32, Custom);
274   } else {
275     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
276 
277     if (Subtarget.is64Bit())
278       setOperationAction(ISD::ABS, MVT::i32, Custom);
279   }
280 
281   if (Subtarget.hasStdExtZbt()) {
282     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
283     setOperationAction(ISD::SELECT, XLenVT, Legal);
284 
285     if (Subtarget.is64Bit())
286       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
287   } else {
288     setOperationAction(ISD::SELECT, XLenVT, Custom);
289   }
290 
291   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
292       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
293       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
294       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
295       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
296       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
297       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
298 
299   static const ISD::CondCode FPCCToExpand[] = {
300       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
301       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
302       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
303 
304   static const ISD::NodeType FPOpToExpand[] = {
305       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
306       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
307 
308   if (Subtarget.hasStdExtZfh())
309     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
310 
311   if (Subtarget.hasStdExtZfh()) {
312     for (auto NT : FPLegalNodeTypes)
313       setOperationAction(NT, MVT::f16, Legal);
314     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
315     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
316     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
317     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
318     setOperationAction(ISD::SELECT, MVT::f16, Custom);
319     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
320 
321     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
322                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
323                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
324                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
325                         ISD::FLOG2, ISD::FLOG10},
326                        MVT::f16, Promote);
327 
328     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
329     // complete support for all operations in LegalizeDAG.
330 
331     // We need to custom promote this.
332     if (Subtarget.is64Bit())
333       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
334   }
335 
336   if (Subtarget.hasStdExtF()) {
337     for (auto NT : FPLegalNodeTypes)
338       setOperationAction(NT, MVT::f32, Legal);
339     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
340     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
341     setOperationAction(ISD::SELECT, MVT::f32, Custom);
342     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
343     for (auto Op : FPOpToExpand)
344       setOperationAction(Op, MVT::f32, Expand);
345     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
346     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
347   }
348 
349   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
350     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
351 
352   if (Subtarget.hasStdExtD()) {
353     for (auto NT : FPLegalNodeTypes)
354       setOperationAction(NT, MVT::f64, Legal);
355     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
357     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
358     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
359     setOperationAction(ISD::SELECT, MVT::f64, Custom);
360     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
361     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
362     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
363     for (auto Op : FPOpToExpand)
364       setOperationAction(Op, MVT::f64, Expand);
365     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
366     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
367   }
368 
369   if (Subtarget.is64Bit())
370     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
371                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
372                        MVT::i32, Custom);
373 
374   if (Subtarget.hasStdExtF()) {
375     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
376                        Custom);
377 
378     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
379                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
380                        XLenVT, Legal);
381 
382     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
383     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
384   }
385 
386   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
387                       ISD::JumpTable},
388                      XLenVT, Custom);
389 
390   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
391 
392   if (Subtarget.is64Bit())
393     setOperationAction(ISD::Constant, MVT::i64, Custom);
394 
395   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
396   // Unfortunately this can't be determined just from the ISA naming string.
397   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
398                      Subtarget.is64Bit() ? Legal : Custom);
399 
400   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
401   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
402   if (Subtarget.is64Bit())
403     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
404 
405   if (Subtarget.hasStdExtA()) {
406     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
407     setMinCmpXchgSizeInBits(32);
408   } else {
409     setMaxAtomicSizeInBitsSupported(0);
410   }
411 
412   setBooleanContents(ZeroOrOneBooleanContent);
413 
414   if (Subtarget.hasVInstructions()) {
415     setBooleanVectorContents(ZeroOrOneBooleanContent);
416 
417     setOperationAction(ISD::VSCALE, XLenVT, Custom);
418 
419     // RVV intrinsics may have illegal operands.
420     // We also need to custom legalize vmv.x.s.
421     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
422                        {MVT::i8, MVT::i16}, Custom);
423     if (Subtarget.is64Bit())
424       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
425     else
426       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
427                          MVT::i64, Custom);
428 
429     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
430                        MVT::Other, Custom);
431 
432     static const unsigned IntegerVPOps[] = {
433         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
434         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
435         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
436         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
437         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
438         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
439         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
440         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
441         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
442         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
443 
444     static const unsigned FloatingPointVPOps[] = {
445         ISD::VP_FADD,        ISD::VP_FSUB,
446         ISD::VP_FMUL,        ISD::VP_FDIV,
447         ISD::VP_FNEG,        ISD::VP_FMA,
448         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
449         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
450         ISD::VP_MERGE,       ISD::VP_SELECT,
451         ISD::VP_SITOFP,      ISD::VP_UITOFP,
452         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
453         ISD::VP_FP_EXTEND};
454 
455     if (!Subtarget.is64Bit()) {
456       // We must custom-lower certain vXi64 operations on RV32 due to the vector
457       // element type being illegal.
458       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
459                          MVT::i64, Custom);
460 
461       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
462                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
463                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
464                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
465                          MVT::i64, Custom);
466 
467       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
468                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
469                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
470                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
471                          MVT::i64, Custom);
472     }
473 
474     for (MVT VT : BoolVecVTs) {
475       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
476 
477       // Mask VTs are custom-expanded into a series of standard nodes
478       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
479                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
480                          VT, Custom);
481 
482       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
483                          Custom);
484 
485       setOperationAction(ISD::SELECT, VT, Custom);
486       setOperationAction(
487           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
488           Expand);
489 
490       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
491 
492       setOperationAction(
493           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
494           Custom);
495 
496       setOperationAction(
497           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
498           Custom);
499 
500       // RVV has native int->float & float->int conversions where the
501       // element type sizes are within one power-of-two of each other. Any
502       // wider distances between type sizes have to be lowered as sequences
503       // which progressively narrow the gap in stages.
504       setOperationAction(
505           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
506           VT, Custom);
507 
508       // Expand all extending loads to types larger than this, and truncating
509       // stores from types larger than this.
510       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
511         setTruncStoreAction(OtherVT, VT, Expand);
512         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
513                          VT, Expand);
514       }
515 
516       setOperationAction(
517           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
518           Custom);
519     }
520 
521     for (MVT VT : IntVecVTs) {
522       if (VT.getVectorElementType() == MVT::i64 &&
523           !Subtarget.hasVInstructionsI64())
524         continue;
525 
526       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
527       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
528 
529       // Vectors implement MULHS/MULHU.
530       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
531 
532       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
533       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
534         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
535 
536       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
537                          Legal);
538 
539       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
540 
541       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
542                          Expand);
543 
544       setOperationAction(ISD::BSWAP, VT, Expand);
545 
546       // Custom-lower extensions and truncations from/to mask types.
547       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
548                          VT, Custom);
549 
550       // RVV has native int->float & float->int conversions where the
551       // element type sizes are within one power-of-two of each other. Any
552       // wider distances between type sizes have to be lowered as sequences
553       // which progressively narrow the gap in stages.
554       setOperationAction(
555           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
556           VT, Custom);
557 
558       setOperationAction(
559           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
560 
561       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
562       // nodes which truncate by one power of two at a time.
563       setOperationAction(ISD::TRUNCATE, VT, Custom);
564 
565       // Custom-lower insert/extract operations to simplify patterns.
566       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
567                          Custom);
568 
569       // Custom-lower reduction operations to set up the corresponding custom
570       // nodes' operands.
571       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
572                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
573                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
574                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
575                          VT, Custom);
576 
577       setOperationAction(IntegerVPOps, VT, Custom);
578 
579       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
580 
581       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
582                          VT, Custom);
583 
584       setOperationAction(
585           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
586           Custom);
587 
588       setOperationAction(
589           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
590           VT, Custom);
591 
592       setOperationAction(ISD::SELECT, VT, Custom);
593       setOperationAction(ISD::SELECT_CC, VT, Expand);
594 
595       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
596 
597       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
598         setTruncStoreAction(VT, OtherVT, Expand);
599         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
600                          VT, Expand);
601       }
602 
603       // Splice
604       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
605 
606       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
607       // type that can represent the value exactly.
608       if (VT.getVectorElementType() != MVT::i64) {
609         MVT FloatEltVT =
610             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
611         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
612         if (isTypeLegal(FloatVT)) {
613           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
614                              Custom);
615         }
616       }
617     }
618 
619     // Expand various CCs to best match the RVV ISA, which natively supports UNE
620     // but no other unordered comparisons, and supports all ordered comparisons
621     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
622     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
623     // and we pattern-match those back to the "original", swapping operands once
624     // more. This way we catch both operations and both "vf" and "fv" forms with
625     // fewer patterns.
626     static const ISD::CondCode VFPCCToExpand[] = {
627         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
628         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
629         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
630     };
631 
632     // Sets common operation actions on RVV floating-point vector types.
633     const auto SetCommonVFPActions = [&](MVT VT) {
634       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
635       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
636       // sizes are within one power-of-two of each other. Therefore conversions
637       // between vXf16 and vXf64 must be lowered as sequences which convert via
638       // vXf32.
639       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
640       // Custom-lower insert/extract operations to simplify patterns.
641       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
642                          Custom);
643       // Expand various condition codes (explained above).
644       setCondCodeAction(VFPCCToExpand, VT, Expand);
645 
646       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
647 
648       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
649                          VT, Custom);
650 
651       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
652                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
653                          VT, Custom);
654 
655       // Expand FP operations that need libcalls.
656       setOperationAction(ISD::FREM, VT, Expand);
657       setOperationAction(ISD::FPOW, VT, Expand);
658       setOperationAction(ISD::FCOS, VT, Expand);
659       setOperationAction(ISD::FSIN, VT, Expand);
660       setOperationAction(ISD::FSINCOS, VT, Expand);
661       setOperationAction(ISD::FEXP, VT, Expand);
662       setOperationAction(ISD::FEXP2, VT, Expand);
663       setOperationAction(ISD::FLOG, VT, Expand);
664       setOperationAction(ISD::FLOG2, VT, Expand);
665       setOperationAction(ISD::FLOG10, VT, Expand);
666       setOperationAction(ISD::FRINT, VT, Expand);
667       setOperationAction(ISD::FNEARBYINT, VT, Expand);
668 
669       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
670       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
671       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
672       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
673 
674       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
675 
676       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
677 
678       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
679                          VT, Custom);
680 
681       setOperationAction(
682           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
683           Custom);
684 
685       setOperationAction(ISD::SELECT, VT, Custom);
686       setOperationAction(ISD::SELECT_CC, VT, Expand);
687 
688       setOperationAction(
689           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
690           VT, Custom);
691 
692       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
693 
694       setOperationAction(FloatingPointVPOps, VT, Custom);
695     };
696 
697     // Sets common extload/truncstore actions on RVV floating-point vector
698     // types.
699     const auto SetCommonVFPExtLoadTruncStoreActions =
700         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
701           for (auto SmallVT : SmallerVTs) {
702             setTruncStoreAction(VT, SmallVT, Expand);
703             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
704           }
705         };
706 
707     if (Subtarget.hasVInstructionsF16())
708       for (MVT VT : F16VecVTs)
709         SetCommonVFPActions(VT);
710 
711     for (MVT VT : F32VecVTs) {
712       if (Subtarget.hasVInstructionsF32())
713         SetCommonVFPActions(VT);
714       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
715     }
716 
717     for (MVT VT : F64VecVTs) {
718       if (Subtarget.hasVInstructionsF64())
719         SetCommonVFPActions(VT);
720       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
721       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
722     }
723 
724     if (Subtarget.useRVVForFixedLengthVectors()) {
725       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
726         if (!useRVVForFixedLengthVectorVT(VT))
727           continue;
728 
729         // By default everything must be expanded.
730         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
731           setOperationAction(Op, VT, Expand);
732         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
733           setTruncStoreAction(VT, OtherVT, Expand);
734           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
735                            OtherVT, VT, Expand);
736         }
737 
738         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
739         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
740                            Custom);
741 
742         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
743                            Custom);
744 
745         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
746                            VT, Custom);
747 
748         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
749 
750         setOperationAction(ISD::SETCC, VT, Custom);
751 
752         setOperationAction(ISD::SELECT, VT, Custom);
753 
754         setOperationAction(ISD::TRUNCATE, VT, Custom);
755 
756         setOperationAction(ISD::BITCAST, VT, Custom);
757 
758         setOperationAction(
759             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
760             Custom);
761 
762         setOperationAction(
763             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
764             Custom);
765 
766         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
767                             ISD::FP_TO_UINT},
768                            VT, Custom);
769 
770         // Operations below are different for between masks and other vectors.
771         if (VT.getVectorElementType() == MVT::i1) {
772           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
773                               ISD::OR, ISD::XOR},
774                              VT, Custom);
775 
776           setOperationAction(
777               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
778               VT, Custom);
779           continue;
780         }
781 
782         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
783         // it before type legalization for i64 vectors on RV32. It will then be
784         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
785         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
786         // improvements first.
787         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
788           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
789           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
790         }
791 
792         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
793         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
794 
795         setOperationAction(
796             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
797 
798         setOperationAction(
799             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
800             Custom);
801 
802         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
803                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
804                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
805                            VT, Custom);
806 
807         setOperationAction(
808             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
809 
810         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
811         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
812           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
813 
814         setOperationAction(
815             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
816             Custom);
817 
818         setOperationAction(ISD::VSELECT, VT, Custom);
819         setOperationAction(ISD::SELECT_CC, VT, Expand);
820 
821         setOperationAction(
822             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
823 
824         // Custom-lower reduction operations to set up the corresponding custom
825         // nodes' operands.
826         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
827                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
828                             ISD::VECREDUCE_UMIN},
829                            VT, Custom);
830 
831         setOperationAction(IntegerVPOps, VT, Custom);
832 
833         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
834         // type that can represent the value exactly.
835         if (VT.getVectorElementType() != MVT::i64) {
836           MVT FloatEltVT =
837               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
838           EVT FloatVT =
839               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
840           if (isTypeLegal(FloatVT))
841             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
842                                Custom);
843         }
844       }
845 
846       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
847         if (!useRVVForFixedLengthVectorVT(VT))
848           continue;
849 
850         // By default everything must be expanded.
851         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
852           setOperationAction(Op, VT, Expand);
853         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
854           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
855           setTruncStoreAction(VT, OtherVT, Expand);
856         }
857 
858         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
859         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
860                            Custom);
861 
862         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
863                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
864                             ISD::EXTRACT_VECTOR_ELT},
865                            VT, Custom);
866 
867         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
868                             ISD::MGATHER, ISD::MSCATTER},
869                            VT, Custom);
870 
871         setOperationAction(
872             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
873             Custom);
874 
875         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
876                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
877                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
878                            VT, Custom);
879 
880         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
881 
882         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
883                            VT, Custom);
884 
885         for (auto CC : VFPCCToExpand)
886           setCondCodeAction(CC, VT, Expand);
887 
888         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
889         setOperationAction(ISD::SELECT_CC, VT, Expand);
890 
891         setOperationAction(ISD::BITCAST, VT, Custom);
892 
893         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
894                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
895                            VT, Custom);
896 
897         setOperationAction(FloatingPointVPOps, VT, Custom);
898       }
899 
900       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
901       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
902                          Custom);
903       if (Subtarget.hasStdExtZfh())
904         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
905       if (Subtarget.hasStdExtF())
906         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
907       if (Subtarget.hasStdExtD())
908         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
909     }
910   }
911 
912   // Function alignments.
913   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
914   setMinFunctionAlignment(FunctionAlignment);
915   setPrefFunctionAlignment(FunctionAlignment);
916 
917   setMinimumJumpTableEntries(5);
918 
919   // Jumps are expensive, compared to logic
920   setJumpIsExpensive();
921 
922   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
923                        ISD::OR, ISD::XOR});
924 
925   if (Subtarget.hasStdExtF())
926     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
927 
928   if (Subtarget.hasStdExtZbp())
929     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
930 
931   if (Subtarget.hasStdExtZbb())
932     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
933 
934   if (Subtarget.hasStdExtZbkb())
935     setTargetDAGCombine(ISD::BITREVERSE);
936   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
937     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
938   if (Subtarget.hasStdExtF())
939     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
940                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
941   if (Subtarget.hasVInstructions())
942     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
943                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
944                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
945   if (Subtarget.useRVVForFixedLengthVectors())
946     setTargetDAGCombine(ISD::BITCAST);
947 
948   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
949   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
950 }
951 
952 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
953                                             LLVMContext &Context,
954                                             EVT VT) const {
955   if (!VT.isVector())
956     return getPointerTy(DL);
957   if (Subtarget.hasVInstructions() &&
958       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
959     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
960   return VT.changeVectorElementTypeToInteger();
961 }
962 
963 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
964   return Subtarget.getXLenVT();
965 }
966 
967 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
968                                              const CallInst &I,
969                                              MachineFunction &MF,
970                                              unsigned Intrinsic) const {
971   auto &DL = I.getModule()->getDataLayout();
972   switch (Intrinsic) {
973   default:
974     return false;
975   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
976   case Intrinsic::riscv_masked_atomicrmw_add_i32:
977   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
978   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
979   case Intrinsic::riscv_masked_atomicrmw_max_i32:
980   case Intrinsic::riscv_masked_atomicrmw_min_i32:
981   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
982   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
983   case Intrinsic::riscv_masked_cmpxchg_i32:
984     Info.opc = ISD::INTRINSIC_W_CHAIN;
985     Info.memVT = MVT::i32;
986     Info.ptrVal = I.getArgOperand(0);
987     Info.offset = 0;
988     Info.align = Align(4);
989     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
990                  MachineMemOperand::MOVolatile;
991     return true;
992   case Intrinsic::riscv_masked_strided_load:
993     Info.opc = ISD::INTRINSIC_W_CHAIN;
994     Info.ptrVal = I.getArgOperand(1);
995     Info.memVT = getValueType(DL, I.getType()->getScalarType());
996     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
997     Info.size = MemoryLocation::UnknownSize;
998     Info.flags |= MachineMemOperand::MOLoad;
999     return true;
1000   case Intrinsic::riscv_masked_strided_store:
1001     Info.opc = ISD::INTRINSIC_VOID;
1002     Info.ptrVal = I.getArgOperand(1);
1003     Info.memVT =
1004         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1005     Info.align = Align(
1006         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1007         8);
1008     Info.size = MemoryLocation::UnknownSize;
1009     Info.flags |= MachineMemOperand::MOStore;
1010     return true;
1011   case Intrinsic::riscv_seg2_load:
1012   case Intrinsic::riscv_seg3_load:
1013   case Intrinsic::riscv_seg4_load:
1014   case Intrinsic::riscv_seg5_load:
1015   case Intrinsic::riscv_seg6_load:
1016   case Intrinsic::riscv_seg7_load:
1017   case Intrinsic::riscv_seg8_load:
1018     Info.opc = ISD::INTRINSIC_W_CHAIN;
1019     Info.ptrVal = I.getArgOperand(0);
1020     Info.memVT =
1021         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1022     Info.align =
1023         Align(DL.getTypeSizeInBits(
1024                   I.getType()->getStructElementType(0)->getScalarType()) /
1025               8);
1026     Info.size = MemoryLocation::UnknownSize;
1027     Info.flags |= MachineMemOperand::MOLoad;
1028     return true;
1029   }
1030 }
1031 
1032 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1033                                                 const AddrMode &AM, Type *Ty,
1034                                                 unsigned AS,
1035                                                 Instruction *I) const {
1036   // No global is ever allowed as a base.
1037   if (AM.BaseGV)
1038     return false;
1039 
1040   // RVV instructions only support register addressing.
1041   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1042     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1043 
1044   // Require a 12-bit signed offset.
1045   if (!isInt<12>(AM.BaseOffs))
1046     return false;
1047 
1048   switch (AM.Scale) {
1049   case 0: // "r+i" or just "i", depending on HasBaseReg.
1050     break;
1051   case 1:
1052     if (!AM.HasBaseReg) // allow "r+i".
1053       break;
1054     return false; // disallow "r+r" or "r+r+i".
1055   default:
1056     return false;
1057   }
1058 
1059   return true;
1060 }
1061 
1062 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1063   return isInt<12>(Imm);
1064 }
1065 
1066 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1067   return isInt<12>(Imm);
1068 }
1069 
1070 // On RV32, 64-bit integers are split into their high and low parts and held
1071 // in two different registers, so the trunc is free since the low register can
1072 // just be used.
1073 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1074   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1075     return false;
1076   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1077   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1078   return (SrcBits == 64 && DestBits == 32);
1079 }
1080 
1081 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1082   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1083       !SrcVT.isInteger() || !DstVT.isInteger())
1084     return false;
1085   unsigned SrcBits = SrcVT.getSizeInBits();
1086   unsigned DestBits = DstVT.getSizeInBits();
1087   return (SrcBits == 64 && DestBits == 32);
1088 }
1089 
1090 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1091   // Zexts are free if they can be combined with a load.
1092   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1093   // poorly with type legalization of compares preferring sext.
1094   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1095     EVT MemVT = LD->getMemoryVT();
1096     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1097         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1098          LD->getExtensionType() == ISD::ZEXTLOAD))
1099       return true;
1100   }
1101 
1102   return TargetLowering::isZExtFree(Val, VT2);
1103 }
1104 
1105 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1106   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1107 }
1108 
1109 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1110   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1111 }
1112 
1113 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1114   return Subtarget.hasStdExtZbb();
1115 }
1116 
1117 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1118   return Subtarget.hasStdExtZbb();
1119 }
1120 
1121 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1122   EVT VT = Y.getValueType();
1123 
1124   // FIXME: Support vectors once we have tests.
1125   if (VT.isVector())
1126     return false;
1127 
1128   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1129           Subtarget.hasStdExtZbkb()) &&
1130          !isa<ConstantSDNode>(Y);
1131 }
1132 
1133 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1134   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1135   auto *C = dyn_cast<ConstantSDNode>(Y);
1136   return C && C->getAPIntValue().ule(10);
1137 }
1138 
1139 bool RISCVTargetLowering::
1140     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1141         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1142         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1143         SelectionDAG &DAG) const {
1144   // One interesting pattern that we'd want to form is 'bit extract':
1145   //   ((1 >> Y) & 1) ==/!= 0
1146   // But we also need to be careful not to try to reverse that fold.
1147 
1148   // Is this '((1 >> Y) & 1)'?
1149   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1150     return false; // Keep the 'bit extract' pattern.
1151 
1152   // Will this be '((1 >> Y) & 1)' after the transform?
1153   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1154     return true; // Do form the 'bit extract' pattern.
1155 
1156   // If 'X' is a constant, and we transform, then we will immediately
1157   // try to undo the fold, thus causing endless combine loop.
1158   // So only do the transform if X is not a constant. This matches the default
1159   // implementation of this function.
1160   return !XC;
1161 }
1162 
1163 /// Check if sinking \p I's operands to I's basic block is profitable, because
1164 /// the operands can be folded into a target instruction, e.g.
1165 /// splats of scalars can fold into vector instructions.
1166 bool RISCVTargetLowering::shouldSinkOperands(
1167     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1168   using namespace llvm::PatternMatch;
1169 
1170   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1171     return false;
1172 
1173   auto IsSinker = [&](Instruction *I, int Operand) {
1174     switch (I->getOpcode()) {
1175     case Instruction::Add:
1176     case Instruction::Sub:
1177     case Instruction::Mul:
1178     case Instruction::And:
1179     case Instruction::Or:
1180     case Instruction::Xor:
1181     case Instruction::FAdd:
1182     case Instruction::FSub:
1183     case Instruction::FMul:
1184     case Instruction::FDiv:
1185     case Instruction::ICmp:
1186     case Instruction::FCmp:
1187       return true;
1188     case Instruction::Shl:
1189     case Instruction::LShr:
1190     case Instruction::AShr:
1191     case Instruction::UDiv:
1192     case Instruction::SDiv:
1193     case Instruction::URem:
1194     case Instruction::SRem:
1195       return Operand == 1;
1196     case Instruction::Call:
1197       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1198         switch (II->getIntrinsicID()) {
1199         case Intrinsic::fma:
1200         case Intrinsic::vp_fma:
1201           return Operand == 0 || Operand == 1;
1202         // FIXME: Our patterns can only match vx/vf instructions when the splat
1203         // it on the RHS, because TableGen doesn't recognize our VP operations
1204         // as commutative.
1205         case Intrinsic::vp_add:
1206         case Intrinsic::vp_mul:
1207         case Intrinsic::vp_and:
1208         case Intrinsic::vp_or:
1209         case Intrinsic::vp_xor:
1210         case Intrinsic::vp_fadd:
1211         case Intrinsic::vp_fmul:
1212         case Intrinsic::vp_shl:
1213         case Intrinsic::vp_lshr:
1214         case Intrinsic::vp_ashr:
1215         case Intrinsic::vp_udiv:
1216         case Intrinsic::vp_sdiv:
1217         case Intrinsic::vp_urem:
1218         case Intrinsic::vp_srem:
1219           return Operand == 1;
1220         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1221         // explicit patterns for both LHS and RHS (as 'vr' versions).
1222         case Intrinsic::vp_sub:
1223         case Intrinsic::vp_fsub:
1224         case Intrinsic::vp_fdiv:
1225           return Operand == 0 || Operand == 1;
1226         default:
1227           return false;
1228         }
1229       }
1230       return false;
1231     default:
1232       return false;
1233     }
1234   };
1235 
1236   for (auto OpIdx : enumerate(I->operands())) {
1237     if (!IsSinker(I, OpIdx.index()))
1238       continue;
1239 
1240     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1241     // Make sure we are not already sinking this operand
1242     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1243       continue;
1244 
1245     // We are looking for a splat that can be sunk.
1246     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1247                              m_Undef(), m_ZeroMask())))
1248       continue;
1249 
1250     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1251     // and vector registers
1252     for (Use &U : Op->uses()) {
1253       Instruction *Insn = cast<Instruction>(U.getUser());
1254       if (!IsSinker(Insn, U.getOperandNo()))
1255         return false;
1256     }
1257 
1258     Ops.push_back(&Op->getOperandUse(0));
1259     Ops.push_back(&OpIdx.value());
1260   }
1261   return true;
1262 }
1263 
1264 bool RISCVTargetLowering::isOffsetFoldingLegal(
1265     const GlobalAddressSDNode *GA) const {
1266   // In order to maximise the opportunity for common subexpression elimination,
1267   // keep a separate ADD node for the global address offset instead of folding
1268   // it in the global address node. Later peephole optimisations may choose to
1269   // fold it back in when profitable.
1270   return false;
1271 }
1272 
1273 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1274                                        bool ForCodeSize) const {
1275   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1276   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1277     return false;
1278   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1279     return false;
1280   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1281     return false;
1282   return Imm.isZero();
1283 }
1284 
1285 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1286   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1287          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1288          (VT == MVT::f64 && Subtarget.hasStdExtD());
1289 }
1290 
1291 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1292                                                       CallingConv::ID CC,
1293                                                       EVT VT) const {
1294   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1295   // We might still end up using a GPR but that will be decided based on ABI.
1296   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1297   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1298     return MVT::f32;
1299 
1300   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1301 }
1302 
1303 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1304                                                            CallingConv::ID CC,
1305                                                            EVT VT) const {
1306   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1307   // We might still end up using a GPR but that will be decided based on ABI.
1308   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1309   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1310     return 1;
1311 
1312   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1313 }
1314 
1315 // Changes the condition code and swaps operands if necessary, so the SetCC
1316 // operation matches one of the comparisons supported directly by branches
1317 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1318 // with 1/-1.
1319 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1320                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1321   // Convert X > -1 to X >= 0.
1322   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1323     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1324     CC = ISD::SETGE;
1325     return;
1326   }
1327   // Convert X < 1 to 0 >= X.
1328   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1329     RHS = LHS;
1330     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1331     CC = ISD::SETGE;
1332     return;
1333   }
1334 
1335   switch (CC) {
1336   default:
1337     break;
1338   case ISD::SETGT:
1339   case ISD::SETLE:
1340   case ISD::SETUGT:
1341   case ISD::SETULE:
1342     CC = ISD::getSetCCSwappedOperands(CC);
1343     std::swap(LHS, RHS);
1344     break;
1345   }
1346 }
1347 
1348 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1349   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1350   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1351   if (VT.getVectorElementType() == MVT::i1)
1352     KnownSize *= 8;
1353 
1354   switch (KnownSize) {
1355   default:
1356     llvm_unreachable("Invalid LMUL.");
1357   case 8:
1358     return RISCVII::VLMUL::LMUL_F8;
1359   case 16:
1360     return RISCVII::VLMUL::LMUL_F4;
1361   case 32:
1362     return RISCVII::VLMUL::LMUL_F2;
1363   case 64:
1364     return RISCVII::VLMUL::LMUL_1;
1365   case 128:
1366     return RISCVII::VLMUL::LMUL_2;
1367   case 256:
1368     return RISCVII::VLMUL::LMUL_4;
1369   case 512:
1370     return RISCVII::VLMUL::LMUL_8;
1371   }
1372 }
1373 
1374 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1375   switch (LMul) {
1376   default:
1377     llvm_unreachable("Invalid LMUL.");
1378   case RISCVII::VLMUL::LMUL_F8:
1379   case RISCVII::VLMUL::LMUL_F4:
1380   case RISCVII::VLMUL::LMUL_F2:
1381   case RISCVII::VLMUL::LMUL_1:
1382     return RISCV::VRRegClassID;
1383   case RISCVII::VLMUL::LMUL_2:
1384     return RISCV::VRM2RegClassID;
1385   case RISCVII::VLMUL::LMUL_4:
1386     return RISCV::VRM4RegClassID;
1387   case RISCVII::VLMUL::LMUL_8:
1388     return RISCV::VRM8RegClassID;
1389   }
1390 }
1391 
1392 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1393   RISCVII::VLMUL LMUL = getLMUL(VT);
1394   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1395       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1396       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1397       LMUL == RISCVII::VLMUL::LMUL_1) {
1398     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1399                   "Unexpected subreg numbering");
1400     return RISCV::sub_vrm1_0 + Index;
1401   }
1402   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1403     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1404                   "Unexpected subreg numbering");
1405     return RISCV::sub_vrm2_0 + Index;
1406   }
1407   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1408     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1409                   "Unexpected subreg numbering");
1410     return RISCV::sub_vrm4_0 + Index;
1411   }
1412   llvm_unreachable("Invalid vector type.");
1413 }
1414 
1415 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1416   if (VT.getVectorElementType() == MVT::i1)
1417     return RISCV::VRRegClassID;
1418   return getRegClassIDForLMUL(getLMUL(VT));
1419 }
1420 
1421 // Attempt to decompose a subvector insert/extract between VecVT and
1422 // SubVecVT via subregister indices. Returns the subregister index that
1423 // can perform the subvector insert/extract with the given element index, as
1424 // well as the index corresponding to any leftover subvectors that must be
1425 // further inserted/extracted within the register class for SubVecVT.
1426 std::pair<unsigned, unsigned>
1427 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1428     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1429     const RISCVRegisterInfo *TRI) {
1430   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1431                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1432                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1433                 "Register classes not ordered");
1434   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1435   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1436   // Try to compose a subregister index that takes us from the incoming
1437   // LMUL>1 register class down to the outgoing one. At each step we half
1438   // the LMUL:
1439   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1440   // Note that this is not guaranteed to find a subregister index, such as
1441   // when we are extracting from one VR type to another.
1442   unsigned SubRegIdx = RISCV::NoSubRegister;
1443   for (const unsigned RCID :
1444        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1445     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1446       VecVT = VecVT.getHalfNumVectorElementsVT();
1447       bool IsHi =
1448           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1449       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1450                                             getSubregIndexByMVT(VecVT, IsHi));
1451       if (IsHi)
1452         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1453     }
1454   return {SubRegIdx, InsertExtractIdx};
1455 }
1456 
1457 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1458 // stores for those types.
1459 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1460   return !Subtarget.useRVVForFixedLengthVectors() ||
1461          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1462 }
1463 
1464 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1465   if (ScalarTy->isPointerTy())
1466     return true;
1467 
1468   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1469       ScalarTy->isIntegerTy(32))
1470     return true;
1471 
1472   if (ScalarTy->isIntegerTy(64))
1473     return Subtarget.hasVInstructionsI64();
1474 
1475   if (ScalarTy->isHalfTy())
1476     return Subtarget.hasVInstructionsF16();
1477   if (ScalarTy->isFloatTy())
1478     return Subtarget.hasVInstructionsF32();
1479   if (ScalarTy->isDoubleTy())
1480     return Subtarget.hasVInstructionsF64();
1481 
1482   return false;
1483 }
1484 
1485 static SDValue getVLOperand(SDValue Op) {
1486   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1487           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1488          "Unexpected opcode");
1489   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1490   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1491   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1492       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1493   if (!II)
1494     return SDValue();
1495   return Op.getOperand(II->VLOperand + 1 + HasChain);
1496 }
1497 
1498 static bool useRVVForFixedLengthVectorVT(MVT VT,
1499                                          const RISCVSubtarget &Subtarget) {
1500   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1501   if (!Subtarget.useRVVForFixedLengthVectors())
1502     return false;
1503 
1504   // We only support a set of vector types with a consistent maximum fixed size
1505   // across all supported vector element types to avoid legalization issues.
1506   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1507   // fixed-length vector type we support is 1024 bytes.
1508   if (VT.getFixedSizeInBits() > 1024 * 8)
1509     return false;
1510 
1511   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1512 
1513   MVT EltVT = VT.getVectorElementType();
1514 
1515   // Don't use RVV for vectors we cannot scalarize if required.
1516   switch (EltVT.SimpleTy) {
1517   // i1 is supported but has different rules.
1518   default:
1519     return false;
1520   case MVT::i1:
1521     // Masks can only use a single register.
1522     if (VT.getVectorNumElements() > MinVLen)
1523       return false;
1524     MinVLen /= 8;
1525     break;
1526   case MVT::i8:
1527   case MVT::i16:
1528   case MVT::i32:
1529     break;
1530   case MVT::i64:
1531     if (!Subtarget.hasVInstructionsI64())
1532       return false;
1533     break;
1534   case MVT::f16:
1535     if (!Subtarget.hasVInstructionsF16())
1536       return false;
1537     break;
1538   case MVT::f32:
1539     if (!Subtarget.hasVInstructionsF32())
1540       return false;
1541     break;
1542   case MVT::f64:
1543     if (!Subtarget.hasVInstructionsF64())
1544       return false;
1545     break;
1546   }
1547 
1548   // Reject elements larger than ELEN.
1549   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1550     return false;
1551 
1552   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1553   // Don't use RVV for types that don't fit.
1554   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1555     return false;
1556 
1557   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1558   // the base fixed length RVV support in place.
1559   if (!VT.isPow2VectorType())
1560     return false;
1561 
1562   return true;
1563 }
1564 
1565 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1566   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1567 }
1568 
1569 // Return the largest legal scalable vector type that matches VT's element type.
1570 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1571                                             const RISCVSubtarget &Subtarget) {
1572   // This may be called before legal types are setup.
1573   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1574           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1575          "Expected legal fixed length vector!");
1576 
1577   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1578   unsigned MaxELen = Subtarget.getELEN();
1579 
1580   MVT EltVT = VT.getVectorElementType();
1581   switch (EltVT.SimpleTy) {
1582   default:
1583     llvm_unreachable("unexpected element type for RVV container");
1584   case MVT::i1:
1585   case MVT::i8:
1586   case MVT::i16:
1587   case MVT::i32:
1588   case MVT::i64:
1589   case MVT::f16:
1590   case MVT::f32:
1591   case MVT::f64: {
1592     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1593     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1594     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1595     unsigned NumElts =
1596         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1597     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1598     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1599     return MVT::getScalableVectorVT(EltVT, NumElts);
1600   }
1601   }
1602 }
1603 
1604 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1605                                             const RISCVSubtarget &Subtarget) {
1606   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1607                                           Subtarget);
1608 }
1609 
1610 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1611   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1612 }
1613 
1614 // Grow V to consume an entire RVV register.
1615 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1616                                        const RISCVSubtarget &Subtarget) {
1617   assert(VT.isScalableVector() &&
1618          "Expected to convert into a scalable vector!");
1619   assert(V.getValueType().isFixedLengthVector() &&
1620          "Expected a fixed length vector operand!");
1621   SDLoc DL(V);
1622   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1623   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1624 }
1625 
1626 // Shrink V so it's just big enough to maintain a VT's worth of data.
1627 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1628                                          const RISCVSubtarget &Subtarget) {
1629   assert(VT.isFixedLengthVector() &&
1630          "Expected to convert into a fixed length vector!");
1631   assert(V.getValueType().isScalableVector() &&
1632          "Expected a scalable vector operand!");
1633   SDLoc DL(V);
1634   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1635   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1636 }
1637 
1638 /// Return the type of the mask type suitable for masking the provided
1639 /// vector type.  This is simply an i1 element type vector of the same
1640 /// (possibly scalable) length.
1641 static MVT getMaskTypeFor(EVT VecVT) {
1642   assert(VecVT.isVector());
1643   ElementCount EC = VecVT.getVectorElementCount();
1644   return MVT::getVectorVT(MVT::i1, EC);
1645 }
1646 
1647 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1648 /// vector length VL.  .
1649 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1650                               SelectionDAG &DAG) {
1651   MVT MaskVT = getMaskTypeFor(VecVT);
1652   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1653 }
1654 
1655 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1656 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1657 // the vector type that it is contained in.
1658 static std::pair<SDValue, SDValue>
1659 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1660                 const RISCVSubtarget &Subtarget) {
1661   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1662   MVT XLenVT = Subtarget.getXLenVT();
1663   SDValue VL = VecVT.isFixedLengthVector()
1664                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1665                    : DAG.getRegister(RISCV::X0, XLenVT);
1666   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1667   return {Mask, VL};
1668 }
1669 
1670 // As above but assuming the given type is a scalable vector type.
1671 static std::pair<SDValue, SDValue>
1672 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1673                         const RISCVSubtarget &Subtarget) {
1674   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1675   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1676 }
1677 
1678 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1679 // of either is (currently) supported. This can get us into an infinite loop
1680 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1681 // as a ..., etc.
1682 // Until either (or both) of these can reliably lower any node, reporting that
1683 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1684 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1685 // which is not desirable.
1686 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1687     EVT VT, unsigned DefinedValues) const {
1688   return false;
1689 }
1690 
1691 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1692                                   const RISCVSubtarget &Subtarget) {
1693   // RISCV FP-to-int conversions saturate to the destination register size, but
1694   // don't produce 0 for nan. We can use a conversion instruction and fix the
1695   // nan case with a compare and a select.
1696   SDValue Src = Op.getOperand(0);
1697 
1698   EVT DstVT = Op.getValueType();
1699   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1700 
1701   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1702   unsigned Opc;
1703   if (SatVT == DstVT)
1704     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1705   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1706     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1707   else
1708     return SDValue();
1709   // FIXME: Support other SatVTs by clamping before or after the conversion.
1710 
1711   SDLoc DL(Op);
1712   SDValue FpToInt = DAG.getNode(
1713       Opc, DL, DstVT, Src,
1714       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1715 
1716   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1717   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1718 }
1719 
1720 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1721 // and back. Taking care to avoid converting values that are nan or already
1722 // correct.
1723 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1724 // have FRM dependencies modeled yet.
1725 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1726   MVT VT = Op.getSimpleValueType();
1727   assert(VT.isVector() && "Unexpected type");
1728 
1729   SDLoc DL(Op);
1730 
1731   // Freeze the source since we are increasing the number of uses.
1732   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1733 
1734   // Truncate to integer and convert back to FP.
1735   MVT IntVT = VT.changeVectorElementTypeToInteger();
1736   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1737   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1738 
1739   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1740 
1741   if (Op.getOpcode() == ISD::FCEIL) {
1742     // If the truncated value is the greater than or equal to the original
1743     // value, we've computed the ceil. Otherwise, we went the wrong way and
1744     // need to increase by 1.
1745     // FIXME: This should use a masked operation. Handle here or in isel?
1746     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1747                                  DAG.getConstantFP(1.0, DL, VT));
1748     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1749     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1750   } else if (Op.getOpcode() == ISD::FFLOOR) {
1751     // If the truncated value is the less than or equal to the original value,
1752     // we've computed the floor. Otherwise, we went the wrong way and need to
1753     // decrease by 1.
1754     // FIXME: This should use a masked operation. Handle here or in isel?
1755     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1756                                  DAG.getConstantFP(1.0, DL, VT));
1757     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1758     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1759   }
1760 
1761   // Restore the original sign so that -0.0 is preserved.
1762   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1763 
1764   // Determine the largest integer that can be represented exactly. This and
1765   // values larger than it don't have any fractional bits so don't need to
1766   // be converted.
1767   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1768   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1769   APFloat MaxVal = APFloat(FltSem);
1770   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1771                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1772   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1773 
1774   // If abs(Src) was larger than MaxVal or nan, keep it.
1775   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1776   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1777   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1778 }
1779 
1780 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1781 // This mode isn't supported in vector hardware on RISCV. But as long as we
1782 // aren't compiling with trapping math, we can emulate this with
1783 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1784 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1785 // dependencies modeled yet.
1786 // FIXME: Use masked operations to avoid final merge.
1787 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1788   MVT VT = Op.getSimpleValueType();
1789   assert(VT.isVector() && "Unexpected type");
1790 
1791   SDLoc DL(Op);
1792 
1793   // Freeze the source since we are increasing the number of uses.
1794   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1795 
1796   // We do the conversion on the absolute value and fix the sign at the end.
1797   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1798 
1799   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1800   bool Ignored;
1801   APFloat Point5Pred = APFloat(0.5f);
1802   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1803   Point5Pred.next(/*nextDown*/ true);
1804 
1805   // Add the adjustment.
1806   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1807                                DAG.getConstantFP(Point5Pred, DL, VT));
1808 
1809   // Truncate to integer and convert back to fp.
1810   MVT IntVT = VT.changeVectorElementTypeToInteger();
1811   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1812   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1813 
1814   // Restore the original sign.
1815   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1816 
1817   // Determine the largest integer that can be represented exactly. This and
1818   // values larger than it don't have any fractional bits so don't need to
1819   // be converted.
1820   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1821   APFloat MaxVal = APFloat(FltSem);
1822   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1823                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1824   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1825 
1826   // If abs(Src) was larger than MaxVal or nan, keep it.
1827   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1828   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1829   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1830 }
1831 
1832 struct VIDSequence {
1833   int64_t StepNumerator;
1834   unsigned StepDenominator;
1835   int64_t Addend;
1836 };
1837 
1838 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1839 // to the (non-zero) step S and start value X. This can be then lowered as the
1840 // RVV sequence (VID * S) + X, for example.
1841 // The step S is represented as an integer numerator divided by a positive
1842 // denominator. Note that the implementation currently only identifies
1843 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1844 // cannot detect 2/3, for example.
1845 // Note that this method will also match potentially unappealing index
1846 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1847 // determine whether this is worth generating code for.
1848 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1849   unsigned NumElts = Op.getNumOperands();
1850   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1851   if (!Op.getValueType().isInteger())
1852     return None;
1853 
1854   Optional<unsigned> SeqStepDenom;
1855   Optional<int64_t> SeqStepNum, SeqAddend;
1856   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1857   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1858   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1859     // Assume undef elements match the sequence; we just have to be careful
1860     // when interpolating across them.
1861     if (Op.getOperand(Idx).isUndef())
1862       continue;
1863     // The BUILD_VECTOR must be all constants.
1864     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1865       return None;
1866 
1867     uint64_t Val = Op.getConstantOperandVal(Idx) &
1868                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1869 
1870     if (PrevElt) {
1871       // Calculate the step since the last non-undef element, and ensure
1872       // it's consistent across the entire sequence.
1873       unsigned IdxDiff = Idx - PrevElt->second;
1874       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1875 
1876       // A zero-value value difference means that we're somewhere in the middle
1877       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1878       // step change before evaluating the sequence.
1879       if (ValDiff == 0)
1880         continue;
1881 
1882       int64_t Remainder = ValDiff % IdxDiff;
1883       // Normalize the step if it's greater than 1.
1884       if (Remainder != ValDiff) {
1885         // The difference must cleanly divide the element span.
1886         if (Remainder != 0)
1887           return None;
1888         ValDiff /= IdxDiff;
1889         IdxDiff = 1;
1890       }
1891 
1892       if (!SeqStepNum)
1893         SeqStepNum = ValDiff;
1894       else if (ValDiff != SeqStepNum)
1895         return None;
1896 
1897       if (!SeqStepDenom)
1898         SeqStepDenom = IdxDiff;
1899       else if (IdxDiff != *SeqStepDenom)
1900         return None;
1901     }
1902 
1903     // Record this non-undef element for later.
1904     if (!PrevElt || PrevElt->first != Val)
1905       PrevElt = std::make_pair(Val, Idx);
1906   }
1907 
1908   // We need to have logged a step for this to count as a legal index sequence.
1909   if (!SeqStepNum || !SeqStepDenom)
1910     return None;
1911 
1912   // Loop back through the sequence and validate elements we might have skipped
1913   // while waiting for a valid step. While doing this, log any sequence addend.
1914   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1915     if (Op.getOperand(Idx).isUndef())
1916       continue;
1917     uint64_t Val = Op.getConstantOperandVal(Idx) &
1918                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1919     uint64_t ExpectedVal =
1920         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1921     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1922     if (!SeqAddend)
1923       SeqAddend = Addend;
1924     else if (Addend != SeqAddend)
1925       return None;
1926   }
1927 
1928   assert(SeqAddend && "Must have an addend if we have a step");
1929 
1930   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1931 }
1932 
1933 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1934 // and lower it as a VRGATHER_VX_VL from the source vector.
1935 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1936                                   SelectionDAG &DAG,
1937                                   const RISCVSubtarget &Subtarget) {
1938   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1939     return SDValue();
1940   SDValue Vec = SplatVal.getOperand(0);
1941   // Only perform this optimization on vectors of the same size for simplicity.
1942   // Don't perform this optimization for i1 vectors.
1943   // FIXME: Support i1 vectors, maybe by promoting to i8?
1944   if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
1945     return SDValue();
1946   SDValue Idx = SplatVal.getOperand(1);
1947   // The index must be a legal type.
1948   if (Idx.getValueType() != Subtarget.getXLenVT())
1949     return SDValue();
1950 
1951   MVT ContainerVT = VT;
1952   if (VT.isFixedLengthVector()) {
1953     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1954     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1955   }
1956 
1957   SDValue Mask, VL;
1958   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1959 
1960   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
1961                                DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
1962 
1963   if (!VT.isFixedLengthVector())
1964     return Gather;
1965 
1966   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1967 }
1968 
1969 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1970                                  const RISCVSubtarget &Subtarget) {
1971   MVT VT = Op.getSimpleValueType();
1972   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1973 
1974   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1975 
1976   SDLoc DL(Op);
1977   SDValue Mask, VL;
1978   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1979 
1980   MVT XLenVT = Subtarget.getXLenVT();
1981   unsigned NumElts = Op.getNumOperands();
1982 
1983   if (VT.getVectorElementType() == MVT::i1) {
1984     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1985       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1986       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1987     }
1988 
1989     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1990       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1991       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1992     }
1993 
1994     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1995     // scalar integer chunks whose bit-width depends on the number of mask
1996     // bits and XLEN.
1997     // First, determine the most appropriate scalar integer type to use. This
1998     // is at most XLenVT, but may be shrunk to a smaller vector element type
1999     // according to the size of the final vector - use i8 chunks rather than
2000     // XLenVT if we're producing a v8i1. This results in more consistent
2001     // codegen across RV32 and RV64.
2002     unsigned NumViaIntegerBits =
2003         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2004     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2005     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2006       // If we have to use more than one INSERT_VECTOR_ELT then this
2007       // optimization is likely to increase code size; avoid peforming it in
2008       // such a case. We can use a load from a constant pool in this case.
2009       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2010         return SDValue();
2011       // Now we can create our integer vector type. Note that it may be larger
2012       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2013       MVT IntegerViaVecVT =
2014           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2015                            divideCeil(NumElts, NumViaIntegerBits));
2016 
2017       uint64_t Bits = 0;
2018       unsigned BitPos = 0, IntegerEltIdx = 0;
2019       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2020 
2021       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2022         // Once we accumulate enough bits to fill our scalar type, insert into
2023         // our vector and clear our accumulated data.
2024         if (I != 0 && I % NumViaIntegerBits == 0) {
2025           if (NumViaIntegerBits <= 32)
2026             Bits = SignExtend64<32>(Bits);
2027           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2028           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2029                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2030           Bits = 0;
2031           BitPos = 0;
2032           IntegerEltIdx++;
2033         }
2034         SDValue V = Op.getOperand(I);
2035         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2036         Bits |= ((uint64_t)BitValue << BitPos);
2037       }
2038 
2039       // Insert the (remaining) scalar value into position in our integer
2040       // vector type.
2041       if (NumViaIntegerBits <= 32)
2042         Bits = SignExtend64<32>(Bits);
2043       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2044       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2045                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2046 
2047       if (NumElts < NumViaIntegerBits) {
2048         // If we're producing a smaller vector than our minimum legal integer
2049         // type, bitcast to the equivalent (known-legal) mask type, and extract
2050         // our final mask.
2051         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2052         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2053         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2054                           DAG.getConstant(0, DL, XLenVT));
2055       } else {
2056         // Else we must have produced an integer type with the same size as the
2057         // mask type; bitcast for the final result.
2058         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2059         Vec = DAG.getBitcast(VT, Vec);
2060       }
2061 
2062       return Vec;
2063     }
2064 
2065     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2066     // vector type, we have a legal equivalently-sized i8 type, so we can use
2067     // that.
2068     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2069     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2070 
2071     SDValue WideVec;
2072     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2073       // For a splat, perform a scalar truncate before creating the wider
2074       // vector.
2075       assert(Splat.getValueType() == XLenVT &&
2076              "Unexpected type for i1 splat value");
2077       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2078                           DAG.getConstant(1, DL, XLenVT));
2079       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2080     } else {
2081       SmallVector<SDValue, 8> Ops(Op->op_values());
2082       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2083       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2084       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2085     }
2086 
2087     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2088   }
2089 
2090   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2091     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2092       return Gather;
2093     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2094                                         : RISCVISD::VMV_V_X_VL;
2095     Splat =
2096         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2097     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2098   }
2099 
2100   // Try and match index sequences, which we can lower to the vid instruction
2101   // with optional modifications. An all-undef vector is matched by
2102   // getSplatValue, above.
2103   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2104     int64_t StepNumerator = SimpleVID->StepNumerator;
2105     unsigned StepDenominator = SimpleVID->StepDenominator;
2106     int64_t Addend = SimpleVID->Addend;
2107 
2108     assert(StepNumerator != 0 && "Invalid step");
2109     bool Negate = false;
2110     int64_t SplatStepVal = StepNumerator;
2111     unsigned StepOpcode = ISD::MUL;
2112     if (StepNumerator != 1) {
2113       if (isPowerOf2_64(std::abs(StepNumerator))) {
2114         Negate = StepNumerator < 0;
2115         StepOpcode = ISD::SHL;
2116         SplatStepVal = Log2_64(std::abs(StepNumerator));
2117       }
2118     }
2119 
2120     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2121     // threshold since it's the immediate value many RVV instructions accept.
2122     // There is no vmul.vi instruction so ensure multiply constant can fit in
2123     // a single addi instruction.
2124     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2125          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2126         isPowerOf2_32(StepDenominator) &&
2127         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2128       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2129       // Convert right out of the scalable type so we can use standard ISD
2130       // nodes for the rest of the computation. If we used scalable types with
2131       // these, we'd lose the fixed-length vector info and generate worse
2132       // vsetvli code.
2133       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2134       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2135           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2136         SDValue SplatStep = DAG.getSplatBuildVector(
2137             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2138         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2139       }
2140       if (StepDenominator != 1) {
2141         SDValue SplatStep = DAG.getSplatBuildVector(
2142             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2143         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2144       }
2145       if (Addend != 0 || Negate) {
2146         SDValue SplatAddend = DAG.getSplatBuildVector(
2147             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2148         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2149       }
2150       return VID;
2151     }
2152   }
2153 
2154   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2155   // when re-interpreted as a vector with a larger element type. For example,
2156   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2157   // could be instead splat as
2158   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2159   // TODO: This optimization could also work on non-constant splats, but it
2160   // would require bit-manipulation instructions to construct the splat value.
2161   SmallVector<SDValue> Sequence;
2162   unsigned EltBitSize = VT.getScalarSizeInBits();
2163   const auto *BV = cast<BuildVectorSDNode>(Op);
2164   if (VT.isInteger() && EltBitSize < 64 &&
2165       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2166       BV->getRepeatedSequence(Sequence) &&
2167       (Sequence.size() * EltBitSize) <= 64) {
2168     unsigned SeqLen = Sequence.size();
2169     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2170     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2171     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2172             ViaIntVT == MVT::i64) &&
2173            "Unexpected sequence type");
2174 
2175     unsigned EltIdx = 0;
2176     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2177     uint64_t SplatValue = 0;
2178     // Construct the amalgamated value which can be splatted as this larger
2179     // vector type.
2180     for (const auto &SeqV : Sequence) {
2181       if (!SeqV.isUndef())
2182         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2183                        << (EltIdx * EltBitSize));
2184       EltIdx++;
2185     }
2186 
2187     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2188     // achieve better constant materializion.
2189     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2190       SplatValue = SignExtend64<32>(SplatValue);
2191 
2192     // Since we can't introduce illegal i64 types at this stage, we can only
2193     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2194     // way we can use RVV instructions to splat.
2195     assert((ViaIntVT.bitsLE(XLenVT) ||
2196             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2197            "Unexpected bitcast sequence");
2198     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2199       SDValue ViaVL =
2200           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2201       MVT ViaContainerVT =
2202           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2203       SDValue Splat =
2204           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2205                       DAG.getUNDEF(ViaContainerVT),
2206                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2207       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2208       return DAG.getBitcast(VT, Splat);
2209     }
2210   }
2211 
2212   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2213   // which constitute a large proportion of the elements. In such cases we can
2214   // splat a vector with the dominant element and make up the shortfall with
2215   // INSERT_VECTOR_ELTs.
2216   // Note that this includes vectors of 2 elements by association. The
2217   // upper-most element is the "dominant" one, allowing us to use a splat to
2218   // "insert" the upper element, and an insert of the lower element at position
2219   // 0, which improves codegen.
2220   SDValue DominantValue;
2221   unsigned MostCommonCount = 0;
2222   DenseMap<SDValue, unsigned> ValueCounts;
2223   unsigned NumUndefElts =
2224       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2225 
2226   // Track the number of scalar loads we know we'd be inserting, estimated as
2227   // any non-zero floating-point constant. Other kinds of element are either
2228   // already in registers or are materialized on demand. The threshold at which
2229   // a vector load is more desirable than several scalar materializion and
2230   // vector-insertion instructions is not known.
2231   unsigned NumScalarLoads = 0;
2232 
2233   for (SDValue V : Op->op_values()) {
2234     if (V.isUndef())
2235       continue;
2236 
2237     ValueCounts.insert(std::make_pair(V, 0));
2238     unsigned &Count = ValueCounts[V];
2239 
2240     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2241       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2242 
2243     // Is this value dominant? In case of a tie, prefer the highest element as
2244     // it's cheaper to insert near the beginning of a vector than it is at the
2245     // end.
2246     if (++Count >= MostCommonCount) {
2247       DominantValue = V;
2248       MostCommonCount = Count;
2249     }
2250   }
2251 
2252   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2253   unsigned NumDefElts = NumElts - NumUndefElts;
2254   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2255 
2256   // Don't perform this optimization when optimizing for size, since
2257   // materializing elements and inserting them tends to cause code bloat.
2258   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2259       ((MostCommonCount > DominantValueCountThreshold) ||
2260        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2261     // Start by splatting the most common element.
2262     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2263 
2264     DenseSet<SDValue> Processed{DominantValue};
2265     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2266     for (const auto &OpIdx : enumerate(Op->ops())) {
2267       const SDValue &V = OpIdx.value();
2268       if (V.isUndef() || !Processed.insert(V).second)
2269         continue;
2270       if (ValueCounts[V] == 1) {
2271         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2272                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2273       } else {
2274         // Blend in all instances of this value using a VSELECT, using a
2275         // mask where each bit signals whether that element is the one
2276         // we're after.
2277         SmallVector<SDValue> Ops;
2278         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2279           return DAG.getConstant(V == V1, DL, XLenVT);
2280         });
2281         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2282                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2283                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2284       }
2285     }
2286 
2287     return Vec;
2288   }
2289 
2290   return SDValue();
2291 }
2292 
2293 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2294                                    SDValue Lo, SDValue Hi, SDValue VL,
2295                                    SelectionDAG &DAG) {
2296   if (!Passthru)
2297     Passthru = DAG.getUNDEF(VT);
2298   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2299     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2300     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2301     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2302     // node in order to try and match RVV vector/scalar instructions.
2303     if ((LoC >> 31) == HiC)
2304       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2305 
2306     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2307     // vmv.v.x whose EEW = 32 to lower it.
2308     auto *Const = dyn_cast<ConstantSDNode>(VL);
2309     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2310       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2311       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2312       // access the subtarget here now.
2313       auto InterVec = DAG.getNode(
2314           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2315                                   DAG.getRegister(RISCV::X0, MVT::i32));
2316       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2317     }
2318   }
2319 
2320   // Fall back to a stack store and stride x0 vector load.
2321   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2322                      Hi, VL);
2323 }
2324 
2325 // Called by type legalization to handle splat of i64 on RV32.
2326 // FIXME: We can optimize this when the type has sign or zero bits in one
2327 // of the halves.
2328 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2329                                    SDValue Scalar, SDValue VL,
2330                                    SelectionDAG &DAG) {
2331   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2332   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2333                            DAG.getConstant(0, DL, MVT::i32));
2334   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2335                            DAG.getConstant(1, DL, MVT::i32));
2336   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2337 }
2338 
2339 // This function lowers a splat of a scalar operand Splat with the vector
2340 // length VL. It ensures the final sequence is type legal, which is useful when
2341 // lowering a splat after type legalization.
2342 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2343                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2344                                 const RISCVSubtarget &Subtarget) {
2345   bool HasPassthru = Passthru && !Passthru.isUndef();
2346   if (!HasPassthru && !Passthru)
2347     Passthru = DAG.getUNDEF(VT);
2348   if (VT.isFloatingPoint()) {
2349     // If VL is 1, we could use vfmv.s.f.
2350     if (isOneConstant(VL))
2351       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2352     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2353   }
2354 
2355   MVT XLenVT = Subtarget.getXLenVT();
2356 
2357   // Simplest case is that the operand needs to be promoted to XLenVT.
2358   if (Scalar.getValueType().bitsLE(XLenVT)) {
2359     // If the operand is a constant, sign extend to increase our chances
2360     // of being able to use a .vi instruction. ANY_EXTEND would become a
2361     // a zero extend and the simm5 check in isel would fail.
2362     // FIXME: Should we ignore the upper bits in isel instead?
2363     unsigned ExtOpc =
2364         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2365     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2366     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2367     // If VL is 1 and the scalar value won't benefit from immediate, we could
2368     // use vmv.s.x.
2369     if (isOneConstant(VL) &&
2370         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2371       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2372     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2373   }
2374 
2375   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2376          "Unexpected scalar for splat lowering!");
2377 
2378   if (isOneConstant(VL) && isNullConstant(Scalar))
2379     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2380                        DAG.getConstant(0, DL, XLenVT), VL);
2381 
2382   // Otherwise use the more complicated splatting algorithm.
2383   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2384 }
2385 
2386 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2387                                 const RISCVSubtarget &Subtarget) {
2388   // We need to be able to widen elements to the next larger integer type.
2389   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2390     return false;
2391 
2392   int Size = Mask.size();
2393   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2394 
2395   int Srcs[] = {-1, -1};
2396   for (int i = 0; i != Size; ++i) {
2397     // Ignore undef elements.
2398     if (Mask[i] < 0)
2399       continue;
2400 
2401     // Is this an even or odd element.
2402     int Pol = i % 2;
2403 
2404     // Ensure we consistently use the same source for this element polarity.
2405     int Src = Mask[i] / Size;
2406     if (Srcs[Pol] < 0)
2407       Srcs[Pol] = Src;
2408     if (Srcs[Pol] != Src)
2409       return false;
2410 
2411     // Make sure the element within the source is appropriate for this element
2412     // in the destination.
2413     int Elt = Mask[i] % Size;
2414     if (Elt != i / 2)
2415       return false;
2416   }
2417 
2418   // We need to find a source for each polarity and they can't be the same.
2419   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2420     return false;
2421 
2422   // Swap the sources if the second source was in the even polarity.
2423   SwapSources = Srcs[0] > Srcs[1];
2424 
2425   return true;
2426 }
2427 
2428 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2429 /// and then extract the original number of elements from the rotated result.
2430 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2431 /// returned rotation amount is for a rotate right, where elements move from
2432 /// higher elements to lower elements. \p LoSrc indicates the first source
2433 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2434 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2435 /// 0 or 1 if a rotation is found.
2436 ///
2437 /// NOTE: We talk about rotate to the right which matches how bit shift and
2438 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2439 /// and the table below write vectors with the lowest elements on the left.
2440 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2441   int Size = Mask.size();
2442 
2443   // We need to detect various ways of spelling a rotation:
2444   //   [11, 12, 13, 14, 15,  0,  1,  2]
2445   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2446   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2447   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2448   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2449   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2450   int Rotation = 0;
2451   LoSrc = -1;
2452   HiSrc = -1;
2453   for (int i = 0; i != Size; ++i) {
2454     int M = Mask[i];
2455     if (M < 0)
2456       continue;
2457 
2458     // Determine where a rotate vector would have started.
2459     int StartIdx = i - (M % Size);
2460     // The identity rotation isn't interesting, stop.
2461     if (StartIdx == 0)
2462       return -1;
2463 
2464     // If we found the tail of a vector the rotation must be the missing
2465     // front. If we found the head of a vector, it must be how much of the
2466     // head.
2467     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2468 
2469     if (Rotation == 0)
2470       Rotation = CandidateRotation;
2471     else if (Rotation != CandidateRotation)
2472       // The rotations don't match, so we can't match this mask.
2473       return -1;
2474 
2475     // Compute which value this mask is pointing at.
2476     int MaskSrc = M < Size ? 0 : 1;
2477 
2478     // Compute which of the two target values this index should be assigned to.
2479     // This reflects whether the high elements are remaining or the low elemnts
2480     // are remaining.
2481     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2482 
2483     // Either set up this value if we've not encountered it before, or check
2484     // that it remains consistent.
2485     if (TargetSrc < 0)
2486       TargetSrc = MaskSrc;
2487     else if (TargetSrc != MaskSrc)
2488       // This may be a rotation, but it pulls from the inputs in some
2489       // unsupported interleaving.
2490       return -1;
2491   }
2492 
2493   // Check that we successfully analyzed the mask, and normalize the results.
2494   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2495   assert((LoSrc >= 0 || HiSrc >= 0) &&
2496          "Failed to find a rotated input vector!");
2497 
2498   return Rotation;
2499 }
2500 
2501 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2502                                    const RISCVSubtarget &Subtarget) {
2503   SDValue V1 = Op.getOperand(0);
2504   SDValue V2 = Op.getOperand(1);
2505   SDLoc DL(Op);
2506   MVT XLenVT = Subtarget.getXLenVT();
2507   MVT VT = Op.getSimpleValueType();
2508   unsigned NumElts = VT.getVectorNumElements();
2509   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2510 
2511   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2512 
2513   SDValue TrueMask, VL;
2514   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2515 
2516   if (SVN->isSplat()) {
2517     const int Lane = SVN->getSplatIndex();
2518     if (Lane >= 0) {
2519       MVT SVT = VT.getVectorElementType();
2520 
2521       // Turn splatted vector load into a strided load with an X0 stride.
2522       SDValue V = V1;
2523       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2524       // with undef.
2525       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2526       int Offset = Lane;
2527       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2528         int OpElements =
2529             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2530         V = V.getOperand(Offset / OpElements);
2531         Offset %= OpElements;
2532       }
2533 
2534       // We need to ensure the load isn't atomic or volatile.
2535       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2536         auto *Ld = cast<LoadSDNode>(V);
2537         Offset *= SVT.getStoreSize();
2538         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2539                                                    TypeSize::Fixed(Offset), DL);
2540 
2541         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2542         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2543           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2544           SDValue IntID =
2545               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2546           SDValue Ops[] = {Ld->getChain(),
2547                            IntID,
2548                            DAG.getUNDEF(ContainerVT),
2549                            NewAddr,
2550                            DAG.getRegister(RISCV::X0, XLenVT),
2551                            VL};
2552           SDValue NewLoad = DAG.getMemIntrinsicNode(
2553               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2554               DAG.getMachineFunction().getMachineMemOperand(
2555                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2556           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2557           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2558         }
2559 
2560         // Otherwise use a scalar load and splat. This will give the best
2561         // opportunity to fold a splat into the operation. ISel can turn it into
2562         // the x0 strided load if we aren't able to fold away the select.
2563         if (SVT.isFloatingPoint())
2564           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2565                           Ld->getPointerInfo().getWithOffset(Offset),
2566                           Ld->getOriginalAlign(),
2567                           Ld->getMemOperand()->getFlags());
2568         else
2569           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2570                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2571                              Ld->getOriginalAlign(),
2572                              Ld->getMemOperand()->getFlags());
2573         DAG.makeEquivalentMemoryOrdering(Ld, V);
2574 
2575         unsigned Opc =
2576             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2577         SDValue Splat =
2578             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2579         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2580       }
2581 
2582       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2583       assert(Lane < (int)NumElts && "Unexpected lane!");
2584       SDValue Gather = DAG.getNode(
2585           RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
2586           V1, DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2587       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2588     }
2589   }
2590 
2591   ArrayRef<int> Mask = SVN->getMask();
2592 
2593   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2594   // be undef which can be handled with a single SLIDEDOWN/UP.
2595   int LoSrc, HiSrc;
2596   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2597   if (Rotation > 0) {
2598     SDValue LoV, HiV;
2599     if (LoSrc >= 0) {
2600       LoV = LoSrc == 0 ? V1 : V2;
2601       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2602     }
2603     if (HiSrc >= 0) {
2604       HiV = HiSrc == 0 ? V1 : V2;
2605       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2606     }
2607 
2608     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2609     // to slide LoV up by (NumElts - Rotation).
2610     unsigned InvRotate = NumElts - Rotation;
2611 
2612     SDValue Res = DAG.getUNDEF(ContainerVT);
2613     if (HiV) {
2614       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2615       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2616       // causes multiple vsetvlis in some test cases such as lowering
2617       // reduce.mul
2618       SDValue DownVL = VL;
2619       if (LoV)
2620         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2621       Res =
2622           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2623                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2624     }
2625     if (LoV)
2626       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2627                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2628 
2629     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2630   }
2631 
2632   // Detect an interleave shuffle and lower to
2633   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2634   bool SwapSources;
2635   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2636     // Swap sources if needed.
2637     if (SwapSources)
2638       std::swap(V1, V2);
2639 
2640     // Extract the lower half of the vectors.
2641     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2642     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2643                      DAG.getConstant(0, DL, XLenVT));
2644     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2645                      DAG.getConstant(0, DL, XLenVT));
2646 
2647     // Double the element width and halve the number of elements in an int type.
2648     unsigned EltBits = VT.getScalarSizeInBits();
2649     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2650     MVT WideIntVT =
2651         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2652     // Convert this to a scalable vector. We need to base this on the
2653     // destination size to ensure there's always a type with a smaller LMUL.
2654     MVT WideIntContainerVT =
2655         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2656 
2657     // Convert sources to scalable vectors with the same element count as the
2658     // larger type.
2659     MVT HalfContainerVT = MVT::getVectorVT(
2660         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2661     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2662     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2663 
2664     // Cast sources to integer.
2665     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2666     MVT IntHalfVT =
2667         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2668     V1 = DAG.getBitcast(IntHalfVT, V1);
2669     V2 = DAG.getBitcast(IntHalfVT, V2);
2670 
2671     // Freeze V2 since we use it twice and we need to be sure that the add and
2672     // multiply see the same value.
2673     V2 = DAG.getFreeze(V2);
2674 
2675     // Recreate TrueMask using the widened type's element count.
2676     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2677 
2678     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2679     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2680                               V2, TrueMask, VL);
2681     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2682     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2683                                      DAG.getUNDEF(IntHalfVT),
2684                                      DAG.getAllOnesConstant(DL, XLenVT));
2685     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2686                                    V2, Multiplier, TrueMask, VL);
2687     // Add the new copies to our previous addition giving us 2^eltbits copies of
2688     // V2. This is equivalent to shifting V2 left by eltbits. This should
2689     // combine with the vwmulu.vv above to form vwmaccu.vv.
2690     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2691                       TrueMask, VL);
2692     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2693     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2694     // vector VT.
2695     ContainerVT =
2696         MVT::getVectorVT(VT.getVectorElementType(),
2697                          WideIntContainerVT.getVectorElementCount() * 2);
2698     Add = DAG.getBitcast(ContainerVT, Add);
2699     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2700   }
2701 
2702   // Detect shuffles which can be re-expressed as vector selects; these are
2703   // shuffles in which each element in the destination is taken from an element
2704   // at the corresponding index in either source vectors.
2705   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2706     int MaskIndex = MaskIdx.value();
2707     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2708   });
2709 
2710   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2711 
2712   SmallVector<SDValue> MaskVals;
2713   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2714   // merged with a second vrgather.
2715   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2716 
2717   // By default we preserve the original operand order, and use a mask to
2718   // select LHS as true and RHS as false. However, since RVV vector selects may
2719   // feature splats but only on the LHS, we may choose to invert our mask and
2720   // instead select between RHS and LHS.
2721   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2722   bool InvertMask = IsSelect == SwapOps;
2723 
2724   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2725   // half.
2726   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2727 
2728   // Now construct the mask that will be used by the vselect or blended
2729   // vrgather operation. For vrgathers, construct the appropriate indices into
2730   // each vector.
2731   for (int MaskIndex : Mask) {
2732     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2733     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2734     if (!IsSelect) {
2735       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2736       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2737                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2738                                      : DAG.getUNDEF(XLenVT));
2739       GatherIndicesRHS.push_back(
2740           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2741                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2742       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2743         ++LHSIndexCounts[MaskIndex];
2744       if (!IsLHSOrUndefIndex)
2745         ++RHSIndexCounts[MaskIndex - NumElts];
2746     }
2747   }
2748 
2749   if (SwapOps) {
2750     std::swap(V1, V2);
2751     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2752   }
2753 
2754   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2755   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2756   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2757 
2758   if (IsSelect)
2759     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2760 
2761   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2762     // On such a large vector we're unable to use i8 as the index type.
2763     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2764     // may involve vector splitting if we're already at LMUL=8, or our
2765     // user-supplied maximum fixed-length LMUL.
2766     return SDValue();
2767   }
2768 
2769   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2770   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2771   MVT IndexVT = VT.changeTypeToInteger();
2772   // Since we can't introduce illegal index types at this stage, use i16 and
2773   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2774   // than XLenVT.
2775   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2776     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2777     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2778   }
2779 
2780   MVT IndexContainerVT =
2781       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2782 
2783   SDValue Gather;
2784   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2785   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2786   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2787     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2788                               Subtarget);
2789   } else {
2790     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2791     // If only one index is used, we can use a "splat" vrgather.
2792     // TODO: We can splat the most-common index and fix-up any stragglers, if
2793     // that's beneficial.
2794     if (LHSIndexCounts.size() == 1) {
2795       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2796       Gather = DAG.getNode(
2797           GatherVXOpc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V1,
2798           DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2799     } else {
2800       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2801       LHSIndices =
2802           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2803 
2804       Gather =
2805           DAG.getNode(GatherVVOpc, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
2806                       V1, LHSIndices, TrueMask, VL);
2807     }
2808   }
2809 
2810   // If a second vector operand is used by this shuffle, blend it in with an
2811   // additional vrgather.
2812   if (!V2.isUndef()) {
2813     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2814 
2815     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2816     SelectMask =
2817         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2818 
2819     // If only one index is used, we can use a "splat" vrgather.
2820     // TODO: We can splat the most-common index and fix-up any stragglers, if
2821     // that's beneficial.
2822     if (RHSIndexCounts.size() == 1) {
2823       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2824       Gather =
2825           DAG.getNode(GatherVXOpc, DL, ContainerVT, Gather, V2,
2826                       DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, VL);
2827     } else {
2828       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2829       RHSIndices =
2830           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2831       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, Gather, V2, RHSIndices,
2832                            SelectMask, VL);
2833     }
2834   }
2835 
2836   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2837 }
2838 
2839 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2840   // Support splats for any type. These should type legalize well.
2841   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2842     return true;
2843 
2844   // Only support legal VTs for other shuffles for now.
2845   if (!isTypeLegal(VT))
2846     return false;
2847 
2848   MVT SVT = VT.getSimpleVT();
2849 
2850   bool SwapSources;
2851   int LoSrc, HiSrc;
2852   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2853          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2854 }
2855 
2856 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2857 // the exponent.
2858 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2859   MVT VT = Op.getSimpleValueType();
2860   unsigned EltSize = VT.getScalarSizeInBits();
2861   SDValue Src = Op.getOperand(0);
2862   SDLoc DL(Op);
2863 
2864   // We need a FP type that can represent the value.
2865   // TODO: Use f16 for i8 when possible?
2866   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2867   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2868 
2869   // Legal types should have been checked in the RISCVTargetLowering
2870   // constructor.
2871   // TODO: Splitting may make sense in some cases.
2872   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2873          "Expected legal float type!");
2874 
2875   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2876   // The trailing zero count is equal to log2 of this single bit value.
2877   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2878     SDValue Neg =
2879         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2880     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2881   }
2882 
2883   // We have a legal FP type, convert to it.
2884   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2885   // Bitcast to integer and shift the exponent to the LSB.
2886   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2887   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2888   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2889   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2890                               DAG.getConstant(ShiftAmt, DL, IntVT));
2891   // Truncate back to original type to allow vnsrl.
2892   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2893   // The exponent contains log2 of the value in biased form.
2894   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2895 
2896   // For trailing zeros, we just need to subtract the bias.
2897   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2898     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2899                        DAG.getConstant(ExponentBias, DL, VT));
2900 
2901   // For leading zeros, we need to remove the bias and convert from log2 to
2902   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2903   unsigned Adjust = ExponentBias + (EltSize - 1);
2904   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2905 }
2906 
2907 // While RVV has alignment restrictions, we should always be able to load as a
2908 // legal equivalently-sized byte-typed vector instead. This method is
2909 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2910 // the load is already correctly-aligned, it returns SDValue().
2911 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2912                                                     SelectionDAG &DAG) const {
2913   auto *Load = cast<LoadSDNode>(Op);
2914   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2915 
2916   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2917                                      Load->getMemoryVT(),
2918                                      *Load->getMemOperand()))
2919     return SDValue();
2920 
2921   SDLoc DL(Op);
2922   MVT VT = Op.getSimpleValueType();
2923   unsigned EltSizeBits = VT.getScalarSizeInBits();
2924   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2925          "Unexpected unaligned RVV load type");
2926   MVT NewVT =
2927       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2928   assert(NewVT.isValid() &&
2929          "Expecting equally-sized RVV vector types to be legal");
2930   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2931                           Load->getPointerInfo(), Load->getOriginalAlign(),
2932                           Load->getMemOperand()->getFlags());
2933   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2934 }
2935 
2936 // While RVV has alignment restrictions, we should always be able to store as a
2937 // legal equivalently-sized byte-typed vector instead. This method is
2938 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2939 // returns SDValue() if the store is already correctly aligned.
2940 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2941                                                      SelectionDAG &DAG) const {
2942   auto *Store = cast<StoreSDNode>(Op);
2943   assert(Store && Store->getValue().getValueType().isVector() &&
2944          "Expected vector store");
2945 
2946   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2947                                      Store->getMemoryVT(),
2948                                      *Store->getMemOperand()))
2949     return SDValue();
2950 
2951   SDLoc DL(Op);
2952   SDValue StoredVal = Store->getValue();
2953   MVT VT = StoredVal.getSimpleValueType();
2954   unsigned EltSizeBits = VT.getScalarSizeInBits();
2955   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2956          "Unexpected unaligned RVV store type");
2957   MVT NewVT =
2958       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2959   assert(NewVT.isValid() &&
2960          "Expecting equally-sized RVV vector types to be legal");
2961   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2962   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2963                       Store->getPointerInfo(), Store->getOriginalAlign(),
2964                       Store->getMemOperand()->getFlags());
2965 }
2966 
2967 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
2968                              const RISCVSubtarget &Subtarget) {
2969   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
2970 
2971   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
2972 
2973   // All simm32 constants should be handled by isel.
2974   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
2975   // this check redundant, but small immediates are common so this check
2976   // should have better compile time.
2977   if (isInt<32>(Imm))
2978     return Op;
2979 
2980   // We only need to cost the immediate, if constant pool lowering is enabled.
2981   if (!Subtarget.useConstantPoolForLargeInts())
2982     return Op;
2983 
2984   RISCVMatInt::InstSeq Seq =
2985       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
2986   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
2987     return Op;
2988 
2989   // Expand to a constant pool using the default expansion code.
2990   return SDValue();
2991 }
2992 
2993 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2994                                             SelectionDAG &DAG) const {
2995   switch (Op.getOpcode()) {
2996   default:
2997     report_fatal_error("unimplemented operand");
2998   case ISD::GlobalAddress:
2999     return lowerGlobalAddress(Op, DAG);
3000   case ISD::BlockAddress:
3001     return lowerBlockAddress(Op, DAG);
3002   case ISD::ConstantPool:
3003     return lowerConstantPool(Op, DAG);
3004   case ISD::JumpTable:
3005     return lowerJumpTable(Op, DAG);
3006   case ISD::GlobalTLSAddress:
3007     return lowerGlobalTLSAddress(Op, DAG);
3008   case ISD::Constant:
3009     return lowerConstant(Op, DAG, Subtarget);
3010   case ISD::SELECT:
3011     return lowerSELECT(Op, DAG);
3012   case ISD::BRCOND:
3013     return lowerBRCOND(Op, DAG);
3014   case ISD::VASTART:
3015     return lowerVASTART(Op, DAG);
3016   case ISD::FRAMEADDR:
3017     return lowerFRAMEADDR(Op, DAG);
3018   case ISD::RETURNADDR:
3019     return lowerRETURNADDR(Op, DAG);
3020   case ISD::SHL_PARTS:
3021     return lowerShiftLeftParts(Op, DAG);
3022   case ISD::SRA_PARTS:
3023     return lowerShiftRightParts(Op, DAG, true);
3024   case ISD::SRL_PARTS:
3025     return lowerShiftRightParts(Op, DAG, false);
3026   case ISD::BITCAST: {
3027     SDLoc DL(Op);
3028     EVT VT = Op.getValueType();
3029     SDValue Op0 = Op.getOperand(0);
3030     EVT Op0VT = Op0.getValueType();
3031     MVT XLenVT = Subtarget.getXLenVT();
3032     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3033       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3034       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3035       return FPConv;
3036     }
3037     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3038         Subtarget.hasStdExtF()) {
3039       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3040       SDValue FPConv =
3041           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3042       return FPConv;
3043     }
3044 
3045     // Consider other scalar<->scalar casts as legal if the types are legal.
3046     // Otherwise expand them.
3047     if (!VT.isVector() && !Op0VT.isVector()) {
3048       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3049         return Op;
3050       return SDValue();
3051     }
3052 
3053     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3054            "Unexpected types");
3055 
3056     if (VT.isFixedLengthVector()) {
3057       // We can handle fixed length vector bitcasts with a simple replacement
3058       // in isel.
3059       if (Op0VT.isFixedLengthVector())
3060         return Op;
3061       // When bitcasting from scalar to fixed-length vector, insert the scalar
3062       // into a one-element vector of the result type, and perform a vector
3063       // bitcast.
3064       if (!Op0VT.isVector()) {
3065         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3066         if (!isTypeLegal(BVT))
3067           return SDValue();
3068         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3069                                               DAG.getUNDEF(BVT), Op0,
3070                                               DAG.getConstant(0, DL, XLenVT)));
3071       }
3072       return SDValue();
3073     }
3074     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3075     // thus: bitcast the vector to a one-element vector type whose element type
3076     // is the same as the result type, and extract the first element.
3077     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3078       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3079       if (!isTypeLegal(BVT))
3080         return SDValue();
3081       SDValue BVec = DAG.getBitcast(BVT, Op0);
3082       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3083                          DAG.getConstant(0, DL, XLenVT));
3084     }
3085     return SDValue();
3086   }
3087   case ISD::INTRINSIC_WO_CHAIN:
3088     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3089   case ISD::INTRINSIC_W_CHAIN:
3090     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3091   case ISD::INTRINSIC_VOID:
3092     return LowerINTRINSIC_VOID(Op, DAG);
3093   case ISD::BSWAP:
3094   case ISD::BITREVERSE: {
3095     MVT VT = Op.getSimpleValueType();
3096     SDLoc DL(Op);
3097     if (Subtarget.hasStdExtZbp()) {
3098       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3099       // Start with the maximum immediate value which is the bitwidth - 1.
3100       unsigned Imm = VT.getSizeInBits() - 1;
3101       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3102       if (Op.getOpcode() == ISD::BSWAP)
3103         Imm &= ~0x7U;
3104       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3105                          DAG.getConstant(Imm, DL, VT));
3106     }
3107     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3108     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3109     // Expand bitreverse to a bswap(rev8) followed by brev8.
3110     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3111     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3112     // as brev8 by an isel pattern.
3113     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3114                        DAG.getConstant(7, DL, VT));
3115   }
3116   case ISD::FSHL:
3117   case ISD::FSHR: {
3118     MVT VT = Op.getSimpleValueType();
3119     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3120     SDLoc DL(Op);
3121     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3122     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3123     // accidentally setting the extra bit.
3124     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3125     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3126                                 DAG.getConstant(ShAmtWidth, DL, VT));
3127     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3128     // instruction use different orders. fshl will return its first operand for
3129     // shift of zero, fshr will return its second operand. fsl and fsr both
3130     // return rs1 so the ISD nodes need to have different operand orders.
3131     // Shift amount is in rs2.
3132     SDValue Op0 = Op.getOperand(0);
3133     SDValue Op1 = Op.getOperand(1);
3134     unsigned Opc = RISCVISD::FSL;
3135     if (Op.getOpcode() == ISD::FSHR) {
3136       std::swap(Op0, Op1);
3137       Opc = RISCVISD::FSR;
3138     }
3139     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3140   }
3141   case ISD::TRUNCATE:
3142     // Only custom-lower vector truncates
3143     if (!Op.getSimpleValueType().isVector())
3144       return Op;
3145     return lowerVectorTruncLike(Op, DAG);
3146   case ISD::ANY_EXTEND:
3147   case ISD::ZERO_EXTEND:
3148     if (Op.getOperand(0).getValueType().isVector() &&
3149         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3150       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3151     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3152   case ISD::SIGN_EXTEND:
3153     if (Op.getOperand(0).getValueType().isVector() &&
3154         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3155       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3156     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3157   case ISD::SPLAT_VECTOR_PARTS:
3158     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3159   case ISD::INSERT_VECTOR_ELT:
3160     return lowerINSERT_VECTOR_ELT(Op, DAG);
3161   case ISD::EXTRACT_VECTOR_ELT:
3162     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3163   case ISD::VSCALE: {
3164     MVT VT = Op.getSimpleValueType();
3165     SDLoc DL(Op);
3166     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3167     // We define our scalable vector types for lmul=1 to use a 64 bit known
3168     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3169     // vscale as VLENB / 8.
3170     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3171     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3172       report_fatal_error("Support for VLEN==32 is incomplete.");
3173     // We assume VLENB is a multiple of 8. We manually choose the best shift
3174     // here because SimplifyDemandedBits isn't always able to simplify it.
3175     uint64_t Val = Op.getConstantOperandVal(0);
3176     if (isPowerOf2_64(Val)) {
3177       uint64_t Log2 = Log2_64(Val);
3178       if (Log2 < 3)
3179         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3180                            DAG.getConstant(3 - Log2, DL, VT));
3181       if (Log2 > 3)
3182         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3183                            DAG.getConstant(Log2 - 3, DL, VT));
3184       return VLENB;
3185     }
3186     // If the multiplier is a multiple of 8, scale it down to avoid needing
3187     // to shift the VLENB value.
3188     if ((Val % 8) == 0)
3189       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3190                          DAG.getConstant(Val / 8, DL, VT));
3191 
3192     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3193                                  DAG.getConstant(3, DL, VT));
3194     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3195   }
3196   case ISD::FPOWI: {
3197     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3198     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3199     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3200         Op.getOperand(1).getValueType() == MVT::i32) {
3201       SDLoc DL(Op);
3202       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3203       SDValue Powi =
3204           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3205       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3206                          DAG.getIntPtrConstant(0, DL));
3207     }
3208     return SDValue();
3209   }
3210   case ISD::FP_EXTEND:
3211   case ISD::FP_ROUND:
3212     if (!Op.getValueType().isVector())
3213       return Op;
3214     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3215   case ISD::FP_TO_SINT:
3216   case ISD::FP_TO_UINT:
3217   case ISD::SINT_TO_FP:
3218   case ISD::UINT_TO_FP: {
3219     // RVV can only do fp<->int conversions to types half/double the size as
3220     // the source. We custom-lower any conversions that do two hops into
3221     // sequences.
3222     MVT VT = Op.getSimpleValueType();
3223     if (!VT.isVector())
3224       return Op;
3225     SDLoc DL(Op);
3226     SDValue Src = Op.getOperand(0);
3227     MVT EltVT = VT.getVectorElementType();
3228     MVT SrcVT = Src.getSimpleValueType();
3229     MVT SrcEltVT = SrcVT.getVectorElementType();
3230     unsigned EltSize = EltVT.getSizeInBits();
3231     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3232     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3233            "Unexpected vector element types");
3234 
3235     bool IsInt2FP = SrcEltVT.isInteger();
3236     // Widening conversions
3237     if (EltSize > (2 * SrcEltSize)) {
3238       if (IsInt2FP) {
3239         // Do a regular integer sign/zero extension then convert to float.
3240         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3241                                       VT.getVectorElementCount());
3242         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3243                                  ? ISD::ZERO_EXTEND
3244                                  : ISD::SIGN_EXTEND;
3245         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3246         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3247       }
3248       // FP2Int
3249       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3250       // Do one doubling fp_extend then complete the operation by converting
3251       // to int.
3252       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3253       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3254       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3255     }
3256 
3257     // Narrowing conversions
3258     if (SrcEltSize > (2 * EltSize)) {
3259       if (IsInt2FP) {
3260         // One narrowing int_to_fp, then an fp_round.
3261         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3262         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3263         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3264         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3265       }
3266       // FP2Int
3267       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3268       // representable by the integer, the result is poison.
3269       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3270                                     VT.getVectorElementCount());
3271       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3272       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3273     }
3274 
3275     // Scalable vectors can exit here. Patterns will handle equally-sized
3276     // conversions halving/doubling ones.
3277     if (!VT.isFixedLengthVector())
3278       return Op;
3279 
3280     // For fixed-length vectors we lower to a custom "VL" node.
3281     unsigned RVVOpc = 0;
3282     switch (Op.getOpcode()) {
3283     default:
3284       llvm_unreachable("Impossible opcode");
3285     case ISD::FP_TO_SINT:
3286       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3287       break;
3288     case ISD::FP_TO_UINT:
3289       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3290       break;
3291     case ISD::SINT_TO_FP:
3292       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3293       break;
3294     case ISD::UINT_TO_FP:
3295       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3296       break;
3297     }
3298 
3299     MVT ContainerVT, SrcContainerVT;
3300     // Derive the reference container type from the larger vector type.
3301     if (SrcEltSize > EltSize) {
3302       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3303       ContainerVT =
3304           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3305     } else {
3306       ContainerVT = getContainerForFixedLengthVector(VT);
3307       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3308     }
3309 
3310     SDValue Mask, VL;
3311     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3312 
3313     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3314     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3315     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3316   }
3317   case ISD::FP_TO_SINT_SAT:
3318   case ISD::FP_TO_UINT_SAT:
3319     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3320   case ISD::FTRUNC:
3321   case ISD::FCEIL:
3322   case ISD::FFLOOR:
3323     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3324   case ISD::FROUND:
3325     return lowerFROUND(Op, DAG);
3326   case ISD::VECREDUCE_ADD:
3327   case ISD::VECREDUCE_UMAX:
3328   case ISD::VECREDUCE_SMAX:
3329   case ISD::VECREDUCE_UMIN:
3330   case ISD::VECREDUCE_SMIN:
3331     return lowerVECREDUCE(Op, DAG);
3332   case ISD::VECREDUCE_AND:
3333   case ISD::VECREDUCE_OR:
3334   case ISD::VECREDUCE_XOR:
3335     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3336       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3337     return lowerVECREDUCE(Op, DAG);
3338   case ISD::VECREDUCE_FADD:
3339   case ISD::VECREDUCE_SEQ_FADD:
3340   case ISD::VECREDUCE_FMIN:
3341   case ISD::VECREDUCE_FMAX:
3342     return lowerFPVECREDUCE(Op, DAG);
3343   case ISD::VP_REDUCE_ADD:
3344   case ISD::VP_REDUCE_UMAX:
3345   case ISD::VP_REDUCE_SMAX:
3346   case ISD::VP_REDUCE_UMIN:
3347   case ISD::VP_REDUCE_SMIN:
3348   case ISD::VP_REDUCE_FADD:
3349   case ISD::VP_REDUCE_SEQ_FADD:
3350   case ISD::VP_REDUCE_FMIN:
3351   case ISD::VP_REDUCE_FMAX:
3352     return lowerVPREDUCE(Op, DAG);
3353   case ISD::VP_REDUCE_AND:
3354   case ISD::VP_REDUCE_OR:
3355   case ISD::VP_REDUCE_XOR:
3356     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3357       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3358     return lowerVPREDUCE(Op, DAG);
3359   case ISD::INSERT_SUBVECTOR:
3360     return lowerINSERT_SUBVECTOR(Op, DAG);
3361   case ISD::EXTRACT_SUBVECTOR:
3362     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3363   case ISD::STEP_VECTOR:
3364     return lowerSTEP_VECTOR(Op, DAG);
3365   case ISD::VECTOR_REVERSE:
3366     return lowerVECTOR_REVERSE(Op, DAG);
3367   case ISD::VECTOR_SPLICE:
3368     return lowerVECTOR_SPLICE(Op, DAG);
3369   case ISD::BUILD_VECTOR:
3370     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3371   case ISD::SPLAT_VECTOR:
3372     if (Op.getValueType().getVectorElementType() == MVT::i1)
3373       return lowerVectorMaskSplat(Op, DAG);
3374     return SDValue();
3375   case ISD::VECTOR_SHUFFLE:
3376     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3377   case ISD::CONCAT_VECTORS: {
3378     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3379     // better than going through the stack, as the default expansion does.
3380     SDLoc DL(Op);
3381     MVT VT = Op.getSimpleValueType();
3382     unsigned NumOpElts =
3383         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3384     SDValue Vec = DAG.getUNDEF(VT);
3385     for (const auto &OpIdx : enumerate(Op->ops())) {
3386       SDValue SubVec = OpIdx.value();
3387       // Don't insert undef subvectors.
3388       if (SubVec.isUndef())
3389         continue;
3390       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3391                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3392     }
3393     return Vec;
3394   }
3395   case ISD::LOAD:
3396     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3397       return V;
3398     if (Op.getValueType().isFixedLengthVector())
3399       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3400     return Op;
3401   case ISD::STORE:
3402     if (auto V = expandUnalignedRVVStore(Op, DAG))
3403       return V;
3404     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3405       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3406     return Op;
3407   case ISD::MLOAD:
3408   case ISD::VP_LOAD:
3409     return lowerMaskedLoad(Op, DAG);
3410   case ISD::MSTORE:
3411   case ISD::VP_STORE:
3412     return lowerMaskedStore(Op, DAG);
3413   case ISD::SETCC:
3414     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3415   case ISD::ADD:
3416     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3417   case ISD::SUB:
3418     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3419   case ISD::MUL:
3420     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3421   case ISD::MULHS:
3422     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3423   case ISD::MULHU:
3424     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3425   case ISD::AND:
3426     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3427                                               RISCVISD::AND_VL);
3428   case ISD::OR:
3429     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3430                                               RISCVISD::OR_VL);
3431   case ISD::XOR:
3432     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3433                                               RISCVISD::XOR_VL);
3434   case ISD::SDIV:
3435     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3436   case ISD::SREM:
3437     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3438   case ISD::UDIV:
3439     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3440   case ISD::UREM:
3441     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3442   case ISD::SHL:
3443   case ISD::SRA:
3444   case ISD::SRL:
3445     if (Op.getSimpleValueType().isFixedLengthVector())
3446       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3447     // This can be called for an i32 shift amount that needs to be promoted.
3448     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3449            "Unexpected custom legalisation");
3450     return SDValue();
3451   case ISD::SADDSAT:
3452     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3453   case ISD::UADDSAT:
3454     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3455   case ISD::SSUBSAT:
3456     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3457   case ISD::USUBSAT:
3458     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3459   case ISD::FADD:
3460     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3461   case ISD::FSUB:
3462     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3463   case ISD::FMUL:
3464     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3465   case ISD::FDIV:
3466     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3467   case ISD::FNEG:
3468     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3469   case ISD::FABS:
3470     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3471   case ISD::FSQRT:
3472     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3473   case ISD::FMA:
3474     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3475   case ISD::SMIN:
3476     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3477   case ISD::SMAX:
3478     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3479   case ISD::UMIN:
3480     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3481   case ISD::UMAX:
3482     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3483   case ISD::FMINNUM:
3484     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3485   case ISD::FMAXNUM:
3486     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3487   case ISD::ABS:
3488     return lowerABS(Op, DAG);
3489   case ISD::CTLZ_ZERO_UNDEF:
3490   case ISD::CTTZ_ZERO_UNDEF:
3491     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3492   case ISD::VSELECT:
3493     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3494   case ISD::FCOPYSIGN:
3495     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3496   case ISD::MGATHER:
3497   case ISD::VP_GATHER:
3498     return lowerMaskedGather(Op, DAG);
3499   case ISD::MSCATTER:
3500   case ISD::VP_SCATTER:
3501     return lowerMaskedScatter(Op, DAG);
3502   case ISD::FLT_ROUNDS_:
3503     return lowerGET_ROUNDING(Op, DAG);
3504   case ISD::SET_ROUNDING:
3505     return lowerSET_ROUNDING(Op, DAG);
3506   case ISD::EH_DWARF_CFA:
3507     return lowerEH_DWARF_CFA(Op, DAG);
3508   case ISD::VP_SELECT:
3509     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3510   case ISD::VP_MERGE:
3511     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3512   case ISD::VP_ADD:
3513     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3514   case ISD::VP_SUB:
3515     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3516   case ISD::VP_MUL:
3517     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3518   case ISD::VP_SDIV:
3519     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3520   case ISD::VP_UDIV:
3521     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3522   case ISD::VP_SREM:
3523     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3524   case ISD::VP_UREM:
3525     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3526   case ISD::VP_AND:
3527     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3528   case ISD::VP_OR:
3529     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3530   case ISD::VP_XOR:
3531     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3532   case ISD::VP_ASHR:
3533     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3534   case ISD::VP_LSHR:
3535     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3536   case ISD::VP_SHL:
3537     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3538   case ISD::VP_FADD:
3539     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3540   case ISD::VP_FSUB:
3541     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3542   case ISD::VP_FMUL:
3543     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3544   case ISD::VP_FDIV:
3545     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3546   case ISD::VP_FNEG:
3547     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3548   case ISD::VP_FMA:
3549     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3550   case ISD::VP_SIGN_EXTEND:
3551   case ISD::VP_ZERO_EXTEND:
3552     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3553       return lowerVPExtMaskOp(Op, DAG);
3554     return lowerVPOp(Op, DAG,
3555                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3556                          ? RISCVISD::VSEXT_VL
3557                          : RISCVISD::VZEXT_VL);
3558   case ISD::VP_TRUNCATE:
3559     return lowerVectorTruncLike(Op, DAG);
3560   case ISD::VP_FP_EXTEND:
3561   case ISD::VP_FP_ROUND:
3562     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3563   case ISD::VP_FPTOSI:
3564     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3565   case ISD::VP_FPTOUI:
3566     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3567   case ISD::VP_SITOFP:
3568     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3569   case ISD::VP_UITOFP:
3570     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3571   case ISD::VP_SETCC:
3572     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3573       return lowerVPSetCCMaskOp(Op, DAG);
3574     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3575   }
3576 }
3577 
3578 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3579                              SelectionDAG &DAG, unsigned Flags) {
3580   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3581 }
3582 
3583 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3584                              SelectionDAG &DAG, unsigned Flags) {
3585   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3586                                    Flags);
3587 }
3588 
3589 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3590                              SelectionDAG &DAG, unsigned Flags) {
3591   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3592                                    N->getOffset(), Flags);
3593 }
3594 
3595 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3596                              SelectionDAG &DAG, unsigned Flags) {
3597   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3598 }
3599 
3600 template <class NodeTy>
3601 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3602                                      bool IsLocal) const {
3603   SDLoc DL(N);
3604   EVT Ty = getPointerTy(DAG.getDataLayout());
3605 
3606   if (isPositionIndependent()) {
3607     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3608     if (IsLocal)
3609       // Use PC-relative addressing to access the symbol. This generates the
3610       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3611       // %pcrel_lo(auipc)).
3612       return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3613 
3614     // Use PC-relative addressing to access the GOT for this symbol, then load
3615     // the address from the GOT. This generates the pattern (PseudoLA sym),
3616     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3617     SDValue Load =
3618         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3619     MachineFunction &MF = DAG.getMachineFunction();
3620     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3621         MachinePointerInfo::getGOT(MF),
3622         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3623             MachineMemOperand::MOInvariant,
3624         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3625     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3626     return Load;
3627   }
3628 
3629   switch (getTargetMachine().getCodeModel()) {
3630   default:
3631     report_fatal_error("Unsupported code model for lowering");
3632   case CodeModel::Small: {
3633     // Generate a sequence for accessing addresses within the first 2 GiB of
3634     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3635     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3636     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3637     SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3638     return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
3639   }
3640   case CodeModel::Medium: {
3641     // Generate a sequence for accessing addresses within any 2GiB range within
3642     // the address space. This generates the pattern (PseudoLLA sym), which
3643     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3644     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3645     return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3646   }
3647   }
3648 }
3649 
3650 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3651                                                 SelectionDAG &DAG) const {
3652   SDLoc DL(Op);
3653   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3654   assert(N->getOffset() == 0 && "unexpected offset in global node");
3655 
3656   const GlobalValue *GV = N->getGlobal();
3657   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3658   return getAddr(N, DAG, IsLocal);
3659 }
3660 
3661 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3662                                                SelectionDAG &DAG) const {
3663   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3664 
3665   return getAddr(N, DAG);
3666 }
3667 
3668 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3669                                                SelectionDAG &DAG) const {
3670   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3671 
3672   return getAddr(N, DAG);
3673 }
3674 
3675 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3676                                             SelectionDAG &DAG) const {
3677   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3678 
3679   return getAddr(N, DAG);
3680 }
3681 
3682 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3683                                               SelectionDAG &DAG,
3684                                               bool UseGOT) const {
3685   SDLoc DL(N);
3686   EVT Ty = getPointerTy(DAG.getDataLayout());
3687   const GlobalValue *GV = N->getGlobal();
3688   MVT XLenVT = Subtarget.getXLenVT();
3689 
3690   if (UseGOT) {
3691     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3692     // load the address from the GOT and add the thread pointer. This generates
3693     // the pattern (PseudoLA_TLS_IE sym), which expands to
3694     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3695     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3696     SDValue Load =
3697         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3698     MachineFunction &MF = DAG.getMachineFunction();
3699     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3700         MachinePointerInfo::getGOT(MF),
3701         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3702             MachineMemOperand::MOInvariant,
3703         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3704     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3705 
3706     // Add the thread pointer.
3707     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3708     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3709   }
3710 
3711   // Generate a sequence for accessing the address relative to the thread
3712   // pointer, with the appropriate adjustment for the thread pointer offset.
3713   // This generates the pattern
3714   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3715   SDValue AddrHi =
3716       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3717   SDValue AddrAdd =
3718       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3719   SDValue AddrLo =
3720       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3721 
3722   SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3723   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3724   SDValue MNAdd =
3725       DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
3726   return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
3727 }
3728 
3729 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3730                                                SelectionDAG &DAG) const {
3731   SDLoc DL(N);
3732   EVT Ty = getPointerTy(DAG.getDataLayout());
3733   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3734   const GlobalValue *GV = N->getGlobal();
3735 
3736   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3737   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3738   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3739   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3740   SDValue Load =
3741       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3742 
3743   // Prepare argument list to generate call.
3744   ArgListTy Args;
3745   ArgListEntry Entry;
3746   Entry.Node = Load;
3747   Entry.Ty = CallTy;
3748   Args.push_back(Entry);
3749 
3750   // Setup call to __tls_get_addr.
3751   TargetLowering::CallLoweringInfo CLI(DAG);
3752   CLI.setDebugLoc(DL)
3753       .setChain(DAG.getEntryNode())
3754       .setLibCallee(CallingConv::C, CallTy,
3755                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3756                     std::move(Args));
3757 
3758   return LowerCallTo(CLI).first;
3759 }
3760 
3761 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3762                                                    SelectionDAG &DAG) const {
3763   SDLoc DL(Op);
3764   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3765   assert(N->getOffset() == 0 && "unexpected offset in global node");
3766 
3767   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3768 
3769   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3770       CallingConv::GHC)
3771     report_fatal_error("In GHC calling convention TLS is not supported");
3772 
3773   SDValue Addr;
3774   switch (Model) {
3775   case TLSModel::LocalExec:
3776     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3777     break;
3778   case TLSModel::InitialExec:
3779     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3780     break;
3781   case TLSModel::LocalDynamic:
3782   case TLSModel::GeneralDynamic:
3783     Addr = getDynamicTLSAddr(N, DAG);
3784     break;
3785   }
3786 
3787   return Addr;
3788 }
3789 
3790 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3791   SDValue CondV = Op.getOperand(0);
3792   SDValue TrueV = Op.getOperand(1);
3793   SDValue FalseV = Op.getOperand(2);
3794   SDLoc DL(Op);
3795   MVT VT = Op.getSimpleValueType();
3796   MVT XLenVT = Subtarget.getXLenVT();
3797 
3798   // Lower vector SELECTs to VSELECTs by splatting the condition.
3799   if (VT.isVector()) {
3800     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3801     SDValue CondSplat = VT.isScalableVector()
3802                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3803                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3804     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3805   }
3806 
3807   // If the result type is XLenVT and CondV is the output of a SETCC node
3808   // which also operated on XLenVT inputs, then merge the SETCC node into the
3809   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3810   // compare+branch instructions. i.e.:
3811   // (select (setcc lhs, rhs, cc), truev, falsev)
3812   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3813   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3814       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3815     SDValue LHS = CondV.getOperand(0);
3816     SDValue RHS = CondV.getOperand(1);
3817     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3818     ISD::CondCode CCVal = CC->get();
3819 
3820     // Special case for a select of 2 constants that have a diffence of 1.
3821     // Normally this is done by DAGCombine, but if the select is introduced by
3822     // type legalization or op legalization, we miss it. Restricting to SETLT
3823     // case for now because that is what signed saturating add/sub need.
3824     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3825     // but we would probably want to swap the true/false values if the condition
3826     // is SETGE/SETLE to avoid an XORI.
3827     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3828         CCVal == ISD::SETLT) {
3829       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3830       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3831       if (TrueVal - 1 == FalseVal)
3832         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3833       if (TrueVal + 1 == FalseVal)
3834         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3835     }
3836 
3837     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3838 
3839     SDValue TargetCC = DAG.getCondCode(CCVal);
3840     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3841     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3842   }
3843 
3844   // Otherwise:
3845   // (select condv, truev, falsev)
3846   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3847   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3848   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3849 
3850   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3851 
3852   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3853 }
3854 
3855 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3856   SDValue CondV = Op.getOperand(1);
3857   SDLoc DL(Op);
3858   MVT XLenVT = Subtarget.getXLenVT();
3859 
3860   if (CondV.getOpcode() == ISD::SETCC &&
3861       CondV.getOperand(0).getValueType() == XLenVT) {
3862     SDValue LHS = CondV.getOperand(0);
3863     SDValue RHS = CondV.getOperand(1);
3864     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3865 
3866     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3867 
3868     SDValue TargetCC = DAG.getCondCode(CCVal);
3869     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3870                        LHS, RHS, TargetCC, Op.getOperand(2));
3871   }
3872 
3873   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3874                      CondV, DAG.getConstant(0, DL, XLenVT),
3875                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3876 }
3877 
3878 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3879   MachineFunction &MF = DAG.getMachineFunction();
3880   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3881 
3882   SDLoc DL(Op);
3883   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3884                                  getPointerTy(MF.getDataLayout()));
3885 
3886   // vastart just stores the address of the VarArgsFrameIndex slot into the
3887   // memory location argument.
3888   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3889   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3890                       MachinePointerInfo(SV));
3891 }
3892 
3893 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3894                                             SelectionDAG &DAG) const {
3895   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3896   MachineFunction &MF = DAG.getMachineFunction();
3897   MachineFrameInfo &MFI = MF.getFrameInfo();
3898   MFI.setFrameAddressIsTaken(true);
3899   Register FrameReg = RI.getFrameRegister(MF);
3900   int XLenInBytes = Subtarget.getXLen() / 8;
3901 
3902   EVT VT = Op.getValueType();
3903   SDLoc DL(Op);
3904   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3905   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3906   while (Depth--) {
3907     int Offset = -(XLenInBytes * 2);
3908     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3909                               DAG.getIntPtrConstant(Offset, DL));
3910     FrameAddr =
3911         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3912   }
3913   return FrameAddr;
3914 }
3915 
3916 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3917                                              SelectionDAG &DAG) const {
3918   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3919   MachineFunction &MF = DAG.getMachineFunction();
3920   MachineFrameInfo &MFI = MF.getFrameInfo();
3921   MFI.setReturnAddressIsTaken(true);
3922   MVT XLenVT = Subtarget.getXLenVT();
3923   int XLenInBytes = Subtarget.getXLen() / 8;
3924 
3925   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3926     return SDValue();
3927 
3928   EVT VT = Op.getValueType();
3929   SDLoc DL(Op);
3930   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3931   if (Depth) {
3932     int Off = -XLenInBytes;
3933     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3934     SDValue Offset = DAG.getConstant(Off, DL, VT);
3935     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3936                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3937                        MachinePointerInfo());
3938   }
3939 
3940   // Return the value of the return address register, marking it an implicit
3941   // live-in.
3942   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3943   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3944 }
3945 
3946 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3947                                                  SelectionDAG &DAG) const {
3948   SDLoc DL(Op);
3949   SDValue Lo = Op.getOperand(0);
3950   SDValue Hi = Op.getOperand(1);
3951   SDValue Shamt = Op.getOperand(2);
3952   EVT VT = Lo.getValueType();
3953 
3954   // if Shamt-XLEN < 0: // Shamt < XLEN
3955   //   Lo = Lo << Shamt
3956   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3957   // else:
3958   //   Lo = 0
3959   //   Hi = Lo << (Shamt-XLEN)
3960 
3961   SDValue Zero = DAG.getConstant(0, DL, VT);
3962   SDValue One = DAG.getConstant(1, DL, VT);
3963   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3964   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3965   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3966   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3967 
3968   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3969   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3970   SDValue ShiftRightLo =
3971       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3972   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3973   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3974   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3975 
3976   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3977 
3978   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3979   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3980 
3981   SDValue Parts[2] = {Lo, Hi};
3982   return DAG.getMergeValues(Parts, DL);
3983 }
3984 
3985 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3986                                                   bool IsSRA) const {
3987   SDLoc DL(Op);
3988   SDValue Lo = Op.getOperand(0);
3989   SDValue Hi = Op.getOperand(1);
3990   SDValue Shamt = Op.getOperand(2);
3991   EVT VT = Lo.getValueType();
3992 
3993   // SRA expansion:
3994   //   if Shamt-XLEN < 0: // Shamt < XLEN
3995   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3996   //     Hi = Hi >>s Shamt
3997   //   else:
3998   //     Lo = Hi >>s (Shamt-XLEN);
3999   //     Hi = Hi >>s (XLEN-1)
4000   //
4001   // SRL expansion:
4002   //   if Shamt-XLEN < 0: // Shamt < XLEN
4003   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4004   //     Hi = Hi >>u Shamt
4005   //   else:
4006   //     Lo = Hi >>u (Shamt-XLEN);
4007   //     Hi = 0;
4008 
4009   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4010 
4011   SDValue Zero = DAG.getConstant(0, DL, VT);
4012   SDValue One = DAG.getConstant(1, DL, VT);
4013   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4014   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4015   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4016   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4017 
4018   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4019   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4020   SDValue ShiftLeftHi =
4021       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4022   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4023   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4024   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4025   SDValue HiFalse =
4026       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4027 
4028   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4029 
4030   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4031   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4032 
4033   SDValue Parts[2] = {Lo, Hi};
4034   return DAG.getMergeValues(Parts, DL);
4035 }
4036 
4037 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4038 // legal equivalently-sized i8 type, so we can use that as a go-between.
4039 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4040                                                   SelectionDAG &DAG) const {
4041   SDLoc DL(Op);
4042   MVT VT = Op.getSimpleValueType();
4043   SDValue SplatVal = Op.getOperand(0);
4044   // All-zeros or all-ones splats are handled specially.
4045   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4046     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4047     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4048   }
4049   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4050     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4051     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4052   }
4053   MVT XLenVT = Subtarget.getXLenVT();
4054   assert(SplatVal.getValueType() == XLenVT &&
4055          "Unexpected type for i1 splat value");
4056   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4057   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4058                          DAG.getConstant(1, DL, XLenVT));
4059   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4060   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4061   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4062 }
4063 
4064 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4065 // illegal (currently only vXi64 RV32).
4066 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4067 // them to VMV_V_X_VL.
4068 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4069                                                      SelectionDAG &DAG) const {
4070   SDLoc DL(Op);
4071   MVT VecVT = Op.getSimpleValueType();
4072   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4073          "Unexpected SPLAT_VECTOR_PARTS lowering");
4074 
4075   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4076   SDValue Lo = Op.getOperand(0);
4077   SDValue Hi = Op.getOperand(1);
4078 
4079   if (VecVT.isFixedLengthVector()) {
4080     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4081     SDLoc DL(Op);
4082     SDValue Mask, VL;
4083     std::tie(Mask, VL) =
4084         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4085 
4086     SDValue Res =
4087         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4088     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4089   }
4090 
4091   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4092     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4093     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4094     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4095     // node in order to try and match RVV vector/scalar instructions.
4096     if ((LoC >> 31) == HiC)
4097       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4098                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4099   }
4100 
4101   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4102   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4103       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4104       Hi.getConstantOperandVal(1) == 31)
4105     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4106                        DAG.getRegister(RISCV::X0, MVT::i32));
4107 
4108   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4109   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4110                      DAG.getUNDEF(VecVT), Lo, Hi,
4111                      DAG.getRegister(RISCV::X0, MVT::i32));
4112 }
4113 
4114 // Custom-lower extensions from mask vectors by using a vselect either with 1
4115 // for zero/any-extension or -1 for sign-extension:
4116 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4117 // Note that any-extension is lowered identically to zero-extension.
4118 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4119                                                 int64_t ExtTrueVal) const {
4120   SDLoc DL(Op);
4121   MVT VecVT = Op.getSimpleValueType();
4122   SDValue Src = Op.getOperand(0);
4123   // Only custom-lower extensions from mask types
4124   assert(Src.getValueType().isVector() &&
4125          Src.getValueType().getVectorElementType() == MVT::i1);
4126 
4127   if (VecVT.isScalableVector()) {
4128     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4129     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4130     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4131   }
4132 
4133   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4134   MVT I1ContainerVT =
4135       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4136 
4137   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4138 
4139   SDValue Mask, VL;
4140   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4141 
4142   MVT XLenVT = Subtarget.getXLenVT();
4143   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4144   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4145 
4146   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4147                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4148   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4149                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4150   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4151                                SplatTrueVal, SplatZero, VL);
4152 
4153   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4154 }
4155 
4156 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4157     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4158   MVT ExtVT = Op.getSimpleValueType();
4159   // Only custom-lower extensions from fixed-length vector types.
4160   if (!ExtVT.isFixedLengthVector())
4161     return Op;
4162   MVT VT = Op.getOperand(0).getSimpleValueType();
4163   // Grab the canonical container type for the extended type. Infer the smaller
4164   // type from that to ensure the same number of vector elements, as we know
4165   // the LMUL will be sufficient to hold the smaller type.
4166   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4167   // Get the extended container type manually to ensure the same number of
4168   // vector elements between source and dest.
4169   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4170                                      ContainerExtVT.getVectorElementCount());
4171 
4172   SDValue Op1 =
4173       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4174 
4175   SDLoc DL(Op);
4176   SDValue Mask, VL;
4177   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4178 
4179   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4180 
4181   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4182 }
4183 
4184 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4185 // setcc operation:
4186 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4187 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4188                                                       SelectionDAG &DAG) const {
4189   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4190   SDLoc DL(Op);
4191   EVT MaskVT = Op.getValueType();
4192   // Only expect to custom-lower truncations to mask types
4193   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4194          "Unexpected type for vector mask lowering");
4195   SDValue Src = Op.getOperand(0);
4196   MVT VecVT = Src.getSimpleValueType();
4197   SDValue Mask, VL;
4198   if (IsVPTrunc) {
4199     Mask = Op.getOperand(1);
4200     VL = Op.getOperand(2);
4201   }
4202   // If this is a fixed vector, we need to convert it to a scalable vector.
4203   MVT ContainerVT = VecVT;
4204 
4205   if (VecVT.isFixedLengthVector()) {
4206     ContainerVT = getContainerForFixedLengthVector(VecVT);
4207     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4208     if (IsVPTrunc) {
4209       MVT MaskContainerVT =
4210           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4211       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4212     }
4213   }
4214 
4215   if (!IsVPTrunc) {
4216     std::tie(Mask, VL) =
4217         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4218   }
4219 
4220   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4221   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4222 
4223   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4224                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4225   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4226                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4227 
4228   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4229   SDValue Trunc =
4230       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4231   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4232                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4233   if (MaskVT.isFixedLengthVector())
4234     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4235   return Trunc;
4236 }
4237 
4238 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4239                                                   SelectionDAG &DAG) const {
4240   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4241   SDLoc DL(Op);
4242 
4243   MVT VT = Op.getSimpleValueType();
4244   // Only custom-lower vector truncates
4245   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4246 
4247   // Truncates to mask types are handled differently
4248   if (VT.getVectorElementType() == MVT::i1)
4249     return lowerVectorMaskTruncLike(Op, DAG);
4250 
4251   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4252   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4253   // truncate by one power of two at a time.
4254   MVT DstEltVT = VT.getVectorElementType();
4255 
4256   SDValue Src = Op.getOperand(0);
4257   MVT SrcVT = Src.getSimpleValueType();
4258   MVT SrcEltVT = SrcVT.getVectorElementType();
4259 
4260   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4261          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4262          "Unexpected vector truncate lowering");
4263 
4264   MVT ContainerVT = SrcVT;
4265   SDValue Mask, VL;
4266   if (IsVPTrunc) {
4267     Mask = Op.getOperand(1);
4268     VL = Op.getOperand(2);
4269   }
4270   if (SrcVT.isFixedLengthVector()) {
4271     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4272     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4273     if (IsVPTrunc) {
4274       MVT MaskVT = getMaskTypeFor(ContainerVT);
4275       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4276     }
4277   }
4278 
4279   SDValue Result = Src;
4280   if (!IsVPTrunc) {
4281     std::tie(Mask, VL) =
4282         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4283   }
4284 
4285   LLVMContext &Context = *DAG.getContext();
4286   const ElementCount Count = ContainerVT.getVectorElementCount();
4287   do {
4288     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4289     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4290     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4291                          Mask, VL);
4292   } while (SrcEltVT != DstEltVT);
4293 
4294   if (SrcVT.isFixedLengthVector())
4295     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4296 
4297   return Result;
4298 }
4299 
4300 SDValue
4301 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4302                                                     SelectionDAG &DAG) const {
4303   bool IsVP =
4304       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4305   bool IsExtend =
4306       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4307   // RVV can only do truncate fp to types half the size as the source. We
4308   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4309   // conversion instruction.
4310   SDLoc DL(Op);
4311   MVT VT = Op.getSimpleValueType();
4312 
4313   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4314 
4315   SDValue Src = Op.getOperand(0);
4316   MVT SrcVT = Src.getSimpleValueType();
4317 
4318   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4319                                      SrcVT.getVectorElementType() != MVT::f16);
4320   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4321                                      SrcVT.getVectorElementType() != MVT::f64);
4322 
4323   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4324 
4325   // Prepare any fixed-length vector operands.
4326   MVT ContainerVT = VT;
4327   SDValue Mask, VL;
4328   if (IsVP) {
4329     Mask = Op.getOperand(1);
4330     VL = Op.getOperand(2);
4331   }
4332   if (VT.isFixedLengthVector()) {
4333     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4334     ContainerVT =
4335         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4336     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4337     if (IsVP) {
4338       MVT MaskVT = getMaskTypeFor(ContainerVT);
4339       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4340     }
4341   }
4342 
4343   if (!IsVP)
4344     std::tie(Mask, VL) =
4345         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4346 
4347   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4348 
4349   if (IsDirectConv) {
4350     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4351     if (VT.isFixedLengthVector())
4352       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4353     return Src;
4354   }
4355 
4356   unsigned InterConvOpc =
4357       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4358 
4359   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4360   SDValue IntermediateConv =
4361       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4362   SDValue Result =
4363       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4364   if (VT.isFixedLengthVector())
4365     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4366   return Result;
4367 }
4368 
4369 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4370 // first position of a vector, and that vector is slid up to the insert index.
4371 // By limiting the active vector length to index+1 and merging with the
4372 // original vector (with an undisturbed tail policy for elements >= VL), we
4373 // achieve the desired result of leaving all elements untouched except the one
4374 // at VL-1, which is replaced with the desired value.
4375 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4376                                                     SelectionDAG &DAG) const {
4377   SDLoc DL(Op);
4378   MVT VecVT = Op.getSimpleValueType();
4379   SDValue Vec = Op.getOperand(0);
4380   SDValue Val = Op.getOperand(1);
4381   SDValue Idx = Op.getOperand(2);
4382 
4383   if (VecVT.getVectorElementType() == MVT::i1) {
4384     // FIXME: For now we just promote to an i8 vector and insert into that,
4385     // but this is probably not optimal.
4386     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4387     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4388     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4389     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4390   }
4391 
4392   MVT ContainerVT = VecVT;
4393   // If the operand is a fixed-length vector, convert to a scalable one.
4394   if (VecVT.isFixedLengthVector()) {
4395     ContainerVT = getContainerForFixedLengthVector(VecVT);
4396     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4397   }
4398 
4399   MVT XLenVT = Subtarget.getXLenVT();
4400 
4401   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4402   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4403   // Even i64-element vectors on RV32 can be lowered without scalar
4404   // legalization if the most-significant 32 bits of the value are not affected
4405   // by the sign-extension of the lower 32 bits.
4406   // TODO: We could also catch sign extensions of a 32-bit value.
4407   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4408     const auto *CVal = cast<ConstantSDNode>(Val);
4409     if (isInt<32>(CVal->getSExtValue())) {
4410       IsLegalInsert = true;
4411       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4412     }
4413   }
4414 
4415   SDValue Mask, VL;
4416   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4417 
4418   SDValue ValInVec;
4419 
4420   if (IsLegalInsert) {
4421     unsigned Opc =
4422         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4423     if (isNullConstant(Idx)) {
4424       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4425       if (!VecVT.isFixedLengthVector())
4426         return Vec;
4427       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4428     }
4429     ValInVec =
4430         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4431   } else {
4432     // On RV32, i64-element vectors must be specially handled to place the
4433     // value at element 0, by using two vslide1up instructions in sequence on
4434     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4435     // this.
4436     SDValue One = DAG.getConstant(1, DL, XLenVT);
4437     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4438     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4439     MVT I32ContainerVT =
4440         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4441     SDValue I32Mask =
4442         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4443     // Limit the active VL to two.
4444     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4445     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4446     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4447     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4448                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4449     // First slide in the hi value, then the lo in underneath it.
4450     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4451                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4452                            I32Mask, InsertI64VL);
4453     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4454                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4455                            I32Mask, InsertI64VL);
4456     // Bitcast back to the right container type.
4457     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4458   }
4459 
4460   // Now that the value is in a vector, slide it into position.
4461   SDValue InsertVL =
4462       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4463   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4464                                 ValInVec, Idx, Mask, InsertVL);
4465   if (!VecVT.isFixedLengthVector())
4466     return Slideup;
4467   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4468 }
4469 
4470 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4471 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4472 // types this is done using VMV_X_S to allow us to glean information about the
4473 // sign bits of the result.
4474 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4475                                                      SelectionDAG &DAG) const {
4476   SDLoc DL(Op);
4477   SDValue Idx = Op.getOperand(1);
4478   SDValue Vec = Op.getOperand(0);
4479   EVT EltVT = Op.getValueType();
4480   MVT VecVT = Vec.getSimpleValueType();
4481   MVT XLenVT = Subtarget.getXLenVT();
4482 
4483   if (VecVT.getVectorElementType() == MVT::i1) {
4484     if (VecVT.isFixedLengthVector()) {
4485       unsigned NumElts = VecVT.getVectorNumElements();
4486       if (NumElts >= 8) {
4487         MVT WideEltVT;
4488         unsigned WidenVecLen;
4489         SDValue ExtractElementIdx;
4490         SDValue ExtractBitIdx;
4491         unsigned MaxEEW = Subtarget.getELEN();
4492         MVT LargestEltVT = MVT::getIntegerVT(
4493             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4494         if (NumElts <= LargestEltVT.getSizeInBits()) {
4495           assert(isPowerOf2_32(NumElts) &&
4496                  "the number of elements should be power of 2");
4497           WideEltVT = MVT::getIntegerVT(NumElts);
4498           WidenVecLen = 1;
4499           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4500           ExtractBitIdx = Idx;
4501         } else {
4502           WideEltVT = LargestEltVT;
4503           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4504           // extract element index = index / element width
4505           ExtractElementIdx = DAG.getNode(
4506               ISD::SRL, DL, XLenVT, Idx,
4507               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4508           // mask bit index = index % element width
4509           ExtractBitIdx = DAG.getNode(
4510               ISD::AND, DL, XLenVT, Idx,
4511               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4512         }
4513         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4514         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4515         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4516                                          Vec, ExtractElementIdx);
4517         // Extract the bit from GPR.
4518         SDValue ShiftRight =
4519             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4520         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4521                            DAG.getConstant(1, DL, XLenVT));
4522       }
4523     }
4524     // Otherwise, promote to an i8 vector and extract from that.
4525     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4526     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4527     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4528   }
4529 
4530   // If this is a fixed vector, we need to convert it to a scalable vector.
4531   MVT ContainerVT = VecVT;
4532   if (VecVT.isFixedLengthVector()) {
4533     ContainerVT = getContainerForFixedLengthVector(VecVT);
4534     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4535   }
4536 
4537   // If the index is 0, the vector is already in the right position.
4538   if (!isNullConstant(Idx)) {
4539     // Use a VL of 1 to avoid processing more elements than we need.
4540     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4541     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4542     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4543                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4544   }
4545 
4546   if (!EltVT.isInteger()) {
4547     // Floating-point extracts are handled in TableGen.
4548     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4549                        DAG.getConstant(0, DL, XLenVT));
4550   }
4551 
4552   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4553   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4554 }
4555 
4556 // Some RVV intrinsics may claim that they want an integer operand to be
4557 // promoted or expanded.
4558 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4559                                            const RISCVSubtarget &Subtarget) {
4560   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4561           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4562          "Unexpected opcode");
4563 
4564   if (!Subtarget.hasVInstructions())
4565     return SDValue();
4566 
4567   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4568   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4569   SDLoc DL(Op);
4570 
4571   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4572       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4573   if (!II || !II->hasScalarOperand())
4574     return SDValue();
4575 
4576   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4577   assert(SplatOp < Op.getNumOperands());
4578 
4579   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4580   SDValue &ScalarOp = Operands[SplatOp];
4581   MVT OpVT = ScalarOp.getSimpleValueType();
4582   MVT XLenVT = Subtarget.getXLenVT();
4583 
4584   // If this isn't a scalar, or its type is XLenVT we're done.
4585   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4586     return SDValue();
4587 
4588   // Simplest case is that the operand needs to be promoted to XLenVT.
4589   if (OpVT.bitsLT(XLenVT)) {
4590     // If the operand is a constant, sign extend to increase our chances
4591     // of being able to use a .vi instruction. ANY_EXTEND would become a
4592     // a zero extend and the simm5 check in isel would fail.
4593     // FIXME: Should we ignore the upper bits in isel instead?
4594     unsigned ExtOpc =
4595         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4596     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4597     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4598   }
4599 
4600   // Use the previous operand to get the vXi64 VT. The result might be a mask
4601   // VT for compares. Using the previous operand assumes that the previous
4602   // operand will never have a smaller element size than a scalar operand and
4603   // that a widening operation never uses SEW=64.
4604   // NOTE: If this fails the below assert, we can probably just find the
4605   // element count from any operand or result and use it to construct the VT.
4606   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4607   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4608 
4609   // The more complex case is when the scalar is larger than XLenVT.
4610   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4611          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4612 
4613   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4614   // instruction to sign-extend since SEW>XLEN.
4615   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4616     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4617     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4618   }
4619 
4620   switch (IntNo) {
4621   case Intrinsic::riscv_vslide1up:
4622   case Intrinsic::riscv_vslide1down:
4623   case Intrinsic::riscv_vslide1up_mask:
4624   case Intrinsic::riscv_vslide1down_mask: {
4625     // We need to special case these when the scalar is larger than XLen.
4626     unsigned NumOps = Op.getNumOperands();
4627     bool IsMasked = NumOps == 7;
4628 
4629     // Convert the vector source to the equivalent nxvXi32 vector.
4630     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4631     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4632 
4633     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4634                                    DAG.getConstant(0, DL, XLenVT));
4635     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4636                                    DAG.getConstant(1, DL, XLenVT));
4637 
4638     // Double the VL since we halved SEW.
4639     SDValue AVL = getVLOperand(Op);
4640     SDValue I32VL;
4641 
4642     // Optimize for constant AVL
4643     if (isa<ConstantSDNode>(AVL)) {
4644       unsigned EltSize = VT.getScalarSizeInBits();
4645       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4646 
4647       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4648       unsigned MaxVLMAX =
4649           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4650 
4651       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4652       unsigned MinVLMAX =
4653           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4654 
4655       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4656       if (AVLInt <= MinVLMAX) {
4657         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4658       } else if (AVLInt >= 2 * MaxVLMAX) {
4659         // Just set vl to VLMAX in this situation
4660         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4661         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4662         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4663         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4664         SDValue SETVLMAX = DAG.getTargetConstant(
4665             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4666         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4667                             LMUL);
4668       } else {
4669         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4670         // is related to the hardware implementation.
4671         // So let the following code handle
4672       }
4673     }
4674     if (!I32VL) {
4675       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4676       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4677       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4678       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4679       SDValue SETVL =
4680           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4681       // Using vsetvli instruction to get actually used length which related to
4682       // the hardware implementation
4683       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4684                                SEW, LMUL);
4685       I32VL =
4686           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4687     }
4688 
4689     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4690 
4691     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4692     // instructions.
4693     SDValue Passthru;
4694     if (IsMasked)
4695       Passthru = DAG.getUNDEF(I32VT);
4696     else
4697       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4698 
4699     if (IntNo == Intrinsic::riscv_vslide1up ||
4700         IntNo == Intrinsic::riscv_vslide1up_mask) {
4701       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4702                         ScalarHi, I32Mask, I32VL);
4703       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4704                         ScalarLo, I32Mask, I32VL);
4705     } else {
4706       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4707                         ScalarLo, I32Mask, I32VL);
4708       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4709                         ScalarHi, I32Mask, I32VL);
4710     }
4711 
4712     // Convert back to nxvXi64.
4713     Vec = DAG.getBitcast(VT, Vec);
4714 
4715     if (!IsMasked)
4716       return Vec;
4717     // Apply mask after the operation.
4718     SDValue Mask = Operands[NumOps - 3];
4719     SDValue MaskedOff = Operands[1];
4720     // Assume Policy operand is the last operand.
4721     uint64_t Policy =
4722         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4723     // We don't need to select maskedoff if it's undef.
4724     if (MaskedOff.isUndef())
4725       return Vec;
4726     // TAMU
4727     if (Policy == RISCVII::TAIL_AGNOSTIC)
4728       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4729                          AVL);
4730     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4731     // It's fine because vmerge does not care mask policy.
4732     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4733                        AVL);
4734   }
4735   }
4736 
4737   // We need to convert the scalar to a splat vector.
4738   SDValue VL = getVLOperand(Op);
4739   assert(VL.getValueType() == XLenVT);
4740   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4741   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4742 }
4743 
4744 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4745                                                      SelectionDAG &DAG) const {
4746   unsigned IntNo = Op.getConstantOperandVal(0);
4747   SDLoc DL(Op);
4748   MVT XLenVT = Subtarget.getXLenVT();
4749 
4750   switch (IntNo) {
4751   default:
4752     break; // Don't custom lower most intrinsics.
4753   case Intrinsic::thread_pointer: {
4754     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4755     return DAG.getRegister(RISCV::X4, PtrVT);
4756   }
4757   case Intrinsic::riscv_orc_b:
4758   case Intrinsic::riscv_brev8: {
4759     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4760     unsigned Opc =
4761         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4762     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4763                        DAG.getConstant(7, DL, XLenVT));
4764   }
4765   case Intrinsic::riscv_grev:
4766   case Intrinsic::riscv_gorc: {
4767     unsigned Opc =
4768         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4769     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4770   }
4771   case Intrinsic::riscv_zip:
4772   case Intrinsic::riscv_unzip: {
4773     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4774     // For i32 the immediate is 15. For i64 the immediate is 31.
4775     unsigned Opc =
4776         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4777     unsigned BitWidth = Op.getValueSizeInBits();
4778     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4779     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4780                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4781   }
4782   case Intrinsic::riscv_shfl:
4783   case Intrinsic::riscv_unshfl: {
4784     unsigned Opc =
4785         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4786     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4787   }
4788   case Intrinsic::riscv_bcompress:
4789   case Intrinsic::riscv_bdecompress: {
4790     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4791                                                        : RISCVISD::BDECOMPRESS;
4792     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4793   }
4794   case Intrinsic::riscv_bfp:
4795     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4796                        Op.getOperand(2));
4797   case Intrinsic::riscv_fsl:
4798     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4799                        Op.getOperand(2), Op.getOperand(3));
4800   case Intrinsic::riscv_fsr:
4801     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4802                        Op.getOperand(2), Op.getOperand(3));
4803   case Intrinsic::riscv_vmv_x_s:
4804     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4805     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4806                        Op.getOperand(1));
4807   case Intrinsic::riscv_vmv_v_x:
4808     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4809                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4810                             Subtarget);
4811   case Intrinsic::riscv_vfmv_v_f:
4812     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4813                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4814   case Intrinsic::riscv_vmv_s_x: {
4815     SDValue Scalar = Op.getOperand(2);
4816 
4817     if (Scalar.getValueType().bitsLE(XLenVT)) {
4818       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4819       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4820                          Op.getOperand(1), Scalar, Op.getOperand(3));
4821     }
4822 
4823     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4824 
4825     // This is an i64 value that lives in two scalar registers. We have to
4826     // insert this in a convoluted way. First we build vXi64 splat containing
4827     // the two values that we assemble using some bit math. Next we'll use
4828     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4829     // to merge element 0 from our splat into the source vector.
4830     // FIXME: This is probably not the best way to do this, but it is
4831     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4832     // point.
4833     //   sw lo, (a0)
4834     //   sw hi, 4(a0)
4835     //   vlse vX, (a0)
4836     //
4837     //   vid.v      vVid
4838     //   vmseq.vx   mMask, vVid, 0
4839     //   vmerge.vvm vDest, vSrc, vVal, mMask
4840     MVT VT = Op.getSimpleValueType();
4841     SDValue Vec = Op.getOperand(1);
4842     SDValue VL = getVLOperand(Op);
4843 
4844     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4845     if (Op.getOperand(1).isUndef())
4846       return SplattedVal;
4847     SDValue SplattedIdx =
4848         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4849                     DAG.getConstant(0, DL, MVT::i32), VL);
4850 
4851     MVT MaskVT = getMaskTypeFor(VT);
4852     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4853     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4854     SDValue SelectCond =
4855         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4856                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4857     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4858                        Vec, VL);
4859   }
4860   }
4861 
4862   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4863 }
4864 
4865 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4866                                                     SelectionDAG &DAG) const {
4867   unsigned IntNo = Op.getConstantOperandVal(1);
4868   switch (IntNo) {
4869   default:
4870     break;
4871   case Intrinsic::riscv_masked_strided_load: {
4872     SDLoc DL(Op);
4873     MVT XLenVT = Subtarget.getXLenVT();
4874 
4875     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4876     // the selection of the masked intrinsics doesn't do this for us.
4877     SDValue Mask = Op.getOperand(5);
4878     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4879 
4880     MVT VT = Op->getSimpleValueType(0);
4881     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4882 
4883     SDValue PassThru = Op.getOperand(2);
4884     if (!IsUnmasked) {
4885       MVT MaskVT = getMaskTypeFor(ContainerVT);
4886       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4887       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4888     }
4889 
4890     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4891 
4892     SDValue IntID = DAG.getTargetConstant(
4893         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4894         XLenVT);
4895 
4896     auto *Load = cast<MemIntrinsicSDNode>(Op);
4897     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4898     if (IsUnmasked)
4899       Ops.push_back(DAG.getUNDEF(ContainerVT));
4900     else
4901       Ops.push_back(PassThru);
4902     Ops.push_back(Op.getOperand(3)); // Ptr
4903     Ops.push_back(Op.getOperand(4)); // Stride
4904     if (!IsUnmasked)
4905       Ops.push_back(Mask);
4906     Ops.push_back(VL);
4907     if (!IsUnmasked) {
4908       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4909       Ops.push_back(Policy);
4910     }
4911 
4912     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4913     SDValue Result =
4914         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4915                                 Load->getMemoryVT(), Load->getMemOperand());
4916     SDValue Chain = Result.getValue(1);
4917     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4918     return DAG.getMergeValues({Result, Chain}, DL);
4919   }
4920   case Intrinsic::riscv_seg2_load:
4921   case Intrinsic::riscv_seg3_load:
4922   case Intrinsic::riscv_seg4_load:
4923   case Intrinsic::riscv_seg5_load:
4924   case Intrinsic::riscv_seg6_load:
4925   case Intrinsic::riscv_seg7_load:
4926   case Intrinsic::riscv_seg8_load: {
4927     SDLoc DL(Op);
4928     static const Intrinsic::ID VlsegInts[7] = {
4929         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4930         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4931         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4932         Intrinsic::riscv_vlseg8};
4933     unsigned NF = Op->getNumValues() - 1;
4934     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4935     MVT XLenVT = Subtarget.getXLenVT();
4936     MVT VT = Op->getSimpleValueType(0);
4937     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4938 
4939     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4940     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4941     auto *Load = cast<MemIntrinsicSDNode>(Op);
4942     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4943     ContainerVTs.push_back(MVT::Other);
4944     SDVTList VTs = DAG.getVTList(ContainerVTs);
4945     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
4946     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
4947     Ops.push_back(Op.getOperand(2));
4948     Ops.push_back(VL);
4949     SDValue Result =
4950         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4951                                 Load->getMemoryVT(), Load->getMemOperand());
4952     SmallVector<SDValue, 9> Results;
4953     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4954       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4955                                                   DAG, Subtarget));
4956     Results.push_back(Result.getValue(NF));
4957     return DAG.getMergeValues(Results, DL);
4958   }
4959   }
4960 
4961   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4962 }
4963 
4964 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4965                                                  SelectionDAG &DAG) const {
4966   unsigned IntNo = Op.getConstantOperandVal(1);
4967   switch (IntNo) {
4968   default:
4969     break;
4970   case Intrinsic::riscv_masked_strided_store: {
4971     SDLoc DL(Op);
4972     MVT XLenVT = Subtarget.getXLenVT();
4973 
4974     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4975     // the selection of the masked intrinsics doesn't do this for us.
4976     SDValue Mask = Op.getOperand(5);
4977     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4978 
4979     SDValue Val = Op.getOperand(2);
4980     MVT VT = Val.getSimpleValueType();
4981     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4982 
4983     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4984     if (!IsUnmasked) {
4985       MVT MaskVT = getMaskTypeFor(ContainerVT);
4986       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4987     }
4988 
4989     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4990 
4991     SDValue IntID = DAG.getTargetConstant(
4992         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4993         XLenVT);
4994 
4995     auto *Store = cast<MemIntrinsicSDNode>(Op);
4996     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4997     Ops.push_back(Val);
4998     Ops.push_back(Op.getOperand(3)); // Ptr
4999     Ops.push_back(Op.getOperand(4)); // Stride
5000     if (!IsUnmasked)
5001       Ops.push_back(Mask);
5002     Ops.push_back(VL);
5003 
5004     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5005                                    Ops, Store->getMemoryVT(),
5006                                    Store->getMemOperand());
5007   }
5008   }
5009 
5010   return SDValue();
5011 }
5012 
5013 static MVT getLMUL1VT(MVT VT) {
5014   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5015          "Unexpected vector MVT");
5016   return MVT::getScalableVectorVT(
5017       VT.getVectorElementType(),
5018       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5019 }
5020 
5021 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5022   switch (ISDOpcode) {
5023   default:
5024     llvm_unreachable("Unhandled reduction");
5025   case ISD::VECREDUCE_ADD:
5026     return RISCVISD::VECREDUCE_ADD_VL;
5027   case ISD::VECREDUCE_UMAX:
5028     return RISCVISD::VECREDUCE_UMAX_VL;
5029   case ISD::VECREDUCE_SMAX:
5030     return RISCVISD::VECREDUCE_SMAX_VL;
5031   case ISD::VECREDUCE_UMIN:
5032     return RISCVISD::VECREDUCE_UMIN_VL;
5033   case ISD::VECREDUCE_SMIN:
5034     return RISCVISD::VECREDUCE_SMIN_VL;
5035   case ISD::VECREDUCE_AND:
5036     return RISCVISD::VECREDUCE_AND_VL;
5037   case ISD::VECREDUCE_OR:
5038     return RISCVISD::VECREDUCE_OR_VL;
5039   case ISD::VECREDUCE_XOR:
5040     return RISCVISD::VECREDUCE_XOR_VL;
5041   }
5042 }
5043 
5044 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5045                                                          SelectionDAG &DAG,
5046                                                          bool IsVP) const {
5047   SDLoc DL(Op);
5048   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5049   MVT VecVT = Vec.getSimpleValueType();
5050   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5051           Op.getOpcode() == ISD::VECREDUCE_OR ||
5052           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5053           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5054           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5055           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5056          "Unexpected reduction lowering");
5057 
5058   MVT XLenVT = Subtarget.getXLenVT();
5059   assert(Op.getValueType() == XLenVT &&
5060          "Expected reduction output to be legalized to XLenVT");
5061 
5062   MVT ContainerVT = VecVT;
5063   if (VecVT.isFixedLengthVector()) {
5064     ContainerVT = getContainerForFixedLengthVector(VecVT);
5065     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5066   }
5067 
5068   SDValue Mask, VL;
5069   if (IsVP) {
5070     Mask = Op.getOperand(2);
5071     VL = Op.getOperand(3);
5072   } else {
5073     std::tie(Mask, VL) =
5074         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5075   }
5076 
5077   unsigned BaseOpc;
5078   ISD::CondCode CC;
5079   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5080 
5081   switch (Op.getOpcode()) {
5082   default:
5083     llvm_unreachable("Unhandled reduction");
5084   case ISD::VECREDUCE_AND:
5085   case ISD::VP_REDUCE_AND: {
5086     // vcpop ~x == 0
5087     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5088     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5089     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5090     CC = ISD::SETEQ;
5091     BaseOpc = ISD::AND;
5092     break;
5093   }
5094   case ISD::VECREDUCE_OR:
5095   case ISD::VP_REDUCE_OR:
5096     // vcpop x != 0
5097     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5098     CC = ISD::SETNE;
5099     BaseOpc = ISD::OR;
5100     break;
5101   case ISD::VECREDUCE_XOR:
5102   case ISD::VP_REDUCE_XOR: {
5103     // ((vcpop x) & 1) != 0
5104     SDValue One = DAG.getConstant(1, DL, XLenVT);
5105     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5106     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5107     CC = ISD::SETNE;
5108     BaseOpc = ISD::XOR;
5109     break;
5110   }
5111   }
5112 
5113   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5114 
5115   if (!IsVP)
5116     return SetCC;
5117 
5118   // Now include the start value in the operation.
5119   // Note that we must return the start value when no elements are operated
5120   // upon. The vcpop instructions we've emitted in each case above will return
5121   // 0 for an inactive vector, and so we've already received the neutral value:
5122   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5123   // can simply include the start value.
5124   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5125 }
5126 
5127 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5128                                             SelectionDAG &DAG) const {
5129   SDLoc DL(Op);
5130   SDValue Vec = Op.getOperand(0);
5131   EVT VecEVT = Vec.getValueType();
5132 
5133   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5134 
5135   // Due to ordering in legalize types we may have a vector type that needs to
5136   // be split. Do that manually so we can get down to a legal type.
5137   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5138          TargetLowering::TypeSplitVector) {
5139     SDValue Lo, Hi;
5140     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5141     VecEVT = Lo.getValueType();
5142     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5143   }
5144 
5145   // TODO: The type may need to be widened rather than split. Or widened before
5146   // it can be split.
5147   if (!isTypeLegal(VecEVT))
5148     return SDValue();
5149 
5150   MVT VecVT = VecEVT.getSimpleVT();
5151   MVT VecEltVT = VecVT.getVectorElementType();
5152   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5153 
5154   MVT ContainerVT = VecVT;
5155   if (VecVT.isFixedLengthVector()) {
5156     ContainerVT = getContainerForFixedLengthVector(VecVT);
5157     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5158   }
5159 
5160   MVT M1VT = getLMUL1VT(ContainerVT);
5161   MVT XLenVT = Subtarget.getXLenVT();
5162 
5163   SDValue Mask, VL;
5164   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5165 
5166   SDValue NeutralElem =
5167       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5168   SDValue IdentitySplat =
5169       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5170                        M1VT, DL, DAG, Subtarget);
5171   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5172                                   IdentitySplat, Mask, VL);
5173   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5174                              DAG.getConstant(0, DL, XLenVT));
5175   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5176 }
5177 
5178 // Given a reduction op, this function returns the matching reduction opcode,
5179 // the vector SDValue and the scalar SDValue required to lower this to a
5180 // RISCVISD node.
5181 static std::tuple<unsigned, SDValue, SDValue>
5182 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5183   SDLoc DL(Op);
5184   auto Flags = Op->getFlags();
5185   unsigned Opcode = Op.getOpcode();
5186   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5187   switch (Opcode) {
5188   default:
5189     llvm_unreachable("Unhandled reduction");
5190   case ISD::VECREDUCE_FADD: {
5191     // Use positive zero if we can. It is cheaper to materialize.
5192     SDValue Zero =
5193         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5194     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5195   }
5196   case ISD::VECREDUCE_SEQ_FADD:
5197     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5198                            Op.getOperand(0));
5199   case ISD::VECREDUCE_FMIN:
5200     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5201                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5202   case ISD::VECREDUCE_FMAX:
5203     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5204                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5205   }
5206 }
5207 
5208 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5209                                               SelectionDAG &DAG) const {
5210   SDLoc DL(Op);
5211   MVT VecEltVT = Op.getSimpleValueType();
5212 
5213   unsigned RVVOpcode;
5214   SDValue VectorVal, ScalarVal;
5215   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5216       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5217   MVT VecVT = VectorVal.getSimpleValueType();
5218 
5219   MVT ContainerVT = VecVT;
5220   if (VecVT.isFixedLengthVector()) {
5221     ContainerVT = getContainerForFixedLengthVector(VecVT);
5222     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5223   }
5224 
5225   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5226   MVT XLenVT = Subtarget.getXLenVT();
5227 
5228   SDValue Mask, VL;
5229   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5230 
5231   SDValue ScalarSplat =
5232       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5233                        M1VT, DL, DAG, Subtarget);
5234   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5235                                   VectorVal, ScalarSplat, Mask, VL);
5236   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5237                      DAG.getConstant(0, DL, XLenVT));
5238 }
5239 
5240 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5241   switch (ISDOpcode) {
5242   default:
5243     llvm_unreachable("Unhandled reduction");
5244   case ISD::VP_REDUCE_ADD:
5245     return RISCVISD::VECREDUCE_ADD_VL;
5246   case ISD::VP_REDUCE_UMAX:
5247     return RISCVISD::VECREDUCE_UMAX_VL;
5248   case ISD::VP_REDUCE_SMAX:
5249     return RISCVISD::VECREDUCE_SMAX_VL;
5250   case ISD::VP_REDUCE_UMIN:
5251     return RISCVISD::VECREDUCE_UMIN_VL;
5252   case ISD::VP_REDUCE_SMIN:
5253     return RISCVISD::VECREDUCE_SMIN_VL;
5254   case ISD::VP_REDUCE_AND:
5255     return RISCVISD::VECREDUCE_AND_VL;
5256   case ISD::VP_REDUCE_OR:
5257     return RISCVISD::VECREDUCE_OR_VL;
5258   case ISD::VP_REDUCE_XOR:
5259     return RISCVISD::VECREDUCE_XOR_VL;
5260   case ISD::VP_REDUCE_FADD:
5261     return RISCVISD::VECREDUCE_FADD_VL;
5262   case ISD::VP_REDUCE_SEQ_FADD:
5263     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5264   case ISD::VP_REDUCE_FMAX:
5265     return RISCVISD::VECREDUCE_FMAX_VL;
5266   case ISD::VP_REDUCE_FMIN:
5267     return RISCVISD::VECREDUCE_FMIN_VL;
5268   }
5269 }
5270 
5271 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5272                                            SelectionDAG &DAG) const {
5273   SDLoc DL(Op);
5274   SDValue Vec = Op.getOperand(1);
5275   EVT VecEVT = Vec.getValueType();
5276 
5277   // TODO: The type may need to be widened rather than split. Or widened before
5278   // it can be split.
5279   if (!isTypeLegal(VecEVT))
5280     return SDValue();
5281 
5282   MVT VecVT = VecEVT.getSimpleVT();
5283   MVT VecEltVT = VecVT.getVectorElementType();
5284   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5285 
5286   MVT ContainerVT = VecVT;
5287   if (VecVT.isFixedLengthVector()) {
5288     ContainerVT = getContainerForFixedLengthVector(VecVT);
5289     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5290   }
5291 
5292   SDValue VL = Op.getOperand(3);
5293   SDValue Mask = Op.getOperand(2);
5294 
5295   MVT M1VT = getLMUL1VT(ContainerVT);
5296   MVT XLenVT = Subtarget.getXLenVT();
5297   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5298 
5299   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5300                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5301                                         DL, DAG, Subtarget);
5302   SDValue Reduction =
5303       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5304   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5305                              DAG.getConstant(0, DL, XLenVT));
5306   if (!VecVT.isInteger())
5307     return Elt0;
5308   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5309 }
5310 
5311 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5312                                                    SelectionDAG &DAG) const {
5313   SDValue Vec = Op.getOperand(0);
5314   SDValue SubVec = Op.getOperand(1);
5315   MVT VecVT = Vec.getSimpleValueType();
5316   MVT SubVecVT = SubVec.getSimpleValueType();
5317 
5318   SDLoc DL(Op);
5319   MVT XLenVT = Subtarget.getXLenVT();
5320   unsigned OrigIdx = Op.getConstantOperandVal(2);
5321   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5322 
5323   // We don't have the ability to slide mask vectors up indexed by their i1
5324   // elements; the smallest we can do is i8. Often we are able to bitcast to
5325   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5326   // into a scalable one, we might not necessarily have enough scalable
5327   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5328   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5329       (OrigIdx != 0 || !Vec.isUndef())) {
5330     if (VecVT.getVectorMinNumElements() >= 8 &&
5331         SubVecVT.getVectorMinNumElements() >= 8) {
5332       assert(OrigIdx % 8 == 0 && "Invalid index");
5333       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5334              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5335              "Unexpected mask vector lowering");
5336       OrigIdx /= 8;
5337       SubVecVT =
5338           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5339                            SubVecVT.isScalableVector());
5340       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5341                                VecVT.isScalableVector());
5342       Vec = DAG.getBitcast(VecVT, Vec);
5343       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5344     } else {
5345       // We can't slide this mask vector up indexed by its i1 elements.
5346       // This poses a problem when we wish to insert a scalable vector which
5347       // can't be re-expressed as a larger type. Just choose the slow path and
5348       // extend to a larger type, then truncate back down.
5349       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5350       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5351       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5352       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5353       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5354                         Op.getOperand(2));
5355       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5356       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5357     }
5358   }
5359 
5360   // If the subvector vector is a fixed-length type, we cannot use subregister
5361   // manipulation to simplify the codegen; we don't know which register of a
5362   // LMUL group contains the specific subvector as we only know the minimum
5363   // register size. Therefore we must slide the vector group up the full
5364   // amount.
5365   if (SubVecVT.isFixedLengthVector()) {
5366     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5367       return Op;
5368     MVT ContainerVT = VecVT;
5369     if (VecVT.isFixedLengthVector()) {
5370       ContainerVT = getContainerForFixedLengthVector(VecVT);
5371       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5372     }
5373     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5374                          DAG.getUNDEF(ContainerVT), SubVec,
5375                          DAG.getConstant(0, DL, XLenVT));
5376     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5377       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5378       return DAG.getBitcast(Op.getValueType(), SubVec);
5379     }
5380     SDValue Mask =
5381         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5382     // Set the vector length to only the number of elements we care about. Note
5383     // that for slideup this includes the offset.
5384     SDValue VL =
5385         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5386     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5387     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5388                                   SubVec, SlideupAmt, Mask, VL);
5389     if (VecVT.isFixedLengthVector())
5390       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5391     return DAG.getBitcast(Op.getValueType(), Slideup);
5392   }
5393 
5394   unsigned SubRegIdx, RemIdx;
5395   std::tie(SubRegIdx, RemIdx) =
5396       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5397           VecVT, SubVecVT, OrigIdx, TRI);
5398 
5399   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5400   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5401                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5402                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5403 
5404   // 1. If the Idx has been completely eliminated and this subvector's size is
5405   // a vector register or a multiple thereof, or the surrounding elements are
5406   // undef, then this is a subvector insert which naturally aligns to a vector
5407   // register. These can easily be handled using subregister manipulation.
5408   // 2. If the subvector is smaller than a vector register, then the insertion
5409   // must preserve the undisturbed elements of the register. We do this by
5410   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5411   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5412   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5413   // LMUL=1 type back into the larger vector (resolving to another subregister
5414   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5415   // to avoid allocating a large register group to hold our subvector.
5416   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5417     return Op;
5418 
5419   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5420   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5421   // (in our case undisturbed). This means we can set up a subvector insertion
5422   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5423   // size of the subvector.
5424   MVT InterSubVT = VecVT;
5425   SDValue AlignedExtract = Vec;
5426   unsigned AlignedIdx = OrigIdx - RemIdx;
5427   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5428     InterSubVT = getLMUL1VT(VecVT);
5429     // Extract a subvector equal to the nearest full vector register type. This
5430     // should resolve to a EXTRACT_SUBREG instruction.
5431     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5432                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5433   }
5434 
5435   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5436   // For scalable vectors this must be further multiplied by vscale.
5437   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5438 
5439   SDValue Mask, VL;
5440   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5441 
5442   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5443   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5444   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5445   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5446 
5447   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5448                        DAG.getUNDEF(InterSubVT), SubVec,
5449                        DAG.getConstant(0, DL, XLenVT));
5450 
5451   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5452                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5453 
5454   // If required, insert this subvector back into the correct vector register.
5455   // This should resolve to an INSERT_SUBREG instruction.
5456   if (VecVT.bitsGT(InterSubVT))
5457     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5458                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5459 
5460   // We might have bitcast from a mask type: cast back to the original type if
5461   // required.
5462   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5463 }
5464 
5465 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5466                                                     SelectionDAG &DAG) const {
5467   SDValue Vec = Op.getOperand(0);
5468   MVT SubVecVT = Op.getSimpleValueType();
5469   MVT VecVT = Vec.getSimpleValueType();
5470 
5471   SDLoc DL(Op);
5472   MVT XLenVT = Subtarget.getXLenVT();
5473   unsigned OrigIdx = Op.getConstantOperandVal(1);
5474   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5475 
5476   // We don't have the ability to slide mask vectors down indexed by their i1
5477   // elements; the smallest we can do is i8. Often we are able to bitcast to
5478   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5479   // from a scalable one, we might not necessarily have enough scalable
5480   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5481   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5482     if (VecVT.getVectorMinNumElements() >= 8 &&
5483         SubVecVT.getVectorMinNumElements() >= 8) {
5484       assert(OrigIdx % 8 == 0 && "Invalid index");
5485       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5486              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5487              "Unexpected mask vector lowering");
5488       OrigIdx /= 8;
5489       SubVecVT =
5490           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5491                            SubVecVT.isScalableVector());
5492       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5493                                VecVT.isScalableVector());
5494       Vec = DAG.getBitcast(VecVT, Vec);
5495     } else {
5496       // We can't slide this mask vector down, indexed by its i1 elements.
5497       // This poses a problem when we wish to extract a scalable vector which
5498       // can't be re-expressed as a larger type. Just choose the slow path and
5499       // extend to a larger type, then truncate back down.
5500       // TODO: We could probably improve this when extracting certain fixed
5501       // from fixed, where we can extract as i8 and shift the correct element
5502       // right to reach the desired subvector?
5503       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5504       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5505       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5506       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5507                         Op.getOperand(1));
5508       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5509       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5510     }
5511   }
5512 
5513   // If the subvector vector is a fixed-length type, we cannot use subregister
5514   // manipulation to simplify the codegen; we don't know which register of a
5515   // LMUL group contains the specific subvector as we only know the minimum
5516   // register size. Therefore we must slide the vector group down the full
5517   // amount.
5518   if (SubVecVT.isFixedLengthVector()) {
5519     // With an index of 0 this is a cast-like subvector, which can be performed
5520     // with subregister operations.
5521     if (OrigIdx == 0)
5522       return Op;
5523     MVT ContainerVT = VecVT;
5524     if (VecVT.isFixedLengthVector()) {
5525       ContainerVT = getContainerForFixedLengthVector(VecVT);
5526       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5527     }
5528     SDValue Mask =
5529         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5530     // Set the vector length to only the number of elements we care about. This
5531     // avoids sliding down elements we're going to discard straight away.
5532     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5533     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5534     SDValue Slidedown =
5535         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5536                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5537     // Now we can use a cast-like subvector extract to get the result.
5538     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5539                             DAG.getConstant(0, DL, XLenVT));
5540     return DAG.getBitcast(Op.getValueType(), Slidedown);
5541   }
5542 
5543   unsigned SubRegIdx, RemIdx;
5544   std::tie(SubRegIdx, RemIdx) =
5545       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5546           VecVT, SubVecVT, OrigIdx, TRI);
5547 
5548   // If the Idx has been completely eliminated then this is a subvector extract
5549   // which naturally aligns to a vector register. These can easily be handled
5550   // using subregister manipulation.
5551   if (RemIdx == 0)
5552     return Op;
5553 
5554   // Else we must shift our vector register directly to extract the subvector.
5555   // Do this using VSLIDEDOWN.
5556 
5557   // If the vector type is an LMUL-group type, extract a subvector equal to the
5558   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5559   // instruction.
5560   MVT InterSubVT = VecVT;
5561   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5562     InterSubVT = getLMUL1VT(VecVT);
5563     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5564                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5565   }
5566 
5567   // Slide this vector register down by the desired number of elements in order
5568   // to place the desired subvector starting at element 0.
5569   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5570   // For scalable vectors this must be further multiplied by vscale.
5571   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5572 
5573   SDValue Mask, VL;
5574   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5575   SDValue Slidedown =
5576       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5577                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5578 
5579   // Now the vector is in the right position, extract our final subvector. This
5580   // should resolve to a COPY.
5581   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5582                           DAG.getConstant(0, DL, XLenVT));
5583 
5584   // We might have bitcast from a mask type: cast back to the original type if
5585   // required.
5586   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5587 }
5588 
5589 // Lower step_vector to the vid instruction. Any non-identity step value must
5590 // be accounted for my manual expansion.
5591 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5592                                               SelectionDAG &DAG) const {
5593   SDLoc DL(Op);
5594   MVT VT = Op.getSimpleValueType();
5595   MVT XLenVT = Subtarget.getXLenVT();
5596   SDValue Mask, VL;
5597   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5598   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5599   uint64_t StepValImm = Op.getConstantOperandVal(0);
5600   if (StepValImm != 1) {
5601     if (isPowerOf2_64(StepValImm)) {
5602       SDValue StepVal =
5603           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5604                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5605       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5606     } else {
5607       SDValue StepVal = lowerScalarSplat(
5608           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5609           VL, VT, DL, DAG, Subtarget);
5610       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5611     }
5612   }
5613   return StepVec;
5614 }
5615 
5616 // Implement vector_reverse using vrgather.vv with indices determined by
5617 // subtracting the id of each element from (VLMAX-1). This will convert
5618 // the indices like so:
5619 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5620 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5621 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5622                                                  SelectionDAG &DAG) const {
5623   SDLoc DL(Op);
5624   MVT VecVT = Op.getSimpleValueType();
5625   unsigned EltSize = VecVT.getScalarSizeInBits();
5626   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5627 
5628   unsigned MaxVLMAX = 0;
5629   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5630   if (VectorBitsMax != 0)
5631     MaxVLMAX =
5632         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5633 
5634   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5635   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5636 
5637   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5638   // to use vrgatherei16.vv.
5639   // TODO: It's also possible to use vrgatherei16.vv for other types to
5640   // decrease register width for the index calculation.
5641   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5642     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5643     // Reverse each half, then reassemble them in reverse order.
5644     // NOTE: It's also possible that after splitting that VLMAX no longer
5645     // requires vrgatherei16.vv.
5646     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5647       SDValue Lo, Hi;
5648       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5649       EVT LoVT, HiVT;
5650       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5651       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5652       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5653       // Reassemble the low and high pieces reversed.
5654       // FIXME: This is a CONCAT_VECTORS.
5655       SDValue Res =
5656           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5657                       DAG.getIntPtrConstant(0, DL));
5658       return DAG.getNode(
5659           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5660           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5661     }
5662 
5663     // Just promote the int type to i16 which will double the LMUL.
5664     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5665     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5666   }
5667 
5668   MVT XLenVT = Subtarget.getXLenVT();
5669   SDValue Mask, VL;
5670   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5671 
5672   // Calculate VLMAX-1 for the desired SEW.
5673   unsigned MinElts = VecVT.getVectorMinNumElements();
5674   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5675                               DAG.getConstant(MinElts, DL, XLenVT));
5676   SDValue VLMinus1 =
5677       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5678 
5679   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5680   bool IsRV32E64 =
5681       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5682   SDValue SplatVL;
5683   if (!IsRV32E64)
5684     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5685   else
5686     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5687                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5688 
5689   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5690   SDValue Indices =
5691       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5692 
5693   return DAG.getNode(GatherOpc, DL, VecVT, DAG.getUNDEF(VecVT),
5694                      Op.getOperand(0), Indices, Mask, VL);
5695 }
5696 
5697 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5698                                                 SelectionDAG &DAG) const {
5699   SDLoc DL(Op);
5700   SDValue V1 = Op.getOperand(0);
5701   SDValue V2 = Op.getOperand(1);
5702   MVT XLenVT = Subtarget.getXLenVT();
5703   MVT VecVT = Op.getSimpleValueType();
5704 
5705   unsigned MinElts = VecVT.getVectorMinNumElements();
5706   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5707                               DAG.getConstant(MinElts, DL, XLenVT));
5708 
5709   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5710   SDValue DownOffset, UpOffset;
5711   if (ImmValue >= 0) {
5712     // The operand is a TargetConstant, we need to rebuild it as a regular
5713     // constant.
5714     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5715     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5716   } else {
5717     // The operand is a TargetConstant, we need to rebuild it as a regular
5718     // constant rather than negating the original operand.
5719     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5720     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5721   }
5722 
5723   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5724 
5725   SDValue SlideDown =
5726       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5727                   DownOffset, TrueMask, UpOffset);
5728   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5729                      TrueMask,
5730                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5731 }
5732 
5733 SDValue
5734 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5735                                                      SelectionDAG &DAG) const {
5736   SDLoc DL(Op);
5737   auto *Load = cast<LoadSDNode>(Op);
5738 
5739   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5740                                         Load->getMemoryVT(),
5741                                         *Load->getMemOperand()) &&
5742          "Expecting a correctly-aligned load");
5743 
5744   MVT VT = Op.getSimpleValueType();
5745   MVT XLenVT = Subtarget.getXLenVT();
5746   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5747 
5748   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5749 
5750   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5751   SDValue IntID = DAG.getTargetConstant(
5752       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5753   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5754   if (!IsMaskOp)
5755     Ops.push_back(DAG.getUNDEF(ContainerVT));
5756   Ops.push_back(Load->getBasePtr());
5757   Ops.push_back(VL);
5758   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5759   SDValue NewLoad =
5760       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5761                               Load->getMemoryVT(), Load->getMemOperand());
5762 
5763   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5764   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5765 }
5766 
5767 SDValue
5768 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5769                                                       SelectionDAG &DAG) const {
5770   SDLoc DL(Op);
5771   auto *Store = cast<StoreSDNode>(Op);
5772 
5773   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5774                                         Store->getMemoryVT(),
5775                                         *Store->getMemOperand()) &&
5776          "Expecting a correctly-aligned store");
5777 
5778   SDValue StoreVal = Store->getValue();
5779   MVT VT = StoreVal.getSimpleValueType();
5780   MVT XLenVT = Subtarget.getXLenVT();
5781 
5782   // If the size less than a byte, we need to pad with zeros to make a byte.
5783   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5784     VT = MVT::v8i1;
5785     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5786                            DAG.getConstant(0, DL, VT), StoreVal,
5787                            DAG.getIntPtrConstant(0, DL));
5788   }
5789 
5790   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5791 
5792   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5793 
5794   SDValue NewValue =
5795       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5796 
5797   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5798   SDValue IntID = DAG.getTargetConstant(
5799       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5800   return DAG.getMemIntrinsicNode(
5801       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5802       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5803       Store->getMemoryVT(), Store->getMemOperand());
5804 }
5805 
5806 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5807                                              SelectionDAG &DAG) const {
5808   SDLoc DL(Op);
5809   MVT VT = Op.getSimpleValueType();
5810 
5811   const auto *MemSD = cast<MemSDNode>(Op);
5812   EVT MemVT = MemSD->getMemoryVT();
5813   MachineMemOperand *MMO = MemSD->getMemOperand();
5814   SDValue Chain = MemSD->getChain();
5815   SDValue BasePtr = MemSD->getBasePtr();
5816 
5817   SDValue Mask, PassThru, VL;
5818   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5819     Mask = VPLoad->getMask();
5820     PassThru = DAG.getUNDEF(VT);
5821     VL = VPLoad->getVectorLength();
5822   } else {
5823     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5824     Mask = MLoad->getMask();
5825     PassThru = MLoad->getPassThru();
5826   }
5827 
5828   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5829 
5830   MVT XLenVT = Subtarget.getXLenVT();
5831 
5832   MVT ContainerVT = VT;
5833   if (VT.isFixedLengthVector()) {
5834     ContainerVT = getContainerForFixedLengthVector(VT);
5835     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5836     if (!IsUnmasked) {
5837       MVT MaskVT = getMaskTypeFor(ContainerVT);
5838       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5839     }
5840   }
5841 
5842   if (!VL)
5843     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5844 
5845   unsigned IntID =
5846       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5847   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5848   if (IsUnmasked)
5849     Ops.push_back(DAG.getUNDEF(ContainerVT));
5850   else
5851     Ops.push_back(PassThru);
5852   Ops.push_back(BasePtr);
5853   if (!IsUnmasked)
5854     Ops.push_back(Mask);
5855   Ops.push_back(VL);
5856   if (!IsUnmasked)
5857     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5858 
5859   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5860 
5861   SDValue Result =
5862       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5863   Chain = Result.getValue(1);
5864 
5865   if (VT.isFixedLengthVector())
5866     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5867 
5868   return DAG.getMergeValues({Result, Chain}, DL);
5869 }
5870 
5871 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5872                                               SelectionDAG &DAG) const {
5873   SDLoc DL(Op);
5874 
5875   const auto *MemSD = cast<MemSDNode>(Op);
5876   EVT MemVT = MemSD->getMemoryVT();
5877   MachineMemOperand *MMO = MemSD->getMemOperand();
5878   SDValue Chain = MemSD->getChain();
5879   SDValue BasePtr = MemSD->getBasePtr();
5880   SDValue Val, Mask, VL;
5881 
5882   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5883     Val = VPStore->getValue();
5884     Mask = VPStore->getMask();
5885     VL = VPStore->getVectorLength();
5886   } else {
5887     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5888     Val = MStore->getValue();
5889     Mask = MStore->getMask();
5890   }
5891 
5892   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5893 
5894   MVT VT = Val.getSimpleValueType();
5895   MVT XLenVT = Subtarget.getXLenVT();
5896 
5897   MVT ContainerVT = VT;
5898   if (VT.isFixedLengthVector()) {
5899     ContainerVT = getContainerForFixedLengthVector(VT);
5900 
5901     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5902     if (!IsUnmasked) {
5903       MVT MaskVT = getMaskTypeFor(ContainerVT);
5904       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5905     }
5906   }
5907 
5908   if (!VL)
5909     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5910 
5911   unsigned IntID =
5912       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5913   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5914   Ops.push_back(Val);
5915   Ops.push_back(BasePtr);
5916   if (!IsUnmasked)
5917     Ops.push_back(Mask);
5918   Ops.push_back(VL);
5919 
5920   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5921                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5922 }
5923 
5924 SDValue
5925 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5926                                                       SelectionDAG &DAG) const {
5927   MVT InVT = Op.getOperand(0).getSimpleValueType();
5928   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5929 
5930   MVT VT = Op.getSimpleValueType();
5931 
5932   SDValue Op1 =
5933       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5934   SDValue Op2 =
5935       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5936 
5937   SDLoc DL(Op);
5938   SDValue VL =
5939       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5940 
5941   MVT MaskVT = getMaskTypeFor(ContainerVT);
5942   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
5943 
5944   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5945                             Op.getOperand(2), Mask, VL);
5946 
5947   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5948 }
5949 
5950 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5951     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5952   MVT VT = Op.getSimpleValueType();
5953 
5954   if (VT.getVectorElementType() == MVT::i1)
5955     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5956 
5957   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5958 }
5959 
5960 SDValue
5961 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5962                                                       SelectionDAG &DAG) const {
5963   unsigned Opc;
5964   switch (Op.getOpcode()) {
5965   default: llvm_unreachable("Unexpected opcode!");
5966   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5967   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5968   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5969   }
5970 
5971   return lowerToScalableOp(Op, DAG, Opc);
5972 }
5973 
5974 // Lower vector ABS to smax(X, sub(0, X)).
5975 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5976   SDLoc DL(Op);
5977   MVT VT = Op.getSimpleValueType();
5978   SDValue X = Op.getOperand(0);
5979 
5980   assert(VT.isFixedLengthVector() && "Unexpected type");
5981 
5982   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5983   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5984 
5985   SDValue Mask, VL;
5986   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5987 
5988   SDValue SplatZero = DAG.getNode(
5989       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5990       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5991   SDValue NegX =
5992       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5993   SDValue Max =
5994       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5995 
5996   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5997 }
5998 
5999 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6000     SDValue Op, SelectionDAG &DAG) const {
6001   SDLoc DL(Op);
6002   MVT VT = Op.getSimpleValueType();
6003   SDValue Mag = Op.getOperand(0);
6004   SDValue Sign = Op.getOperand(1);
6005   assert(Mag.getValueType() == Sign.getValueType() &&
6006          "Can only handle COPYSIGN with matching types.");
6007 
6008   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6009   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6010   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6011 
6012   SDValue Mask, VL;
6013   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6014 
6015   SDValue CopySign =
6016       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6017 
6018   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6019 }
6020 
6021 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6022     SDValue Op, SelectionDAG &DAG) const {
6023   MVT VT = Op.getSimpleValueType();
6024   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6025 
6026   MVT I1ContainerVT =
6027       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6028 
6029   SDValue CC =
6030       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6031   SDValue Op1 =
6032       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6033   SDValue Op2 =
6034       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6035 
6036   SDLoc DL(Op);
6037   SDValue Mask, VL;
6038   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6039 
6040   SDValue Select =
6041       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6042 
6043   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6044 }
6045 
6046 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6047                                                unsigned NewOpc,
6048                                                bool HasMask) const {
6049   MVT VT = Op.getSimpleValueType();
6050   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6051 
6052   // Create list of operands by converting existing ones to scalable types.
6053   SmallVector<SDValue, 6> Ops;
6054   for (const SDValue &V : Op->op_values()) {
6055     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6056 
6057     // Pass through non-vector operands.
6058     if (!V.getValueType().isVector()) {
6059       Ops.push_back(V);
6060       continue;
6061     }
6062 
6063     // "cast" fixed length vector to a scalable vector.
6064     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6065            "Only fixed length vectors are supported!");
6066     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6067   }
6068 
6069   SDLoc DL(Op);
6070   SDValue Mask, VL;
6071   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6072   if (HasMask)
6073     Ops.push_back(Mask);
6074   Ops.push_back(VL);
6075 
6076   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6077   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6078 }
6079 
6080 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6081 // * Operands of each node are assumed to be in the same order.
6082 // * The EVL operand is promoted from i32 to i64 on RV64.
6083 // * Fixed-length vectors are converted to their scalable-vector container
6084 //   types.
6085 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6086                                        unsigned RISCVISDOpc) const {
6087   SDLoc DL(Op);
6088   MVT VT = Op.getSimpleValueType();
6089   SmallVector<SDValue, 4> Ops;
6090 
6091   for (const auto &OpIdx : enumerate(Op->ops())) {
6092     SDValue V = OpIdx.value();
6093     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6094     // Pass through operands which aren't fixed-length vectors.
6095     if (!V.getValueType().isFixedLengthVector()) {
6096       Ops.push_back(V);
6097       continue;
6098     }
6099     // "cast" fixed length vector to a scalable vector.
6100     MVT OpVT = V.getSimpleValueType();
6101     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6102     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6103            "Only fixed length vectors are supported!");
6104     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6105   }
6106 
6107   if (!VT.isFixedLengthVector())
6108     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6109 
6110   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6111 
6112   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6113 
6114   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6115 }
6116 
6117 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6118                                               SelectionDAG &DAG) const {
6119   SDLoc DL(Op);
6120   MVT VT = Op.getSimpleValueType();
6121 
6122   SDValue Src = Op.getOperand(0);
6123   // NOTE: Mask is dropped.
6124   SDValue VL = Op.getOperand(2);
6125 
6126   MVT ContainerVT = VT;
6127   if (VT.isFixedLengthVector()) {
6128     ContainerVT = getContainerForFixedLengthVector(VT);
6129     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6130     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6131   }
6132 
6133   MVT XLenVT = Subtarget.getXLenVT();
6134   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6135   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6136                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6137 
6138   SDValue SplatValue = DAG.getConstant(
6139       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6140   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6141                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6142 
6143   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6144                                Splat, ZeroSplat, VL);
6145   if (!VT.isFixedLengthVector())
6146     return Result;
6147   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6148 }
6149 
6150 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6151                                                 SelectionDAG &DAG) const {
6152   SDLoc DL(Op);
6153   MVT VT = Op.getSimpleValueType();
6154 
6155   SDValue Op1 = Op.getOperand(0);
6156   SDValue Op2 = Op.getOperand(1);
6157   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6158   // NOTE: Mask is dropped.
6159   SDValue VL = Op.getOperand(4);
6160 
6161   MVT ContainerVT = VT;
6162   if (VT.isFixedLengthVector()) {
6163     ContainerVT = getContainerForFixedLengthVector(VT);
6164     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6165     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6166   }
6167 
6168   SDValue Result;
6169   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6170 
6171   switch (Condition) {
6172   default:
6173     break;
6174   // X != Y  --> (X^Y)
6175   case ISD::SETNE:
6176     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6177     break;
6178   // X == Y  --> ~(X^Y)
6179   case ISD::SETEQ: {
6180     SDValue Temp =
6181         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6182     Result =
6183         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6184     break;
6185   }
6186   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6187   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6188   case ISD::SETGT:
6189   case ISD::SETULT: {
6190     SDValue Temp =
6191         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6192     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6193     break;
6194   }
6195   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6196   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6197   case ISD::SETLT:
6198   case ISD::SETUGT: {
6199     SDValue Temp =
6200         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6201     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6202     break;
6203   }
6204   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6205   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6206   case ISD::SETGE:
6207   case ISD::SETULE: {
6208     SDValue Temp =
6209         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6210     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6211     break;
6212   }
6213   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6214   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6215   case ISD::SETLE:
6216   case ISD::SETUGE: {
6217     SDValue Temp =
6218         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6219     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6220     break;
6221   }
6222   }
6223 
6224   if (!VT.isFixedLengthVector())
6225     return Result;
6226   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6227 }
6228 
6229 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6230 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6231                                                 unsigned RISCVISDOpc) const {
6232   SDLoc DL(Op);
6233 
6234   SDValue Src = Op.getOperand(0);
6235   SDValue Mask = Op.getOperand(1);
6236   SDValue VL = Op.getOperand(2);
6237 
6238   MVT DstVT = Op.getSimpleValueType();
6239   MVT SrcVT = Src.getSimpleValueType();
6240   if (DstVT.isFixedLengthVector()) {
6241     DstVT = getContainerForFixedLengthVector(DstVT);
6242     SrcVT = getContainerForFixedLengthVector(SrcVT);
6243     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6244     MVT MaskVT = getMaskTypeFor(DstVT);
6245     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6246   }
6247 
6248   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6249                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6250                                 ? RISCVISD::VSEXT_VL
6251                                 : RISCVISD::VZEXT_VL;
6252 
6253   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6254   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6255 
6256   SDValue Result;
6257   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6258     if (SrcVT.isInteger()) {
6259       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6260 
6261       // Do we need to do any pre-widening before converting?
6262       if (SrcEltSize == 1) {
6263         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6264         MVT XLenVT = Subtarget.getXLenVT();
6265         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6266         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6267                                         DAG.getUNDEF(IntVT), Zero, VL);
6268         SDValue One = DAG.getConstant(
6269             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6270         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6271                                        DAG.getUNDEF(IntVT), One, VL);
6272         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6273                           ZeroSplat, VL);
6274       } else if (DstEltSize > (2 * SrcEltSize)) {
6275         // Widen before converting.
6276         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6277                                      DstVT.getVectorElementCount());
6278         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6279       }
6280 
6281       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6282     } else {
6283       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6284              "Wrong input/output vector types");
6285 
6286       // Convert f16 to f32 then convert f32 to i64.
6287       if (DstEltSize > (2 * SrcEltSize)) {
6288         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6289         MVT InterimFVT =
6290             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6291         Src =
6292             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6293       }
6294 
6295       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6296     }
6297   } else { // Narrowing + Conversion
6298     if (SrcVT.isInteger()) {
6299       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6300       // First do a narrowing convert to an FP type half the size, then round
6301       // the FP type to a small FP type if needed.
6302 
6303       MVT InterimFVT = DstVT;
6304       if (SrcEltSize > (2 * DstEltSize)) {
6305         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6306         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6307         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6308       }
6309 
6310       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6311 
6312       if (InterimFVT != DstVT) {
6313         Src = Result;
6314         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6315       }
6316     } else {
6317       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6318              "Wrong input/output vector types");
6319       // First do a narrowing conversion to an integer half the size, then
6320       // truncate if needed.
6321 
6322       if (DstEltSize == 1) {
6323         // First convert to the same size integer, then convert to mask using
6324         // setcc.
6325         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6326         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6327                                           DstVT.getVectorElementCount());
6328         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6329 
6330         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6331         // otherwise the conversion was undefined.
6332         MVT XLenVT = Subtarget.getXLenVT();
6333         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6334         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6335                                 DAG.getUNDEF(InterimIVT), SplatZero);
6336         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6337                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6338       } else {
6339         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6340                                           DstVT.getVectorElementCount());
6341 
6342         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6343 
6344         while (InterimIVT != DstVT) {
6345           SrcEltSize /= 2;
6346           Src = Result;
6347           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6348                                         DstVT.getVectorElementCount());
6349           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6350                                Src, Mask, VL);
6351         }
6352       }
6353     }
6354   }
6355 
6356   MVT VT = Op.getSimpleValueType();
6357   if (!VT.isFixedLengthVector())
6358     return Result;
6359   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6360 }
6361 
6362 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6363                                             unsigned MaskOpc,
6364                                             unsigned VecOpc) const {
6365   MVT VT = Op.getSimpleValueType();
6366   if (VT.getVectorElementType() != MVT::i1)
6367     return lowerVPOp(Op, DAG, VecOpc);
6368 
6369   // It is safe to drop mask parameter as masked-off elements are undef.
6370   SDValue Op1 = Op->getOperand(0);
6371   SDValue Op2 = Op->getOperand(1);
6372   SDValue VL = Op->getOperand(3);
6373 
6374   MVT ContainerVT = VT;
6375   const bool IsFixed = VT.isFixedLengthVector();
6376   if (IsFixed) {
6377     ContainerVT = getContainerForFixedLengthVector(VT);
6378     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6379     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6380   }
6381 
6382   SDLoc DL(Op);
6383   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6384   if (!IsFixed)
6385     return Val;
6386   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6387 }
6388 
6389 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6390 // matched to a RVV indexed load. The RVV indexed load instructions only
6391 // support the "unsigned unscaled" addressing mode; indices are implicitly
6392 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6393 // signed or scaled indexing is extended to the XLEN value type and scaled
6394 // accordingly.
6395 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6396                                                SelectionDAG &DAG) const {
6397   SDLoc DL(Op);
6398   MVT VT = Op.getSimpleValueType();
6399 
6400   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6401   EVT MemVT = MemSD->getMemoryVT();
6402   MachineMemOperand *MMO = MemSD->getMemOperand();
6403   SDValue Chain = MemSD->getChain();
6404   SDValue BasePtr = MemSD->getBasePtr();
6405 
6406   ISD::LoadExtType LoadExtType;
6407   SDValue Index, Mask, PassThru, VL;
6408 
6409   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6410     Index = VPGN->getIndex();
6411     Mask = VPGN->getMask();
6412     PassThru = DAG.getUNDEF(VT);
6413     VL = VPGN->getVectorLength();
6414     // VP doesn't support extending loads.
6415     LoadExtType = ISD::NON_EXTLOAD;
6416   } else {
6417     // Else it must be a MGATHER.
6418     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6419     Index = MGN->getIndex();
6420     Mask = MGN->getMask();
6421     PassThru = MGN->getPassThru();
6422     LoadExtType = MGN->getExtensionType();
6423   }
6424 
6425   MVT IndexVT = Index.getSimpleValueType();
6426   MVT XLenVT = Subtarget.getXLenVT();
6427 
6428   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6429          "Unexpected VTs!");
6430   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6431   // Targets have to explicitly opt-in for extending vector loads.
6432   assert(LoadExtType == ISD::NON_EXTLOAD &&
6433          "Unexpected extending MGATHER/VP_GATHER");
6434   (void)LoadExtType;
6435 
6436   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6437   // the selection of the masked intrinsics doesn't do this for us.
6438   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6439 
6440   MVT ContainerVT = VT;
6441   if (VT.isFixedLengthVector()) {
6442     ContainerVT = getContainerForFixedLengthVector(VT);
6443     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6444                                ContainerVT.getVectorElementCount());
6445 
6446     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6447 
6448     if (!IsUnmasked) {
6449       MVT MaskVT = getMaskTypeFor(ContainerVT);
6450       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6451       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6452     }
6453   }
6454 
6455   if (!VL)
6456     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6457 
6458   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6459     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6460     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6461                                    VL);
6462     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6463                         TrueMask, VL);
6464   }
6465 
6466   unsigned IntID =
6467       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6468   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6469   if (IsUnmasked)
6470     Ops.push_back(DAG.getUNDEF(ContainerVT));
6471   else
6472     Ops.push_back(PassThru);
6473   Ops.push_back(BasePtr);
6474   Ops.push_back(Index);
6475   if (!IsUnmasked)
6476     Ops.push_back(Mask);
6477   Ops.push_back(VL);
6478   if (!IsUnmasked)
6479     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6480 
6481   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6482   SDValue Result =
6483       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6484   Chain = Result.getValue(1);
6485 
6486   if (VT.isFixedLengthVector())
6487     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6488 
6489   return DAG.getMergeValues({Result, Chain}, DL);
6490 }
6491 
6492 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6493 // matched to a RVV indexed store. The RVV indexed store instructions only
6494 // support the "unsigned unscaled" addressing mode; indices are implicitly
6495 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6496 // signed or scaled indexing is extended to the XLEN value type and scaled
6497 // accordingly.
6498 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6499                                                 SelectionDAG &DAG) const {
6500   SDLoc DL(Op);
6501   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6502   EVT MemVT = MemSD->getMemoryVT();
6503   MachineMemOperand *MMO = MemSD->getMemOperand();
6504   SDValue Chain = MemSD->getChain();
6505   SDValue BasePtr = MemSD->getBasePtr();
6506 
6507   bool IsTruncatingStore = false;
6508   SDValue Index, Mask, Val, VL;
6509 
6510   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6511     Index = VPSN->getIndex();
6512     Mask = VPSN->getMask();
6513     Val = VPSN->getValue();
6514     VL = VPSN->getVectorLength();
6515     // VP doesn't support truncating stores.
6516     IsTruncatingStore = false;
6517   } else {
6518     // Else it must be a MSCATTER.
6519     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6520     Index = MSN->getIndex();
6521     Mask = MSN->getMask();
6522     Val = MSN->getValue();
6523     IsTruncatingStore = MSN->isTruncatingStore();
6524   }
6525 
6526   MVT VT = Val.getSimpleValueType();
6527   MVT IndexVT = Index.getSimpleValueType();
6528   MVT XLenVT = Subtarget.getXLenVT();
6529 
6530   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6531          "Unexpected VTs!");
6532   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6533   // Targets have to explicitly opt-in for extending vector loads and
6534   // truncating vector stores.
6535   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6536   (void)IsTruncatingStore;
6537 
6538   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6539   // the selection of the masked intrinsics doesn't do this for us.
6540   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6541 
6542   MVT ContainerVT = VT;
6543   if (VT.isFixedLengthVector()) {
6544     ContainerVT = getContainerForFixedLengthVector(VT);
6545     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6546                                ContainerVT.getVectorElementCount());
6547 
6548     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6549     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6550 
6551     if (!IsUnmasked) {
6552       MVT MaskVT = getMaskTypeFor(ContainerVT);
6553       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6554     }
6555   }
6556 
6557   if (!VL)
6558     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6559 
6560   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6561     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6562     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6563                                    VL);
6564     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6565                         TrueMask, VL);
6566   }
6567 
6568   unsigned IntID =
6569       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6570   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6571   Ops.push_back(Val);
6572   Ops.push_back(BasePtr);
6573   Ops.push_back(Index);
6574   if (!IsUnmasked)
6575     Ops.push_back(Mask);
6576   Ops.push_back(VL);
6577 
6578   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6579                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6580 }
6581 
6582 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6583                                                SelectionDAG &DAG) const {
6584   const MVT XLenVT = Subtarget.getXLenVT();
6585   SDLoc DL(Op);
6586   SDValue Chain = Op->getOperand(0);
6587   SDValue SysRegNo = DAG.getTargetConstant(
6588       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6589   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6590   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6591 
6592   // Encoding used for rounding mode in RISCV differs from that used in
6593   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6594   // table, which consists of a sequence of 4-bit fields, each representing
6595   // corresponding FLT_ROUNDS mode.
6596   static const int Table =
6597       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6598       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6599       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6600       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6601       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6602 
6603   SDValue Shift =
6604       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6605   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6606                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6607   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6608                                DAG.getConstant(7, DL, XLenVT));
6609 
6610   return DAG.getMergeValues({Masked, Chain}, DL);
6611 }
6612 
6613 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6614                                                SelectionDAG &DAG) const {
6615   const MVT XLenVT = Subtarget.getXLenVT();
6616   SDLoc DL(Op);
6617   SDValue Chain = Op->getOperand(0);
6618   SDValue RMValue = Op->getOperand(1);
6619   SDValue SysRegNo = DAG.getTargetConstant(
6620       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6621 
6622   // Encoding used for rounding mode in RISCV differs from that used in
6623   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6624   // a table, which consists of a sequence of 4-bit fields, each representing
6625   // corresponding RISCV mode.
6626   static const unsigned Table =
6627       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6628       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6629       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6630       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6631       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6632 
6633   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6634                               DAG.getConstant(2, DL, XLenVT));
6635   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6636                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6637   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6638                         DAG.getConstant(0x7, DL, XLenVT));
6639   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6640                      RMValue);
6641 }
6642 
6643 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6644                                                SelectionDAG &DAG) const {
6645   MachineFunction &MF = DAG.getMachineFunction();
6646 
6647   bool isRISCV64 = Subtarget.is64Bit();
6648   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6649 
6650   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6651   return DAG.getFrameIndex(FI, PtrVT);
6652 }
6653 
6654 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6655   switch (IntNo) {
6656   default:
6657     llvm_unreachable("Unexpected Intrinsic");
6658   case Intrinsic::riscv_bcompress:
6659     return RISCVISD::BCOMPRESSW;
6660   case Intrinsic::riscv_bdecompress:
6661     return RISCVISD::BDECOMPRESSW;
6662   case Intrinsic::riscv_bfp:
6663     return RISCVISD::BFPW;
6664   case Intrinsic::riscv_fsl:
6665     return RISCVISD::FSLW;
6666   case Intrinsic::riscv_fsr:
6667     return RISCVISD::FSRW;
6668   }
6669 }
6670 
6671 // Converts the given intrinsic to a i64 operation with any extension.
6672 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6673                                          unsigned IntNo) {
6674   SDLoc DL(N);
6675   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6676   // Deal with the Instruction Operands
6677   SmallVector<SDValue, 3> NewOps;
6678   for (SDValue Op : drop_begin(N->ops()))
6679     // Promote the operand to i64 type
6680     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6681   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6682   // ReplaceNodeResults requires we maintain the same type for the return value.
6683   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6684 }
6685 
6686 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6687 // form of the given Opcode.
6688 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6689   switch (Opcode) {
6690   default:
6691     llvm_unreachable("Unexpected opcode");
6692   case ISD::SHL:
6693     return RISCVISD::SLLW;
6694   case ISD::SRA:
6695     return RISCVISD::SRAW;
6696   case ISD::SRL:
6697     return RISCVISD::SRLW;
6698   case ISD::SDIV:
6699     return RISCVISD::DIVW;
6700   case ISD::UDIV:
6701     return RISCVISD::DIVUW;
6702   case ISD::UREM:
6703     return RISCVISD::REMUW;
6704   case ISD::ROTL:
6705     return RISCVISD::ROLW;
6706   case ISD::ROTR:
6707     return RISCVISD::RORW;
6708   }
6709 }
6710 
6711 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6712 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6713 // otherwise be promoted to i64, making it difficult to select the
6714 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6715 // type i8/i16/i32 is lost.
6716 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6717                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6718   SDLoc DL(N);
6719   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6720   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6721   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6722   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6723   // ReplaceNodeResults requires we maintain the same type for the return value.
6724   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6725 }
6726 
6727 // Converts the given 32-bit operation to a i64 operation with signed extension
6728 // semantic to reduce the signed extension instructions.
6729 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6730   SDLoc DL(N);
6731   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6732   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6733   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6734   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6735                                DAG.getValueType(MVT::i32));
6736   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6737 }
6738 
6739 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6740                                              SmallVectorImpl<SDValue> &Results,
6741                                              SelectionDAG &DAG) const {
6742   SDLoc DL(N);
6743   switch (N->getOpcode()) {
6744   default:
6745     llvm_unreachable("Don't know how to custom type legalize this operation!");
6746   case ISD::STRICT_FP_TO_SINT:
6747   case ISD::STRICT_FP_TO_UINT:
6748   case ISD::FP_TO_SINT:
6749   case ISD::FP_TO_UINT: {
6750     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6751            "Unexpected custom legalisation");
6752     bool IsStrict = N->isStrictFPOpcode();
6753     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6754                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6755     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6756     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6757         TargetLowering::TypeSoftenFloat) {
6758       if (!isTypeLegal(Op0.getValueType()))
6759         return;
6760       if (IsStrict) {
6761         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6762                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6763         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6764         SDValue Res = DAG.getNode(
6765             Opc, DL, VTs, N->getOperand(0), Op0,
6766             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6767         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6768         Results.push_back(Res.getValue(1));
6769         return;
6770       }
6771       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6772       SDValue Res =
6773           DAG.getNode(Opc, DL, MVT::i64, Op0,
6774                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6775       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6776       return;
6777     }
6778     // If the FP type needs to be softened, emit a library call using the 'si'
6779     // version. If we left it to default legalization we'd end up with 'di'. If
6780     // the FP type doesn't need to be softened just let generic type
6781     // legalization promote the result type.
6782     RTLIB::Libcall LC;
6783     if (IsSigned)
6784       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6785     else
6786       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6787     MakeLibCallOptions CallOptions;
6788     EVT OpVT = Op0.getValueType();
6789     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6790     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6791     SDValue Result;
6792     std::tie(Result, Chain) =
6793         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6794     Results.push_back(Result);
6795     if (IsStrict)
6796       Results.push_back(Chain);
6797     break;
6798   }
6799   case ISD::READCYCLECOUNTER: {
6800     assert(!Subtarget.is64Bit() &&
6801            "READCYCLECOUNTER only has custom type legalization on riscv32");
6802 
6803     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6804     SDValue RCW =
6805         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6806 
6807     Results.push_back(
6808         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6809     Results.push_back(RCW.getValue(2));
6810     break;
6811   }
6812   case ISD::MUL: {
6813     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6814     unsigned XLen = Subtarget.getXLen();
6815     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6816     if (Size > XLen) {
6817       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6818       SDValue LHS = N->getOperand(0);
6819       SDValue RHS = N->getOperand(1);
6820       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6821 
6822       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6823       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6824       // We need exactly one side to be unsigned.
6825       if (LHSIsU == RHSIsU)
6826         return;
6827 
6828       auto MakeMULPair = [&](SDValue S, SDValue U) {
6829         MVT XLenVT = Subtarget.getXLenVT();
6830         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6831         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6832         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6833         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6834         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6835       };
6836 
6837       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6838       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6839 
6840       // The other operand should be signed, but still prefer MULH when
6841       // possible.
6842       if (RHSIsU && LHSIsS && !RHSIsS)
6843         Results.push_back(MakeMULPair(LHS, RHS));
6844       else if (LHSIsU && RHSIsS && !LHSIsS)
6845         Results.push_back(MakeMULPair(RHS, LHS));
6846 
6847       return;
6848     }
6849     LLVM_FALLTHROUGH;
6850   }
6851   case ISD::ADD:
6852   case ISD::SUB:
6853     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6854            "Unexpected custom legalisation");
6855     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6856     break;
6857   case ISD::SHL:
6858   case ISD::SRA:
6859   case ISD::SRL:
6860     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6861            "Unexpected custom legalisation");
6862     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6863       // If we can use a BSET instruction, allow default promotion to apply.
6864       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6865           isOneConstant(N->getOperand(0)))
6866         break;
6867       Results.push_back(customLegalizeToWOp(N, DAG));
6868       break;
6869     }
6870 
6871     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6872     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6873     // shift amount.
6874     if (N->getOpcode() == ISD::SHL) {
6875       SDLoc DL(N);
6876       SDValue NewOp0 =
6877           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6878       SDValue NewOp1 =
6879           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6880       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6881       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6882                                    DAG.getValueType(MVT::i32));
6883       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6884     }
6885 
6886     break;
6887   case ISD::ROTL:
6888   case ISD::ROTR:
6889     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6890            "Unexpected custom legalisation");
6891     Results.push_back(customLegalizeToWOp(N, DAG));
6892     break;
6893   case ISD::CTTZ:
6894   case ISD::CTTZ_ZERO_UNDEF:
6895   case ISD::CTLZ:
6896   case ISD::CTLZ_ZERO_UNDEF: {
6897     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6898            "Unexpected custom legalisation");
6899 
6900     SDValue NewOp0 =
6901         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6902     bool IsCTZ =
6903         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6904     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6905     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6906     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6907     return;
6908   }
6909   case ISD::SDIV:
6910   case ISD::UDIV:
6911   case ISD::UREM: {
6912     MVT VT = N->getSimpleValueType(0);
6913     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6914            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6915            "Unexpected custom legalisation");
6916     // Don't promote division/remainder by constant since we should expand those
6917     // to multiply by magic constant.
6918     // FIXME: What if the expansion is disabled for minsize.
6919     if (N->getOperand(1).getOpcode() == ISD::Constant)
6920       return;
6921 
6922     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6923     // the upper 32 bits. For other types we need to sign or zero extend
6924     // based on the opcode.
6925     unsigned ExtOpc = ISD::ANY_EXTEND;
6926     if (VT != MVT::i32)
6927       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6928                                            : ISD::ZERO_EXTEND;
6929 
6930     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6931     break;
6932   }
6933   case ISD::UADDO:
6934   case ISD::USUBO: {
6935     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6936            "Unexpected custom legalisation");
6937     bool IsAdd = N->getOpcode() == ISD::UADDO;
6938     // Create an ADDW or SUBW.
6939     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6940     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6941     SDValue Res =
6942         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6943     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6944                       DAG.getValueType(MVT::i32));
6945 
6946     SDValue Overflow;
6947     if (IsAdd && isOneConstant(RHS)) {
6948       // Special case uaddo X, 1 overflowed if the addition result is 0.
6949       // The general case (X + C) < C is not necessarily beneficial. Although we
6950       // reduce the live range of X, we may introduce the materialization of
6951       // constant C, especially when the setcc result is used by branch. We have
6952       // no compare with constant and branch instructions.
6953       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6954                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6955     } else {
6956       // Sign extend the LHS and perform an unsigned compare with the ADDW
6957       // result. Since the inputs are sign extended from i32, this is equivalent
6958       // to comparing the lower 32 bits.
6959       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6960       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6961                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6962     }
6963 
6964     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6965     Results.push_back(Overflow);
6966     return;
6967   }
6968   case ISD::UADDSAT:
6969   case ISD::USUBSAT: {
6970     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6971            "Unexpected custom legalisation");
6972     if (Subtarget.hasStdExtZbb()) {
6973       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6974       // sign extend allows overflow of the lower 32 bits to be detected on
6975       // the promoted size.
6976       SDValue LHS =
6977           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6978       SDValue RHS =
6979           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6980       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6981       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6982       return;
6983     }
6984 
6985     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6986     // promotion for UADDO/USUBO.
6987     Results.push_back(expandAddSubSat(N, DAG));
6988     return;
6989   }
6990   case ISD::ABS: {
6991     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6992            "Unexpected custom legalisation");
6993           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6994 
6995     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6996 
6997     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6998 
6999     // Freeze the source so we can increase it's use count.
7000     Src = DAG.getFreeze(Src);
7001 
7002     // Copy sign bit to all bits using the sraiw pattern.
7003     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7004                                    DAG.getValueType(MVT::i32));
7005     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7006                            DAG.getConstant(31, DL, MVT::i64));
7007 
7008     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7009     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7010 
7011     // NOTE: The result is only required to be anyextended, but sext is
7012     // consistent with type legalization of sub.
7013     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7014                          DAG.getValueType(MVT::i32));
7015     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7016     return;
7017   }
7018   case ISD::BITCAST: {
7019     EVT VT = N->getValueType(0);
7020     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7021     SDValue Op0 = N->getOperand(0);
7022     EVT Op0VT = Op0.getValueType();
7023     MVT XLenVT = Subtarget.getXLenVT();
7024     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7025       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7026       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7027     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7028                Subtarget.hasStdExtF()) {
7029       SDValue FPConv =
7030           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7031       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7032     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7033                isTypeLegal(Op0VT)) {
7034       // Custom-legalize bitcasts from fixed-length vector types to illegal
7035       // scalar types in order to improve codegen. Bitcast the vector to a
7036       // one-element vector type whose element type is the same as the result
7037       // type, and extract the first element.
7038       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7039       if (isTypeLegal(BVT)) {
7040         SDValue BVec = DAG.getBitcast(BVT, Op0);
7041         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7042                                       DAG.getConstant(0, DL, XLenVT)));
7043       }
7044     }
7045     break;
7046   }
7047   case RISCVISD::GREV:
7048   case RISCVISD::GORC:
7049   case RISCVISD::SHFL: {
7050     MVT VT = N->getSimpleValueType(0);
7051     MVT XLenVT = Subtarget.getXLenVT();
7052     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7053            "Unexpected custom legalisation");
7054     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7055     assert((Subtarget.hasStdExtZbp() ||
7056             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7057              N->getConstantOperandVal(1) == 7)) &&
7058            "Unexpected extension");
7059     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7060     SDValue NewOp1 =
7061         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7062     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7063     // ReplaceNodeResults requires we maintain the same type for the return
7064     // value.
7065     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7066     break;
7067   }
7068   case ISD::BSWAP:
7069   case ISD::BITREVERSE: {
7070     MVT VT = N->getSimpleValueType(0);
7071     MVT XLenVT = Subtarget.getXLenVT();
7072     assert((VT == MVT::i8 || VT == MVT::i16 ||
7073             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7074            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7075     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7076     unsigned Imm = VT.getSizeInBits() - 1;
7077     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7078     if (N->getOpcode() == ISD::BSWAP)
7079       Imm &= ~0x7U;
7080     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7081                                 DAG.getConstant(Imm, DL, XLenVT));
7082     // ReplaceNodeResults requires we maintain the same type for the return
7083     // value.
7084     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7085     break;
7086   }
7087   case ISD::FSHL:
7088   case ISD::FSHR: {
7089     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7090            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7091     SDValue NewOp0 =
7092         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7093     SDValue NewOp1 =
7094         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7095     SDValue NewShAmt =
7096         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7097     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7098     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7099     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7100                            DAG.getConstant(0x1f, DL, MVT::i64));
7101     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7102     // instruction use different orders. fshl will return its first operand for
7103     // shift of zero, fshr will return its second operand. fsl and fsr both
7104     // return rs1 so the ISD nodes need to have different operand orders.
7105     // Shift amount is in rs2.
7106     unsigned Opc = RISCVISD::FSLW;
7107     if (N->getOpcode() == ISD::FSHR) {
7108       std::swap(NewOp0, NewOp1);
7109       Opc = RISCVISD::FSRW;
7110     }
7111     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7112     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7113     break;
7114   }
7115   case ISD::EXTRACT_VECTOR_ELT: {
7116     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7117     // type is illegal (currently only vXi64 RV32).
7118     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7119     // transferred to the destination register. We issue two of these from the
7120     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7121     // first element.
7122     SDValue Vec = N->getOperand(0);
7123     SDValue Idx = N->getOperand(1);
7124 
7125     // The vector type hasn't been legalized yet so we can't issue target
7126     // specific nodes if it needs legalization.
7127     // FIXME: We would manually legalize if it's important.
7128     if (!isTypeLegal(Vec.getValueType()))
7129       return;
7130 
7131     MVT VecVT = Vec.getSimpleValueType();
7132 
7133     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7134            VecVT.getVectorElementType() == MVT::i64 &&
7135            "Unexpected EXTRACT_VECTOR_ELT legalization");
7136 
7137     // If this is a fixed vector, we need to convert it to a scalable vector.
7138     MVT ContainerVT = VecVT;
7139     if (VecVT.isFixedLengthVector()) {
7140       ContainerVT = getContainerForFixedLengthVector(VecVT);
7141       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7142     }
7143 
7144     MVT XLenVT = Subtarget.getXLenVT();
7145 
7146     // Use a VL of 1 to avoid processing more elements than we need.
7147     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7148     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7149 
7150     // Unless the index is known to be 0, we must slide the vector down to get
7151     // the desired element into index 0.
7152     if (!isNullConstant(Idx)) {
7153       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7154                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7155     }
7156 
7157     // Extract the lower XLEN bits of the correct vector element.
7158     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7159 
7160     // To extract the upper XLEN bits of the vector element, shift the first
7161     // element right by 32 bits and re-extract the lower XLEN bits.
7162     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7163                                      DAG.getUNDEF(ContainerVT),
7164                                      DAG.getConstant(32, DL, XLenVT), VL);
7165     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7166                                  ThirtyTwoV, Mask, VL);
7167 
7168     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7169 
7170     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7171     break;
7172   }
7173   case ISD::INTRINSIC_WO_CHAIN: {
7174     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7175     switch (IntNo) {
7176     default:
7177       llvm_unreachable(
7178           "Don't know how to custom type legalize this intrinsic!");
7179     case Intrinsic::riscv_grev:
7180     case Intrinsic::riscv_gorc: {
7181       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7182              "Unexpected custom legalisation");
7183       SDValue NewOp1 =
7184           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7185       SDValue NewOp2 =
7186           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7187       unsigned Opc =
7188           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7189       // If the control is a constant, promote the node by clearing any extra
7190       // bits bits in the control. isel will form greviw/gorciw if the result is
7191       // sign extended.
7192       if (isa<ConstantSDNode>(NewOp2)) {
7193         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7194                              DAG.getConstant(0x1f, DL, MVT::i64));
7195         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7196       }
7197       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7198       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7199       break;
7200     }
7201     case Intrinsic::riscv_bcompress:
7202     case Intrinsic::riscv_bdecompress:
7203     case Intrinsic::riscv_bfp:
7204     case Intrinsic::riscv_fsl:
7205     case Intrinsic::riscv_fsr: {
7206       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7207              "Unexpected custom legalisation");
7208       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7209       break;
7210     }
7211     case Intrinsic::riscv_orc_b: {
7212       // Lower to the GORCI encoding for orc.b with the operand extended.
7213       SDValue NewOp =
7214           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7215       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7216                                 DAG.getConstant(7, DL, MVT::i64));
7217       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7218       return;
7219     }
7220     case Intrinsic::riscv_shfl:
7221     case Intrinsic::riscv_unshfl: {
7222       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7223              "Unexpected custom legalisation");
7224       SDValue NewOp1 =
7225           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7226       SDValue NewOp2 =
7227           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7228       unsigned Opc =
7229           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7230       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7231       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7232       // will be shuffled the same way as the lower 32 bit half, but the two
7233       // halves won't cross.
7234       if (isa<ConstantSDNode>(NewOp2)) {
7235         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7236                              DAG.getConstant(0xf, DL, MVT::i64));
7237         Opc =
7238             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7239       }
7240       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7241       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7242       break;
7243     }
7244     case Intrinsic::riscv_vmv_x_s: {
7245       EVT VT = N->getValueType(0);
7246       MVT XLenVT = Subtarget.getXLenVT();
7247       if (VT.bitsLT(XLenVT)) {
7248         // Simple case just extract using vmv.x.s and truncate.
7249         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7250                                       Subtarget.getXLenVT(), N->getOperand(1));
7251         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7252         return;
7253       }
7254 
7255       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7256              "Unexpected custom legalization");
7257 
7258       // We need to do the move in two steps.
7259       SDValue Vec = N->getOperand(1);
7260       MVT VecVT = Vec.getSimpleValueType();
7261 
7262       // First extract the lower XLEN bits of the element.
7263       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7264 
7265       // To extract the upper XLEN bits of the vector element, shift the first
7266       // element right by 32 bits and re-extract the lower XLEN bits.
7267       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7268       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7269 
7270       SDValue ThirtyTwoV =
7271           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7272                       DAG.getConstant(32, DL, XLenVT), VL);
7273       SDValue LShr32 =
7274           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7275       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7276 
7277       Results.push_back(
7278           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7279       break;
7280     }
7281     }
7282     break;
7283   }
7284   case ISD::VECREDUCE_ADD:
7285   case ISD::VECREDUCE_AND:
7286   case ISD::VECREDUCE_OR:
7287   case ISD::VECREDUCE_XOR:
7288   case ISD::VECREDUCE_SMAX:
7289   case ISD::VECREDUCE_UMAX:
7290   case ISD::VECREDUCE_SMIN:
7291   case ISD::VECREDUCE_UMIN:
7292     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7293       Results.push_back(V);
7294     break;
7295   case ISD::VP_REDUCE_ADD:
7296   case ISD::VP_REDUCE_AND:
7297   case ISD::VP_REDUCE_OR:
7298   case ISD::VP_REDUCE_XOR:
7299   case ISD::VP_REDUCE_SMAX:
7300   case ISD::VP_REDUCE_UMAX:
7301   case ISD::VP_REDUCE_SMIN:
7302   case ISD::VP_REDUCE_UMIN:
7303     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7304       Results.push_back(V);
7305     break;
7306   case ISD::FLT_ROUNDS_: {
7307     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7308     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7309     Results.push_back(Res.getValue(0));
7310     Results.push_back(Res.getValue(1));
7311     break;
7312   }
7313   }
7314 }
7315 
7316 // A structure to hold one of the bit-manipulation patterns below. Together, a
7317 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7318 //   (or (and (shl x, 1), 0xAAAAAAAA),
7319 //       (and (srl x, 1), 0x55555555))
7320 struct RISCVBitmanipPat {
7321   SDValue Op;
7322   unsigned ShAmt;
7323   bool IsSHL;
7324 
7325   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7326     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7327   }
7328 };
7329 
7330 // Matches patterns of the form
7331 //   (and (shl x, C2), (C1 << C2))
7332 //   (and (srl x, C2), C1)
7333 //   (shl (and x, C1), C2)
7334 //   (srl (and x, (C1 << C2)), C2)
7335 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7336 // The expected masks for each shift amount are specified in BitmanipMasks where
7337 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7338 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7339 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7340 // XLen is 64.
7341 static Optional<RISCVBitmanipPat>
7342 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7343   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7344          "Unexpected number of masks");
7345   Optional<uint64_t> Mask;
7346   // Optionally consume a mask around the shift operation.
7347   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7348     Mask = Op.getConstantOperandVal(1);
7349     Op = Op.getOperand(0);
7350   }
7351   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7352     return None;
7353   bool IsSHL = Op.getOpcode() == ISD::SHL;
7354 
7355   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7356     return None;
7357   uint64_t ShAmt = Op.getConstantOperandVal(1);
7358 
7359   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7360   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7361     return None;
7362   // If we don't have enough masks for 64 bit, then we must be trying to
7363   // match SHFL so we're only allowed to shift 1/4 of the width.
7364   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7365     return None;
7366 
7367   SDValue Src = Op.getOperand(0);
7368 
7369   // The expected mask is shifted left when the AND is found around SHL
7370   // patterns.
7371   //   ((x >> 1) & 0x55555555)
7372   //   ((x << 1) & 0xAAAAAAAA)
7373   bool SHLExpMask = IsSHL;
7374 
7375   if (!Mask) {
7376     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7377     // the mask is all ones: consume that now.
7378     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7379       Mask = Src.getConstantOperandVal(1);
7380       Src = Src.getOperand(0);
7381       // The expected mask is now in fact shifted left for SRL, so reverse the
7382       // decision.
7383       //   ((x & 0xAAAAAAAA) >> 1)
7384       //   ((x & 0x55555555) << 1)
7385       SHLExpMask = !SHLExpMask;
7386     } else {
7387       // Use a default shifted mask of all-ones if there's no AND, truncated
7388       // down to the expected width. This simplifies the logic later on.
7389       Mask = maskTrailingOnes<uint64_t>(Width);
7390       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7391     }
7392   }
7393 
7394   unsigned MaskIdx = Log2_32(ShAmt);
7395   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7396 
7397   if (SHLExpMask)
7398     ExpMask <<= ShAmt;
7399 
7400   if (Mask != ExpMask)
7401     return None;
7402 
7403   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7404 }
7405 
7406 // Matches any of the following bit-manipulation patterns:
7407 //   (and (shl x, 1), (0x55555555 << 1))
7408 //   (and (srl x, 1), 0x55555555)
7409 //   (shl (and x, 0x55555555), 1)
7410 //   (srl (and x, (0x55555555 << 1)), 1)
7411 // where the shift amount and mask may vary thus:
7412 //   [1]  = 0x55555555 / 0xAAAAAAAA
7413 //   [2]  = 0x33333333 / 0xCCCCCCCC
7414 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7415 //   [8]  = 0x00FF00FF / 0xFF00FF00
7416 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7417 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7418 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7419   // These are the unshifted masks which we use to match bit-manipulation
7420   // patterns. They may be shifted left in certain circumstances.
7421   static const uint64_t BitmanipMasks[] = {
7422       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7423       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7424 
7425   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7426 }
7427 
7428 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7429 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7430   auto BinOpToRVVReduce = [](unsigned Opc) {
7431     switch (Opc) {
7432     default:
7433       llvm_unreachable("Unhandled binary to transfrom reduction");
7434     case ISD::ADD:
7435       return RISCVISD::VECREDUCE_ADD_VL;
7436     case ISD::UMAX:
7437       return RISCVISD::VECREDUCE_UMAX_VL;
7438     case ISD::SMAX:
7439       return RISCVISD::VECREDUCE_SMAX_VL;
7440     case ISD::UMIN:
7441       return RISCVISD::VECREDUCE_UMIN_VL;
7442     case ISD::SMIN:
7443       return RISCVISD::VECREDUCE_SMIN_VL;
7444     case ISD::AND:
7445       return RISCVISD::VECREDUCE_AND_VL;
7446     case ISD::OR:
7447       return RISCVISD::VECREDUCE_OR_VL;
7448     case ISD::XOR:
7449       return RISCVISD::VECREDUCE_XOR_VL;
7450     case ISD::FADD:
7451       return RISCVISD::VECREDUCE_FADD_VL;
7452     case ISD::FMAXNUM:
7453       return RISCVISD::VECREDUCE_FMAX_VL;
7454     case ISD::FMINNUM:
7455       return RISCVISD::VECREDUCE_FMIN_VL;
7456     }
7457   };
7458 
7459   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7460     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7461            isNullConstant(V.getOperand(1)) &&
7462            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7463   };
7464 
7465   unsigned Opc = N->getOpcode();
7466   unsigned ReduceIdx;
7467   if (IsReduction(N->getOperand(0), Opc))
7468     ReduceIdx = 0;
7469   else if (IsReduction(N->getOperand(1), Opc))
7470     ReduceIdx = 1;
7471   else
7472     return SDValue();
7473 
7474   // Skip if FADD disallows reassociation but the combiner needs.
7475   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7476     return SDValue();
7477 
7478   SDValue Extract = N->getOperand(ReduceIdx);
7479   SDValue Reduce = Extract.getOperand(0);
7480   if (!Reduce.hasOneUse())
7481     return SDValue();
7482 
7483   SDValue ScalarV = Reduce.getOperand(2);
7484 
7485   // Make sure that ScalarV is a splat with VL=1.
7486   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7487       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7488       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7489     return SDValue();
7490 
7491   if (!isOneConstant(ScalarV.getOperand(2)))
7492     return SDValue();
7493 
7494   // TODO: Deal with value other than neutral element.
7495   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7496     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7497         isNullFPConstant(V))
7498       return true;
7499     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7500                                  N->getFlags()) == V;
7501   };
7502 
7503   // Check the scalar of ScalarV is neutral element
7504   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7505     return SDValue();
7506 
7507   if (!ScalarV.hasOneUse())
7508     return SDValue();
7509 
7510   EVT SplatVT = ScalarV.getValueType();
7511   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7512   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7513   if (SplatVT.isInteger()) {
7514     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7515     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7516       SplatOpc = RISCVISD::VMV_S_X_VL;
7517     else
7518       SplatOpc = RISCVISD::VMV_V_X_VL;
7519   }
7520 
7521   SDValue NewScalarV =
7522       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7523                   ScalarV.getOperand(2));
7524   SDValue NewReduce =
7525       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7526                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7527                   Reduce.getOperand(3), Reduce.getOperand(4));
7528   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7529                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7530 }
7531 
7532 // Match the following pattern as a GREVI(W) operation
7533 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7534 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7535                                const RISCVSubtarget &Subtarget) {
7536   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7537   EVT VT = Op.getValueType();
7538 
7539   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7540     auto LHS = matchGREVIPat(Op.getOperand(0));
7541     auto RHS = matchGREVIPat(Op.getOperand(1));
7542     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7543       SDLoc DL(Op);
7544       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7545                          DAG.getConstant(LHS->ShAmt, DL, VT));
7546     }
7547   }
7548   return SDValue();
7549 }
7550 
7551 // Matches any the following pattern as a GORCI(W) operation
7552 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7553 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7554 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7555 // Note that with the variant of 3.,
7556 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7557 // the inner pattern will first be matched as GREVI and then the outer
7558 // pattern will be matched to GORC via the first rule above.
7559 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7560 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7561                                const RISCVSubtarget &Subtarget) {
7562   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7563   EVT VT = Op.getValueType();
7564 
7565   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7566     SDLoc DL(Op);
7567     SDValue Op0 = Op.getOperand(0);
7568     SDValue Op1 = Op.getOperand(1);
7569 
7570     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7571       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7572           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7573           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7574         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7575       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7576       if ((Reverse.getOpcode() == ISD::ROTL ||
7577            Reverse.getOpcode() == ISD::ROTR) &&
7578           Reverse.getOperand(0) == X &&
7579           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7580         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7581         if (RotAmt == (VT.getSizeInBits() / 2))
7582           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7583                              DAG.getConstant(RotAmt, DL, VT));
7584       }
7585       return SDValue();
7586     };
7587 
7588     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7589     if (SDValue V = MatchOROfReverse(Op0, Op1))
7590       return V;
7591     if (SDValue V = MatchOROfReverse(Op1, Op0))
7592       return V;
7593 
7594     // OR is commutable so canonicalize its OR operand to the left
7595     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7596       std::swap(Op0, Op1);
7597     if (Op0.getOpcode() != ISD::OR)
7598       return SDValue();
7599     SDValue OrOp0 = Op0.getOperand(0);
7600     SDValue OrOp1 = Op0.getOperand(1);
7601     auto LHS = matchGREVIPat(OrOp0);
7602     // OR is commutable so swap the operands and try again: x might have been
7603     // on the left
7604     if (!LHS) {
7605       std::swap(OrOp0, OrOp1);
7606       LHS = matchGREVIPat(OrOp0);
7607     }
7608     auto RHS = matchGREVIPat(Op1);
7609     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7610       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7611                          DAG.getConstant(LHS->ShAmt, DL, VT));
7612     }
7613   }
7614   return SDValue();
7615 }
7616 
7617 // Matches any of the following bit-manipulation patterns:
7618 //   (and (shl x, 1), (0x22222222 << 1))
7619 //   (and (srl x, 1), 0x22222222)
7620 //   (shl (and x, 0x22222222), 1)
7621 //   (srl (and x, (0x22222222 << 1)), 1)
7622 // where the shift amount and mask may vary thus:
7623 //   [1]  = 0x22222222 / 0x44444444
7624 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7625 //   [4]  = 0x00F000F0 / 0x0F000F00
7626 //   [8]  = 0x0000FF00 / 0x00FF0000
7627 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7628 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7629   // These are the unshifted masks which we use to match bit-manipulation
7630   // patterns. They may be shifted left in certain circumstances.
7631   static const uint64_t BitmanipMasks[] = {
7632       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7633       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7634 
7635   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7636 }
7637 
7638 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7639 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7640                                const RISCVSubtarget &Subtarget) {
7641   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7642   EVT VT = Op.getValueType();
7643 
7644   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7645     return SDValue();
7646 
7647   SDValue Op0 = Op.getOperand(0);
7648   SDValue Op1 = Op.getOperand(1);
7649 
7650   // Or is commutable so canonicalize the second OR to the LHS.
7651   if (Op0.getOpcode() != ISD::OR)
7652     std::swap(Op0, Op1);
7653   if (Op0.getOpcode() != ISD::OR)
7654     return SDValue();
7655 
7656   // We found an inner OR, so our operands are the operands of the inner OR
7657   // and the other operand of the outer OR.
7658   SDValue A = Op0.getOperand(0);
7659   SDValue B = Op0.getOperand(1);
7660   SDValue C = Op1;
7661 
7662   auto Match1 = matchSHFLPat(A);
7663   auto Match2 = matchSHFLPat(B);
7664 
7665   // If neither matched, we failed.
7666   if (!Match1 && !Match2)
7667     return SDValue();
7668 
7669   // We had at least one match. if one failed, try the remaining C operand.
7670   if (!Match1) {
7671     std::swap(A, C);
7672     Match1 = matchSHFLPat(A);
7673     if (!Match1)
7674       return SDValue();
7675   } else if (!Match2) {
7676     std::swap(B, C);
7677     Match2 = matchSHFLPat(B);
7678     if (!Match2)
7679       return SDValue();
7680   }
7681   assert(Match1 && Match2);
7682 
7683   // Make sure our matches pair up.
7684   if (!Match1->formsPairWith(*Match2))
7685     return SDValue();
7686 
7687   // All the remains is to make sure C is an AND with the same input, that masks
7688   // out the bits that are being shuffled.
7689   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7690       C.getOperand(0) != Match1->Op)
7691     return SDValue();
7692 
7693   uint64_t Mask = C.getConstantOperandVal(1);
7694 
7695   static const uint64_t BitmanipMasks[] = {
7696       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7697       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7698   };
7699 
7700   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7701   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7702   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7703 
7704   if (Mask != ExpMask)
7705     return SDValue();
7706 
7707   SDLoc DL(Op);
7708   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7709                      DAG.getConstant(Match1->ShAmt, DL, VT));
7710 }
7711 
7712 // Optimize (add (shl x, c0), (shl y, c1)) ->
7713 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7714 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7715                                   const RISCVSubtarget &Subtarget) {
7716   // Perform this optimization only in the zba extension.
7717   if (!Subtarget.hasStdExtZba())
7718     return SDValue();
7719 
7720   // Skip for vector types and larger types.
7721   EVT VT = N->getValueType(0);
7722   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7723     return SDValue();
7724 
7725   // The two operand nodes must be SHL and have no other use.
7726   SDValue N0 = N->getOperand(0);
7727   SDValue N1 = N->getOperand(1);
7728   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7729       !N0->hasOneUse() || !N1->hasOneUse())
7730     return SDValue();
7731 
7732   // Check c0 and c1.
7733   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7734   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7735   if (!N0C || !N1C)
7736     return SDValue();
7737   int64_t C0 = N0C->getSExtValue();
7738   int64_t C1 = N1C->getSExtValue();
7739   if (C0 <= 0 || C1 <= 0)
7740     return SDValue();
7741 
7742   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7743   int64_t Bits = std::min(C0, C1);
7744   int64_t Diff = std::abs(C0 - C1);
7745   if (Diff != 1 && Diff != 2 && Diff != 3)
7746     return SDValue();
7747 
7748   // Build nodes.
7749   SDLoc DL(N);
7750   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7751   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7752   SDValue NA0 =
7753       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7754   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7755   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7756 }
7757 
7758 // Combine
7759 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7760 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7761 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7762 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7763 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7764 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7765 // The grev patterns represents BSWAP.
7766 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7767 // off the grev.
7768 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7769                                           const RISCVSubtarget &Subtarget) {
7770   bool IsWInstruction =
7771       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7772   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7773           IsWInstruction) &&
7774          "Unexpected opcode!");
7775   SDValue Src = N->getOperand(0);
7776   EVT VT = N->getValueType(0);
7777   SDLoc DL(N);
7778 
7779   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7780     return SDValue();
7781 
7782   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7783       !isa<ConstantSDNode>(Src.getOperand(1)))
7784     return SDValue();
7785 
7786   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7787   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7788 
7789   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7790   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7791   unsigned ShAmt1 = N->getConstantOperandVal(1);
7792   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7793   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7794     return SDValue();
7795 
7796   Src = Src.getOperand(0);
7797 
7798   // Toggle bit the MSB of the shift.
7799   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7800   if (CombinedShAmt == 0)
7801     return Src;
7802 
7803   SDValue Res = DAG.getNode(
7804       RISCVISD::GREV, DL, VT, Src,
7805       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7806   if (!IsWInstruction)
7807     return Res;
7808 
7809   // Sign extend the result to match the behavior of the rotate. This will be
7810   // selected to GREVIW in isel.
7811   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7812                      DAG.getValueType(MVT::i32));
7813 }
7814 
7815 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7816 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7817 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7818 // not undo itself, but they are redundant.
7819 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7820   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7821   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7822   SDValue Src = N->getOperand(0);
7823 
7824   if (Src.getOpcode() != N->getOpcode())
7825     return SDValue();
7826 
7827   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7828       !isa<ConstantSDNode>(Src.getOperand(1)))
7829     return SDValue();
7830 
7831   unsigned ShAmt1 = N->getConstantOperandVal(1);
7832   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7833   Src = Src.getOperand(0);
7834 
7835   unsigned CombinedShAmt;
7836   if (IsGORC)
7837     CombinedShAmt = ShAmt1 | ShAmt2;
7838   else
7839     CombinedShAmt = ShAmt1 ^ ShAmt2;
7840 
7841   if (CombinedShAmt == 0)
7842     return Src;
7843 
7844   SDLoc DL(N);
7845   return DAG.getNode(
7846       N->getOpcode(), DL, N->getValueType(0), Src,
7847       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7848 }
7849 
7850 // Combine a constant select operand into its use:
7851 //
7852 // (and (select cond, -1, c), x)
7853 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7854 // (or  (select cond, 0, c), x)
7855 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7856 // (xor (select cond, 0, c), x)
7857 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7858 // (add (select cond, 0, c), x)
7859 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7860 // (sub x, (select cond, 0, c))
7861 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7862 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7863                                    SelectionDAG &DAG, bool AllOnes) {
7864   EVT VT = N->getValueType(0);
7865 
7866   // Skip vectors.
7867   if (VT.isVector())
7868     return SDValue();
7869 
7870   if ((Slct.getOpcode() != ISD::SELECT &&
7871        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7872       !Slct.hasOneUse())
7873     return SDValue();
7874 
7875   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7876     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7877   };
7878 
7879   bool SwapSelectOps;
7880   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7881   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7882   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7883   SDValue NonConstantVal;
7884   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7885     SwapSelectOps = false;
7886     NonConstantVal = FalseVal;
7887   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7888     SwapSelectOps = true;
7889     NonConstantVal = TrueVal;
7890   } else
7891     return SDValue();
7892 
7893   // Slct is now know to be the desired identity constant when CC is true.
7894   TrueVal = OtherOp;
7895   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7896   // Unless SwapSelectOps says the condition should be false.
7897   if (SwapSelectOps)
7898     std::swap(TrueVal, FalseVal);
7899 
7900   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7901     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7902                        {Slct.getOperand(0), Slct.getOperand(1),
7903                         Slct.getOperand(2), TrueVal, FalseVal});
7904 
7905   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7906                      {Slct.getOperand(0), TrueVal, FalseVal});
7907 }
7908 
7909 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7910 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7911                                               bool AllOnes) {
7912   SDValue N0 = N->getOperand(0);
7913   SDValue N1 = N->getOperand(1);
7914   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7915     return Result;
7916   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7917     return Result;
7918   return SDValue();
7919 }
7920 
7921 // Transform (add (mul x, c0), c1) ->
7922 //           (add (mul (add x, c1/c0), c0), c1%c0).
7923 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7924 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7925 // to an infinite loop in DAGCombine if transformed.
7926 // Or transform (add (mul x, c0), c1) ->
7927 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7928 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7929 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7930 // lead to an infinite loop in DAGCombine if transformed.
7931 // Or transform (add (mul x, c0), c1) ->
7932 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7933 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7934 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7935 // lead to an infinite loop in DAGCombine if transformed.
7936 // Or transform (add (mul x, c0), c1) ->
7937 //              (mul (add x, c1/c0), c0).
7938 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7939 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7940                                      const RISCVSubtarget &Subtarget) {
7941   // Skip for vector types and larger types.
7942   EVT VT = N->getValueType(0);
7943   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7944     return SDValue();
7945   // The first operand node must be a MUL and has no other use.
7946   SDValue N0 = N->getOperand(0);
7947   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7948     return SDValue();
7949   // Check if c0 and c1 match above conditions.
7950   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7951   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7952   if (!N0C || !N1C)
7953     return SDValue();
7954   // If N0C has multiple uses it's possible one of the cases in
7955   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7956   // in an infinite loop.
7957   if (!N0C->hasOneUse())
7958     return SDValue();
7959   int64_t C0 = N0C->getSExtValue();
7960   int64_t C1 = N1C->getSExtValue();
7961   int64_t CA, CB;
7962   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7963     return SDValue();
7964   // Search for proper CA (non-zero) and CB that both are simm12.
7965   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7966       !isInt<12>(C0 * (C1 / C0))) {
7967     CA = C1 / C0;
7968     CB = C1 % C0;
7969   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7970              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7971     CA = C1 / C0 + 1;
7972     CB = C1 % C0 - C0;
7973   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7974              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7975     CA = C1 / C0 - 1;
7976     CB = C1 % C0 + C0;
7977   } else
7978     return SDValue();
7979   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7980   SDLoc DL(N);
7981   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7982                              DAG.getConstant(CA, DL, VT));
7983   SDValue New1 =
7984       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7985   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7986 }
7987 
7988 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7989                                  const RISCVSubtarget &Subtarget) {
7990   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7991     return V;
7992   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7993     return V;
7994   if (SDValue V = combineBinOpToReduce(N, DAG))
7995     return V;
7996   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7997   //      (select lhs, rhs, cc, x, (add x, y))
7998   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7999 }
8000 
8001 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8002   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8003   //      (select lhs, rhs, cc, x, (sub x, y))
8004   SDValue N0 = N->getOperand(0);
8005   SDValue N1 = N->getOperand(1);
8006   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8007 }
8008 
8009 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8010                                  const RISCVSubtarget &Subtarget) {
8011   SDValue N0 = N->getOperand(0);
8012   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8013   // extending X. This is safe since we only need the LSB after the shift and
8014   // shift amounts larger than 31 would produce poison. If we wait until
8015   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8016   // to use a BEXT instruction.
8017   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8018       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8019       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8020       N0.hasOneUse()) {
8021     SDLoc DL(N);
8022     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8023     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8024     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8025     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8026                               DAG.getConstant(1, DL, MVT::i64));
8027     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8028   }
8029 
8030   if (SDValue V = combineBinOpToReduce(N, DAG))
8031     return V;
8032 
8033   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8034   //      (select lhs, rhs, cc, x, (and x, y))
8035   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8036 }
8037 
8038 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8039                                 const RISCVSubtarget &Subtarget) {
8040   if (Subtarget.hasStdExtZbp()) {
8041     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8042       return GREV;
8043     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8044       return GORC;
8045     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8046       return SHFL;
8047   }
8048 
8049   if (SDValue V = combineBinOpToReduce(N, DAG))
8050     return V;
8051   // fold (or (select cond, 0, y), x) ->
8052   //      (select cond, x, (or x, y))
8053   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8054 }
8055 
8056 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8057   SDValue N0 = N->getOperand(0);
8058   SDValue N1 = N->getOperand(1);
8059 
8060   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8061   // NOTE: Assumes ROL being legal means ROLW is legal.
8062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8063   if (N0.getOpcode() == RISCVISD::SLLW &&
8064       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8065       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8066     SDLoc DL(N);
8067     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8068                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8069   }
8070 
8071   if (SDValue V = combineBinOpToReduce(N, DAG))
8072     return V;
8073   // fold (xor (select cond, 0, y), x) ->
8074   //      (select cond, x, (xor x, y))
8075   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8076 }
8077 
8078 static SDValue
8079 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8080                                 const RISCVSubtarget &Subtarget) {
8081   SDValue Src = N->getOperand(0);
8082   EVT VT = N->getValueType(0);
8083 
8084   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8085   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8086       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8087     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8088                        Src.getOperand(0));
8089 
8090   // Fold (i64 (sext_inreg (abs X), i32)) ->
8091   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8092   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8093   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8094   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8095   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8096   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8097   // may get combined into an earlier operation so we need to use
8098   // ComputeNumSignBits.
8099   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8100   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8101   // we can't assume that X has 33 sign bits. We must check.
8102   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8103       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8104       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8105       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8106     SDLoc DL(N);
8107     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8108     SDValue Neg =
8109         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8110     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8111                       DAG.getValueType(MVT::i32));
8112     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8113   }
8114 
8115   return SDValue();
8116 }
8117 
8118 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8119 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8120 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8121                                              bool Commute = false) {
8122   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8123           N->getOpcode() == RISCVISD::SUB_VL) &&
8124          "Unexpected opcode");
8125   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8126   SDValue Op0 = N->getOperand(0);
8127   SDValue Op1 = N->getOperand(1);
8128   if (Commute)
8129     std::swap(Op0, Op1);
8130 
8131   MVT VT = N->getSimpleValueType(0);
8132 
8133   // Determine the narrow size for a widening add/sub.
8134   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8135   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8136                                   VT.getVectorElementCount());
8137 
8138   SDValue Mask = N->getOperand(2);
8139   SDValue VL = N->getOperand(3);
8140 
8141   SDLoc DL(N);
8142 
8143   // If the RHS is a sext or zext, we can form a widening op.
8144   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8145        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8146       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8147     unsigned ExtOpc = Op1.getOpcode();
8148     Op1 = Op1.getOperand(0);
8149     // Re-introduce narrower extends if needed.
8150     if (Op1.getValueType() != NarrowVT)
8151       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8152 
8153     unsigned WOpc;
8154     if (ExtOpc == RISCVISD::VSEXT_VL)
8155       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8156     else
8157       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8158 
8159     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8160   }
8161 
8162   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8163   // sext/zext?
8164 
8165   return SDValue();
8166 }
8167 
8168 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8169 // vwsub(u).vv/vx.
8170 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8171   SDValue Op0 = N->getOperand(0);
8172   SDValue Op1 = N->getOperand(1);
8173   SDValue Mask = N->getOperand(2);
8174   SDValue VL = N->getOperand(3);
8175 
8176   MVT VT = N->getSimpleValueType(0);
8177   MVT NarrowVT = Op1.getSimpleValueType();
8178   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8179 
8180   unsigned VOpc;
8181   switch (N->getOpcode()) {
8182   default: llvm_unreachable("Unexpected opcode");
8183   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8184   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8185   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8186   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8187   }
8188 
8189   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8190                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8191 
8192   SDLoc DL(N);
8193 
8194   // If the LHS is a sext or zext, we can narrow this op to the same size as
8195   // the RHS.
8196   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8197        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8198       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8199     unsigned ExtOpc = Op0.getOpcode();
8200     Op0 = Op0.getOperand(0);
8201     // Re-introduce narrower extends if needed.
8202     if (Op0.getValueType() != NarrowVT)
8203       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8204     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8205   }
8206 
8207   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8208                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8209 
8210   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8211   // to commute and use a vwadd(u).vx instead.
8212   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8213       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8214     Op0 = Op0.getOperand(1);
8215 
8216     // See if have enough sign bits or zero bits in the scalar to use a
8217     // widening add/sub by splatting to smaller element size.
8218     unsigned EltBits = VT.getScalarSizeInBits();
8219     unsigned ScalarBits = Op0.getValueSizeInBits();
8220     // Make sure we're getting all element bits from the scalar register.
8221     // FIXME: Support implicit sign extension of vmv.v.x?
8222     if (ScalarBits < EltBits)
8223       return SDValue();
8224 
8225     if (IsSigned) {
8226       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8227         return SDValue();
8228     } else {
8229       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8230       if (!DAG.MaskedValueIsZero(Op0, Mask))
8231         return SDValue();
8232     }
8233 
8234     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8235                       DAG.getUNDEF(NarrowVT), Op0, VL);
8236     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8237   }
8238 
8239   return SDValue();
8240 }
8241 
8242 // Try to form VWMUL, VWMULU or VWMULSU.
8243 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8244 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8245                                        bool Commute) {
8246   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8247   SDValue Op0 = N->getOperand(0);
8248   SDValue Op1 = N->getOperand(1);
8249   if (Commute)
8250     std::swap(Op0, Op1);
8251 
8252   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8253   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8254   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8255   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8256     return SDValue();
8257 
8258   SDValue Mask = N->getOperand(2);
8259   SDValue VL = N->getOperand(3);
8260 
8261   // Make sure the mask and VL match.
8262   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8263     return SDValue();
8264 
8265   MVT VT = N->getSimpleValueType(0);
8266 
8267   // Determine the narrow size for a widening multiply.
8268   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8269   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8270                                   VT.getVectorElementCount());
8271 
8272   SDLoc DL(N);
8273 
8274   // See if the other operand is the same opcode.
8275   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8276     if (!Op1.hasOneUse())
8277       return SDValue();
8278 
8279     // Make sure the mask and VL match.
8280     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8281       return SDValue();
8282 
8283     Op1 = Op1.getOperand(0);
8284   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8285     // The operand is a splat of a scalar.
8286 
8287     // The pasthru must be undef for tail agnostic
8288     if (!Op1.getOperand(0).isUndef())
8289       return SDValue();
8290     // The VL must be the same.
8291     if (Op1.getOperand(2) != VL)
8292       return SDValue();
8293 
8294     // Get the scalar value.
8295     Op1 = Op1.getOperand(1);
8296 
8297     // See if have enough sign bits or zero bits in the scalar to use a
8298     // widening multiply by splatting to smaller element size.
8299     unsigned EltBits = VT.getScalarSizeInBits();
8300     unsigned ScalarBits = Op1.getValueSizeInBits();
8301     // Make sure we're getting all element bits from the scalar register.
8302     // FIXME: Support implicit sign extension of vmv.v.x?
8303     if (ScalarBits < EltBits)
8304       return SDValue();
8305 
8306     // If the LHS is a sign extend, try to use vwmul.
8307     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8308       // Can use vwmul.
8309     } else {
8310       // Otherwise try to use vwmulu or vwmulsu.
8311       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8312       if (DAG.MaskedValueIsZero(Op1, Mask))
8313         IsVWMULSU = IsSignExt;
8314       else
8315         return SDValue();
8316     }
8317 
8318     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8319                       DAG.getUNDEF(NarrowVT), Op1, VL);
8320   } else
8321     return SDValue();
8322 
8323   Op0 = Op0.getOperand(0);
8324 
8325   // Re-introduce narrower extends if needed.
8326   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8327   if (Op0.getValueType() != NarrowVT)
8328     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8329   // vwmulsu requires second operand to be zero extended.
8330   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8331   if (Op1.getValueType() != NarrowVT)
8332     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8333 
8334   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8335   if (!IsVWMULSU)
8336     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8337   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8338 }
8339 
8340 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8341   switch (Op.getOpcode()) {
8342   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8343   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8344   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8345   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8346   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8347   }
8348 
8349   return RISCVFPRndMode::Invalid;
8350 }
8351 
8352 // Fold
8353 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8354 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8355 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8356 //   (fp_to_int (fceil X))      -> fcvt X, rup
8357 //   (fp_to_int (fround X))     -> fcvt X, rmm
8358 static SDValue performFP_TO_INTCombine(SDNode *N,
8359                                        TargetLowering::DAGCombinerInfo &DCI,
8360                                        const RISCVSubtarget &Subtarget) {
8361   SelectionDAG &DAG = DCI.DAG;
8362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8363   MVT XLenVT = Subtarget.getXLenVT();
8364 
8365   // Only handle XLen or i32 types. Other types narrower than XLen will
8366   // eventually be legalized to XLenVT.
8367   EVT VT = N->getValueType(0);
8368   if (VT != MVT::i32 && VT != XLenVT)
8369     return SDValue();
8370 
8371   SDValue Src = N->getOperand(0);
8372 
8373   // Ensure the FP type is also legal.
8374   if (!TLI.isTypeLegal(Src.getValueType()))
8375     return SDValue();
8376 
8377   // Don't do this for f16 with Zfhmin and not Zfh.
8378   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8379     return SDValue();
8380 
8381   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8382   if (FRM == RISCVFPRndMode::Invalid)
8383     return SDValue();
8384 
8385   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8386 
8387   unsigned Opc;
8388   if (VT == XLenVT)
8389     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8390   else
8391     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8392 
8393   SDLoc DL(N);
8394   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8395                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8396   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8397 }
8398 
8399 // Fold
8400 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8401 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8402 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8403 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8404 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8405 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8406                                        TargetLowering::DAGCombinerInfo &DCI,
8407                                        const RISCVSubtarget &Subtarget) {
8408   SelectionDAG &DAG = DCI.DAG;
8409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8410   MVT XLenVT = Subtarget.getXLenVT();
8411 
8412   // Only handle XLen types. Other types narrower than XLen will eventually be
8413   // legalized to XLenVT.
8414   EVT DstVT = N->getValueType(0);
8415   if (DstVT != XLenVT)
8416     return SDValue();
8417 
8418   SDValue Src = N->getOperand(0);
8419 
8420   // Ensure the FP type is also legal.
8421   if (!TLI.isTypeLegal(Src.getValueType()))
8422     return SDValue();
8423 
8424   // Don't do this for f16 with Zfhmin and not Zfh.
8425   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8426     return SDValue();
8427 
8428   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8429 
8430   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8431   if (FRM == RISCVFPRndMode::Invalid)
8432     return SDValue();
8433 
8434   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8435 
8436   unsigned Opc;
8437   if (SatVT == DstVT)
8438     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8439   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8440     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8441   else
8442     return SDValue();
8443   // FIXME: Support other SatVTs by clamping before or after the conversion.
8444 
8445   Src = Src.getOperand(0);
8446 
8447   SDLoc DL(N);
8448   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8449                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8450 
8451   // RISCV FP-to-int conversions saturate to the destination register size, but
8452   // don't produce 0 for nan.
8453   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8454   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8455 }
8456 
8457 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8458 // smaller than XLenVT.
8459 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8460                                         const RISCVSubtarget &Subtarget) {
8461   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8462 
8463   SDValue Src = N->getOperand(0);
8464   if (Src.getOpcode() != ISD::BSWAP)
8465     return SDValue();
8466 
8467   EVT VT = N->getValueType(0);
8468   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8469       !isPowerOf2_32(VT.getSizeInBits()))
8470     return SDValue();
8471 
8472   SDLoc DL(N);
8473   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8474                      DAG.getConstant(7, DL, VT));
8475 }
8476 
8477 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8478                                                DAGCombinerInfo &DCI) const {
8479   SelectionDAG &DAG = DCI.DAG;
8480 
8481   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8482   // bits are demanded. N will be added to the Worklist if it was not deleted.
8483   // Caller should return SDValue(N, 0) if this returns true.
8484   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8485     SDValue Op = N->getOperand(OpNo);
8486     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8487     if (!SimplifyDemandedBits(Op, Mask, DCI))
8488       return false;
8489 
8490     if (N->getOpcode() != ISD::DELETED_NODE)
8491       DCI.AddToWorklist(N);
8492     return true;
8493   };
8494 
8495   switch (N->getOpcode()) {
8496   default:
8497     break;
8498   case RISCVISD::SplitF64: {
8499     SDValue Op0 = N->getOperand(0);
8500     // If the input to SplitF64 is just BuildPairF64 then the operation is
8501     // redundant. Instead, use BuildPairF64's operands directly.
8502     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8503       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8504 
8505     if (Op0->isUndef()) {
8506       SDValue Lo = DAG.getUNDEF(MVT::i32);
8507       SDValue Hi = DAG.getUNDEF(MVT::i32);
8508       return DCI.CombineTo(N, Lo, Hi);
8509     }
8510 
8511     SDLoc DL(N);
8512 
8513     // It's cheaper to materialise two 32-bit integers than to load a double
8514     // from the constant pool and transfer it to integer registers through the
8515     // stack.
8516     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8517       APInt V = C->getValueAPF().bitcastToAPInt();
8518       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8519       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8520       return DCI.CombineTo(N, Lo, Hi);
8521     }
8522 
8523     // This is a target-specific version of a DAGCombine performed in
8524     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8525     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8526     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8527     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8528         !Op0.getNode()->hasOneUse())
8529       break;
8530     SDValue NewSplitF64 =
8531         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8532                     Op0.getOperand(0));
8533     SDValue Lo = NewSplitF64.getValue(0);
8534     SDValue Hi = NewSplitF64.getValue(1);
8535     APInt SignBit = APInt::getSignMask(32);
8536     if (Op0.getOpcode() == ISD::FNEG) {
8537       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8538                                   DAG.getConstant(SignBit, DL, MVT::i32));
8539       return DCI.CombineTo(N, Lo, NewHi);
8540     }
8541     assert(Op0.getOpcode() == ISD::FABS);
8542     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8543                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8544     return DCI.CombineTo(N, Lo, NewHi);
8545   }
8546   case RISCVISD::SLLW:
8547   case RISCVISD::SRAW:
8548   case RISCVISD::SRLW: {
8549     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8550     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8551         SimplifyDemandedLowBitsHelper(1, 5))
8552       return SDValue(N, 0);
8553 
8554     break;
8555   }
8556   case ISD::ROTR:
8557   case ISD::ROTL:
8558   case RISCVISD::RORW:
8559   case RISCVISD::ROLW: {
8560     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8561       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8562       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8563           SimplifyDemandedLowBitsHelper(1, 5))
8564         return SDValue(N, 0);
8565     }
8566 
8567     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8568   }
8569   case RISCVISD::CLZW:
8570   case RISCVISD::CTZW: {
8571     // Only the lower 32 bits of the first operand are read
8572     if (SimplifyDemandedLowBitsHelper(0, 32))
8573       return SDValue(N, 0);
8574     break;
8575   }
8576   case RISCVISD::GREV:
8577   case RISCVISD::GORC: {
8578     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8579     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8580     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8581     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8582       return SDValue(N, 0);
8583 
8584     return combineGREVI_GORCI(N, DAG);
8585   }
8586   case RISCVISD::GREVW:
8587   case RISCVISD::GORCW: {
8588     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8589     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8590         SimplifyDemandedLowBitsHelper(1, 5))
8591       return SDValue(N, 0);
8592 
8593     break;
8594   }
8595   case RISCVISD::SHFL:
8596   case RISCVISD::UNSHFL: {
8597     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8598     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8599     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8600     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8601       return SDValue(N, 0);
8602 
8603     break;
8604   }
8605   case RISCVISD::SHFLW:
8606   case RISCVISD::UNSHFLW: {
8607     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8608     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8609         SimplifyDemandedLowBitsHelper(1, 4))
8610       return SDValue(N, 0);
8611 
8612     break;
8613   }
8614   case RISCVISD::BCOMPRESSW:
8615   case RISCVISD::BDECOMPRESSW: {
8616     // Only the lower 32 bits of LHS and RHS are read.
8617     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8618         SimplifyDemandedLowBitsHelper(1, 32))
8619       return SDValue(N, 0);
8620 
8621     break;
8622   }
8623   case RISCVISD::FSR:
8624   case RISCVISD::FSL:
8625   case RISCVISD::FSRW:
8626   case RISCVISD::FSLW: {
8627     bool IsWInstruction =
8628         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8629     unsigned BitWidth =
8630         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8631     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8632     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8633     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8634       return SDValue(N, 0);
8635 
8636     break;
8637   }
8638   case RISCVISD::FMV_X_ANYEXTH:
8639   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8640     SDLoc DL(N);
8641     SDValue Op0 = N->getOperand(0);
8642     MVT VT = N->getSimpleValueType(0);
8643     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8644     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8645     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8646     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8647          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8648         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8649          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8650       assert(Op0.getOperand(0).getValueType() == VT &&
8651              "Unexpected value type!");
8652       return Op0.getOperand(0);
8653     }
8654 
8655     // This is a target-specific version of a DAGCombine performed in
8656     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8657     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8658     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8659     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8660         !Op0.getNode()->hasOneUse())
8661       break;
8662     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8663     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8664     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8665     if (Op0.getOpcode() == ISD::FNEG)
8666       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8667                          DAG.getConstant(SignBit, DL, VT));
8668 
8669     assert(Op0.getOpcode() == ISD::FABS);
8670     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8671                        DAG.getConstant(~SignBit, DL, VT));
8672   }
8673   case ISD::ADD:
8674     return performADDCombine(N, DAG, Subtarget);
8675   case ISD::SUB:
8676     return performSUBCombine(N, DAG);
8677   case ISD::AND:
8678     return performANDCombine(N, DAG, Subtarget);
8679   case ISD::OR:
8680     return performORCombine(N, DAG, Subtarget);
8681   case ISD::XOR:
8682     return performXORCombine(N, DAG);
8683   case ISD::FADD:
8684   case ISD::UMAX:
8685   case ISD::UMIN:
8686   case ISD::SMAX:
8687   case ISD::SMIN:
8688   case ISD::FMAXNUM:
8689   case ISD::FMINNUM:
8690     return combineBinOpToReduce(N, DAG);
8691   case ISD::SIGN_EXTEND_INREG:
8692     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8693   case ISD::ZERO_EXTEND:
8694     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8695     // type legalization. This is safe because fp_to_uint produces poison if
8696     // it overflows.
8697     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8698       SDValue Src = N->getOperand(0);
8699       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8700           isTypeLegal(Src.getOperand(0).getValueType()))
8701         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8702                            Src.getOperand(0));
8703       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8704           isTypeLegal(Src.getOperand(1).getValueType())) {
8705         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8706         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8707                                   Src.getOperand(0), Src.getOperand(1));
8708         DCI.CombineTo(N, Res);
8709         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8710         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8711         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8712       }
8713     }
8714     return SDValue();
8715   case RISCVISD::SELECT_CC: {
8716     // Transform
8717     SDValue LHS = N->getOperand(0);
8718     SDValue RHS = N->getOperand(1);
8719     SDValue TrueV = N->getOperand(3);
8720     SDValue FalseV = N->getOperand(4);
8721 
8722     // If the True and False values are the same, we don't need a select_cc.
8723     if (TrueV == FalseV)
8724       return TrueV;
8725 
8726     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8727     if (!ISD::isIntEqualitySetCC(CCVal))
8728       break;
8729 
8730     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8731     //      (select_cc X, Y, lt, trueV, falseV)
8732     // Sometimes the setcc is introduced after select_cc has been formed.
8733     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8734         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8735       // If we're looking for eq 0 instead of ne 0, we need to invert the
8736       // condition.
8737       bool Invert = CCVal == ISD::SETEQ;
8738       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8739       if (Invert)
8740         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8741 
8742       SDLoc DL(N);
8743       RHS = LHS.getOperand(1);
8744       LHS = LHS.getOperand(0);
8745       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8746 
8747       SDValue TargetCC = DAG.getCondCode(CCVal);
8748       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8749                          {LHS, RHS, TargetCC, TrueV, FalseV});
8750     }
8751 
8752     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8753     //      (select_cc X, Y, eq/ne, trueV, falseV)
8754     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8755       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8756                          {LHS.getOperand(0), LHS.getOperand(1),
8757                           N->getOperand(2), TrueV, FalseV});
8758     // (select_cc X, 1, setne, trueV, falseV) ->
8759     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8760     // This can occur when legalizing some floating point comparisons.
8761     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8762     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8763       SDLoc DL(N);
8764       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8765       SDValue TargetCC = DAG.getCondCode(CCVal);
8766       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8767       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8768                          {LHS, RHS, TargetCC, TrueV, FalseV});
8769     }
8770 
8771     break;
8772   }
8773   case RISCVISD::BR_CC: {
8774     SDValue LHS = N->getOperand(1);
8775     SDValue RHS = N->getOperand(2);
8776     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8777     if (!ISD::isIntEqualitySetCC(CCVal))
8778       break;
8779 
8780     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8781     //      (br_cc X, Y, lt, dest)
8782     // Sometimes the setcc is introduced after br_cc has been formed.
8783     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8784         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8785       // If we're looking for eq 0 instead of ne 0, we need to invert the
8786       // condition.
8787       bool Invert = CCVal == ISD::SETEQ;
8788       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8789       if (Invert)
8790         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8791 
8792       SDLoc DL(N);
8793       RHS = LHS.getOperand(1);
8794       LHS = LHS.getOperand(0);
8795       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8796 
8797       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8798                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8799                          N->getOperand(4));
8800     }
8801 
8802     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8803     //      (br_cc X, Y, eq/ne, trueV, falseV)
8804     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8805       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8806                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8807                          N->getOperand(3), N->getOperand(4));
8808 
8809     // (br_cc X, 1, setne, br_cc) ->
8810     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8811     // This can occur when legalizing some floating point comparisons.
8812     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8813     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8814       SDLoc DL(N);
8815       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8816       SDValue TargetCC = DAG.getCondCode(CCVal);
8817       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8818       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8819                          N->getOperand(0), LHS, RHS, TargetCC,
8820                          N->getOperand(4));
8821     }
8822     break;
8823   }
8824   case ISD::BITREVERSE:
8825     return performBITREVERSECombine(N, DAG, Subtarget);
8826   case ISD::FP_TO_SINT:
8827   case ISD::FP_TO_UINT:
8828     return performFP_TO_INTCombine(N, DCI, Subtarget);
8829   case ISD::FP_TO_SINT_SAT:
8830   case ISD::FP_TO_UINT_SAT:
8831     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8832   case ISD::FCOPYSIGN: {
8833     EVT VT = N->getValueType(0);
8834     if (!VT.isVector())
8835       break;
8836     // There is a form of VFSGNJ which injects the negated sign of its second
8837     // operand. Try and bubble any FNEG up after the extend/round to produce
8838     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8839     // TRUNC=1.
8840     SDValue In2 = N->getOperand(1);
8841     // Avoid cases where the extend/round has multiple uses, as duplicating
8842     // those is typically more expensive than removing a fneg.
8843     if (!In2.hasOneUse())
8844       break;
8845     if (In2.getOpcode() != ISD::FP_EXTEND &&
8846         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8847       break;
8848     In2 = In2.getOperand(0);
8849     if (In2.getOpcode() != ISD::FNEG)
8850       break;
8851     SDLoc DL(N);
8852     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8853     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8854                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8855   }
8856   case ISD::MGATHER:
8857   case ISD::MSCATTER:
8858   case ISD::VP_GATHER:
8859   case ISD::VP_SCATTER: {
8860     if (!DCI.isBeforeLegalize())
8861       break;
8862     SDValue Index, ScaleOp;
8863     bool IsIndexScaled = false;
8864     bool IsIndexSigned = false;
8865     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8866       Index = VPGSN->getIndex();
8867       ScaleOp = VPGSN->getScale();
8868       IsIndexScaled = VPGSN->isIndexScaled();
8869       IsIndexSigned = VPGSN->isIndexSigned();
8870     } else {
8871       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8872       Index = MGSN->getIndex();
8873       ScaleOp = MGSN->getScale();
8874       IsIndexScaled = MGSN->isIndexScaled();
8875       IsIndexSigned = MGSN->isIndexSigned();
8876     }
8877     EVT IndexVT = Index.getValueType();
8878     MVT XLenVT = Subtarget.getXLenVT();
8879     // RISCV indexed loads only support the "unsigned unscaled" addressing
8880     // mode, so anything else must be manually legalized.
8881     bool NeedsIdxLegalization =
8882         IsIndexScaled ||
8883         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8884     if (!NeedsIdxLegalization)
8885       break;
8886 
8887     SDLoc DL(N);
8888 
8889     // Any index legalization should first promote to XLenVT, so we don't lose
8890     // bits when scaling. This may create an illegal index type so we let
8891     // LLVM's legalization take care of the splitting.
8892     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8893     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8894       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8895       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8896                           DL, IndexVT, Index);
8897     }
8898 
8899     if (IsIndexScaled) {
8900       // Manually scale the indices.
8901       // TODO: Sanitize the scale operand here?
8902       // TODO: For VP nodes, should we use VP_SHL here?
8903       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8904       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8905       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8906       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8907       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
8908     }
8909 
8910     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
8911     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8912       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8913                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8914                               ScaleOp, VPGN->getMask(),
8915                               VPGN->getVectorLength()},
8916                              VPGN->getMemOperand(), NewIndexTy);
8917     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8918       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8919                               {VPSN->getChain(), VPSN->getValue(),
8920                                VPSN->getBasePtr(), Index, ScaleOp,
8921                                VPSN->getMask(), VPSN->getVectorLength()},
8922                               VPSN->getMemOperand(), NewIndexTy);
8923     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8924       return DAG.getMaskedGather(
8925           N->getVTList(), MGN->getMemoryVT(), DL,
8926           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8927            MGN->getBasePtr(), Index, ScaleOp},
8928           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8929     const auto *MSN = cast<MaskedScatterSDNode>(N);
8930     return DAG.getMaskedScatter(
8931         N->getVTList(), MSN->getMemoryVT(), DL,
8932         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8933          Index, ScaleOp},
8934         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8935   }
8936   case RISCVISD::SRA_VL:
8937   case RISCVISD::SRL_VL:
8938   case RISCVISD::SHL_VL: {
8939     SDValue ShAmt = N->getOperand(1);
8940     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8941       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8942       SDLoc DL(N);
8943       SDValue VL = N->getOperand(3);
8944       EVT VT = N->getValueType(0);
8945       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8946                           ShAmt.getOperand(1), VL);
8947       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8948                          N->getOperand(2), N->getOperand(3));
8949     }
8950     break;
8951   }
8952   case ISD::SRA:
8953   case ISD::SRL:
8954   case ISD::SHL: {
8955     SDValue ShAmt = N->getOperand(1);
8956     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8957       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8958       SDLoc DL(N);
8959       EVT VT = N->getValueType(0);
8960       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8961                           ShAmt.getOperand(1),
8962                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8963       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8964     }
8965     break;
8966   }
8967   case RISCVISD::ADD_VL:
8968     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8969       return V;
8970     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8971   case RISCVISD::SUB_VL:
8972     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8973   case RISCVISD::VWADD_W_VL:
8974   case RISCVISD::VWADDU_W_VL:
8975   case RISCVISD::VWSUB_W_VL:
8976   case RISCVISD::VWSUBU_W_VL:
8977     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8978   case RISCVISD::MUL_VL:
8979     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8980       return V;
8981     // Mul is commutative.
8982     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8983   case ISD::STORE: {
8984     auto *Store = cast<StoreSDNode>(N);
8985     SDValue Val = Store->getValue();
8986     // Combine store of vmv.x.s to vse with VL of 1.
8987     // FIXME: Support FP.
8988     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8989       SDValue Src = Val.getOperand(0);
8990       EVT VecVT = Src.getValueType();
8991       EVT MemVT = Store->getMemoryVT();
8992       // The memory VT and the element type must match.
8993       if (VecVT.getVectorElementType() == MemVT) {
8994         SDLoc DL(N);
8995         MVT MaskVT = getMaskTypeFor(VecVT);
8996         return DAG.getStoreVP(
8997             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8998             DAG.getConstant(1, DL, MaskVT),
8999             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
9000             Store->getMemOperand(), Store->getAddressingMode(),
9001             Store->isTruncatingStore(), /*IsCompress*/ false);
9002       }
9003     }
9004 
9005     break;
9006   }
9007   case ISD::SPLAT_VECTOR: {
9008     EVT VT = N->getValueType(0);
9009     // Only perform this combine on legal MVT types.
9010     if (!isTypeLegal(VT))
9011       break;
9012     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9013                                          DAG, Subtarget))
9014       return Gather;
9015     break;
9016   }
9017   case RISCVISD::VMV_V_X_VL: {
9018     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9019     // scalar input.
9020     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9021     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9022     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9023       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9024         return SDValue(N, 0);
9025 
9026     break;
9027   }
9028   case ISD::INTRINSIC_WO_CHAIN: {
9029     unsigned IntNo = N->getConstantOperandVal(0);
9030     switch (IntNo) {
9031       // By default we do not combine any intrinsic.
9032     default:
9033       return SDValue();
9034     case Intrinsic::riscv_vcpop:
9035     case Intrinsic::riscv_vcpop_mask:
9036     case Intrinsic::riscv_vfirst:
9037     case Intrinsic::riscv_vfirst_mask: {
9038       SDValue VL = N->getOperand(2);
9039       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9040           IntNo == Intrinsic::riscv_vfirst_mask)
9041         VL = N->getOperand(3);
9042       if (!isNullConstant(VL))
9043         return SDValue();
9044       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9045       SDLoc DL(N);
9046       EVT VT = N->getValueType(0);
9047       if (IntNo == Intrinsic::riscv_vfirst ||
9048           IntNo == Intrinsic::riscv_vfirst_mask)
9049         return DAG.getConstant(-1, DL, VT);
9050       return DAG.getConstant(0, DL, VT);
9051     }
9052     }
9053   }
9054   case ISD::BITCAST: {
9055     assert(Subtarget.useRVVForFixedLengthVectors());
9056     SDValue N0 = N->getOperand(0);
9057     EVT VT = N->getValueType(0);
9058     EVT SrcVT = N0.getValueType();
9059     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9060     // type, widen both sides to avoid a trip through memory.
9061     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9062         VT.isScalarInteger()) {
9063       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9064       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9065       Ops[0] = N0;
9066       SDLoc DL(N);
9067       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9068       N0 = DAG.getBitcast(MVT::i8, N0);
9069       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9070     }
9071 
9072     return SDValue();
9073   }
9074   }
9075 
9076   return SDValue();
9077 }
9078 
9079 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9080     const SDNode *N, CombineLevel Level) const {
9081   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9082   // materialised in fewer instructions than `(OP _, c1)`:
9083   //
9084   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9085   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9086   SDValue N0 = N->getOperand(0);
9087   EVT Ty = N0.getValueType();
9088   if (Ty.isScalarInteger() &&
9089       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9090     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9091     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9092     if (C1 && C2) {
9093       const APInt &C1Int = C1->getAPIntValue();
9094       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9095 
9096       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9097       // and the combine should happen, to potentially allow further combines
9098       // later.
9099       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9100           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9101         return true;
9102 
9103       // We can materialise `c1` in an add immediate, so it's "free", and the
9104       // combine should be prevented.
9105       if (C1Int.getMinSignedBits() <= 64 &&
9106           isLegalAddImmediate(C1Int.getSExtValue()))
9107         return false;
9108 
9109       // Neither constant will fit into an immediate, so find materialisation
9110       // costs.
9111       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9112                                               Subtarget.getFeatureBits(),
9113                                               /*CompressionCost*/true);
9114       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9115           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9116           /*CompressionCost*/true);
9117 
9118       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9119       // combine should be prevented.
9120       if (C1Cost < ShiftedC1Cost)
9121         return false;
9122     }
9123   }
9124   return true;
9125 }
9126 
9127 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9128     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9129     TargetLoweringOpt &TLO) const {
9130   // Delay this optimization as late as possible.
9131   if (!TLO.LegalOps)
9132     return false;
9133 
9134   EVT VT = Op.getValueType();
9135   if (VT.isVector())
9136     return false;
9137 
9138   // Only handle AND for now.
9139   if (Op.getOpcode() != ISD::AND)
9140     return false;
9141 
9142   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9143   if (!C)
9144     return false;
9145 
9146   const APInt &Mask = C->getAPIntValue();
9147 
9148   // Clear all non-demanded bits initially.
9149   APInt ShrunkMask = Mask & DemandedBits;
9150 
9151   // Try to make a smaller immediate by setting undemanded bits.
9152 
9153   APInt ExpandedMask = Mask | ~DemandedBits;
9154 
9155   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9156     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9157   };
9158   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9159     if (NewMask == Mask)
9160       return true;
9161     SDLoc DL(Op);
9162     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9163     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9164     return TLO.CombineTo(Op, NewOp);
9165   };
9166 
9167   // If the shrunk mask fits in sign extended 12 bits, let the target
9168   // independent code apply it.
9169   if (ShrunkMask.isSignedIntN(12))
9170     return false;
9171 
9172   // Preserve (and X, 0xffff) when zext.h is supported.
9173   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9174     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9175     if (IsLegalMask(NewMask))
9176       return UseMask(NewMask);
9177   }
9178 
9179   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9180   if (VT == MVT::i64) {
9181     APInt NewMask = APInt(64, 0xffffffff);
9182     if (IsLegalMask(NewMask))
9183       return UseMask(NewMask);
9184   }
9185 
9186   // For the remaining optimizations, we need to be able to make a negative
9187   // number through a combination of mask and undemanded bits.
9188   if (!ExpandedMask.isNegative())
9189     return false;
9190 
9191   // What is the fewest number of bits we need to represent the negative number.
9192   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9193 
9194   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9195   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9196   APInt NewMask = ShrunkMask;
9197   if (MinSignedBits <= 12)
9198     NewMask.setBitsFrom(11);
9199   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9200     NewMask.setBitsFrom(31);
9201   else
9202     return false;
9203 
9204   // Check that our new mask is a subset of the demanded mask.
9205   assert(IsLegalMask(NewMask));
9206   return UseMask(NewMask);
9207 }
9208 
9209 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9210   static const uint64_t GREVMasks[] = {
9211       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9212       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9213 
9214   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9215     unsigned Shift = 1 << Stage;
9216     if (ShAmt & Shift) {
9217       uint64_t Mask = GREVMasks[Stage];
9218       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9219       if (IsGORC)
9220         Res |= x;
9221       x = Res;
9222     }
9223   }
9224 
9225   return x;
9226 }
9227 
9228 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9229                                                         KnownBits &Known,
9230                                                         const APInt &DemandedElts,
9231                                                         const SelectionDAG &DAG,
9232                                                         unsigned Depth) const {
9233   unsigned BitWidth = Known.getBitWidth();
9234   unsigned Opc = Op.getOpcode();
9235   assert((Opc >= ISD::BUILTIN_OP_END ||
9236           Opc == ISD::INTRINSIC_WO_CHAIN ||
9237           Opc == ISD::INTRINSIC_W_CHAIN ||
9238           Opc == ISD::INTRINSIC_VOID) &&
9239          "Should use MaskedValueIsZero if you don't know whether Op"
9240          " is a target node!");
9241 
9242   Known.resetAll();
9243   switch (Opc) {
9244   default: break;
9245   case RISCVISD::SELECT_CC: {
9246     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9247     // If we don't know any bits, early out.
9248     if (Known.isUnknown())
9249       break;
9250     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9251 
9252     // Only known if known in both the LHS and RHS.
9253     Known = KnownBits::commonBits(Known, Known2);
9254     break;
9255   }
9256   case RISCVISD::REMUW: {
9257     KnownBits Known2;
9258     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9259     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9260     // We only care about the lower 32 bits.
9261     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9262     // Restore the original width by sign extending.
9263     Known = Known.sext(BitWidth);
9264     break;
9265   }
9266   case RISCVISD::DIVUW: {
9267     KnownBits Known2;
9268     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9269     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9270     // We only care about the lower 32 bits.
9271     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9272     // Restore the original width by sign extending.
9273     Known = Known.sext(BitWidth);
9274     break;
9275   }
9276   case RISCVISD::CTZW: {
9277     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9278     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9279     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9280     Known.Zero.setBitsFrom(LowBits);
9281     break;
9282   }
9283   case RISCVISD::CLZW: {
9284     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9285     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9286     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9287     Known.Zero.setBitsFrom(LowBits);
9288     break;
9289   }
9290   case RISCVISD::GREV:
9291   case RISCVISD::GORC: {
9292     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9293       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9294       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9295       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9296       // To compute zeros, we need to invert the value and invert it back after.
9297       Known.Zero =
9298           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9299       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9300     }
9301     break;
9302   }
9303   case RISCVISD::READ_VLENB: {
9304     // If we know the minimum VLen from Zvl extensions, we can use that to
9305     // determine the trailing zeros of VLENB.
9306     // FIXME: Limit to 128 bit vectors until we have more testing.
9307     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9308     if (MinVLenB > 0)
9309       Known.Zero.setLowBits(Log2_32(MinVLenB));
9310     // We assume VLENB is no more than 65536 / 8 bytes.
9311     Known.Zero.setBitsFrom(14);
9312     break;
9313   }
9314   case ISD::INTRINSIC_W_CHAIN:
9315   case ISD::INTRINSIC_WO_CHAIN: {
9316     unsigned IntNo =
9317         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9318     switch (IntNo) {
9319     default:
9320       // We can't do anything for most intrinsics.
9321       break;
9322     case Intrinsic::riscv_vsetvli:
9323     case Intrinsic::riscv_vsetvlimax:
9324     case Intrinsic::riscv_vsetvli_opt:
9325     case Intrinsic::riscv_vsetvlimax_opt:
9326       // Assume that VL output is positive and would fit in an int32_t.
9327       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9328       if (BitWidth >= 32)
9329         Known.Zero.setBitsFrom(31);
9330       break;
9331     }
9332     break;
9333   }
9334   }
9335 }
9336 
9337 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9338     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9339     unsigned Depth) const {
9340   switch (Op.getOpcode()) {
9341   default:
9342     break;
9343   case RISCVISD::SELECT_CC: {
9344     unsigned Tmp =
9345         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9346     if (Tmp == 1) return 1;  // Early out.
9347     unsigned Tmp2 =
9348         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9349     return std::min(Tmp, Tmp2);
9350   }
9351   case RISCVISD::SLLW:
9352   case RISCVISD::SRAW:
9353   case RISCVISD::SRLW:
9354   case RISCVISD::DIVW:
9355   case RISCVISD::DIVUW:
9356   case RISCVISD::REMUW:
9357   case RISCVISD::ROLW:
9358   case RISCVISD::RORW:
9359   case RISCVISD::GREVW:
9360   case RISCVISD::GORCW:
9361   case RISCVISD::FSLW:
9362   case RISCVISD::FSRW:
9363   case RISCVISD::SHFLW:
9364   case RISCVISD::UNSHFLW:
9365   case RISCVISD::BCOMPRESSW:
9366   case RISCVISD::BDECOMPRESSW:
9367   case RISCVISD::BFPW:
9368   case RISCVISD::FCVT_W_RV64:
9369   case RISCVISD::FCVT_WU_RV64:
9370   case RISCVISD::STRICT_FCVT_W_RV64:
9371   case RISCVISD::STRICT_FCVT_WU_RV64:
9372     // TODO: As the result is sign-extended, this is conservatively correct. A
9373     // more precise answer could be calculated for SRAW depending on known
9374     // bits in the shift amount.
9375     return 33;
9376   case RISCVISD::SHFL:
9377   case RISCVISD::UNSHFL: {
9378     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9379     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9380     // will stay within the upper 32 bits. If there were more than 32 sign bits
9381     // before there will be at least 33 sign bits after.
9382     if (Op.getValueType() == MVT::i64 &&
9383         isa<ConstantSDNode>(Op.getOperand(1)) &&
9384         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9385       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9386       if (Tmp > 32)
9387         return 33;
9388     }
9389     break;
9390   }
9391   case RISCVISD::VMV_X_S: {
9392     // The number of sign bits of the scalar result is computed by obtaining the
9393     // element type of the input vector operand, subtracting its width from the
9394     // XLEN, and then adding one (sign bit within the element type). If the
9395     // element type is wider than XLen, the least-significant XLEN bits are
9396     // taken.
9397     unsigned XLen = Subtarget.getXLen();
9398     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9399     if (EltBits <= XLen)
9400       return XLen - EltBits + 1;
9401     break;
9402   }
9403   }
9404 
9405   return 1;
9406 }
9407 
9408 const Constant *
9409 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9410   assert(Ld && "Unexpected null LoadSDNode");
9411   if (!ISD::isNormalLoad(Ld))
9412     return nullptr;
9413 
9414   SDValue Ptr = Ld->getBasePtr();
9415 
9416   // Only constant pools with no offset are supported.
9417   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9418     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9419     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9420         CNode->getOffset() != 0)
9421       return nullptr;
9422 
9423     return CNode;
9424   };
9425 
9426   // Simple case, LLA.
9427   if (Ptr.getOpcode() == RISCVISD::LLA) {
9428     auto *CNode = GetSupportedConstantPool(Ptr);
9429     if (!CNode || CNode->getTargetFlags() != 0)
9430       return nullptr;
9431 
9432     return CNode->getConstVal();
9433   }
9434 
9435   // Look for a HI and ADD_LO pair.
9436   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9437       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9438     return nullptr;
9439 
9440   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9441   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9442 
9443   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9444       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9445     return nullptr;
9446 
9447   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9448     return nullptr;
9449 
9450   return CNodeLo->getConstVal();
9451 }
9452 
9453 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9454                                                   MachineBasicBlock *BB) {
9455   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9456 
9457   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9458   // Should the count have wrapped while it was being read, we need to try
9459   // again.
9460   // ...
9461   // read:
9462   // rdcycleh x3 # load high word of cycle
9463   // rdcycle  x2 # load low word of cycle
9464   // rdcycleh x4 # load high word of cycle
9465   // bne x3, x4, read # check if high word reads match, otherwise try again
9466   // ...
9467 
9468   MachineFunction &MF = *BB->getParent();
9469   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9470   MachineFunction::iterator It = ++BB->getIterator();
9471 
9472   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9473   MF.insert(It, LoopMBB);
9474 
9475   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9476   MF.insert(It, DoneMBB);
9477 
9478   // Transfer the remainder of BB and its successor edges to DoneMBB.
9479   DoneMBB->splice(DoneMBB->begin(), BB,
9480                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9481   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9482 
9483   BB->addSuccessor(LoopMBB);
9484 
9485   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9486   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9487   Register LoReg = MI.getOperand(0).getReg();
9488   Register HiReg = MI.getOperand(1).getReg();
9489   DebugLoc DL = MI.getDebugLoc();
9490 
9491   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9492   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9493       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9494       .addReg(RISCV::X0);
9495   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9496       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9497       .addReg(RISCV::X0);
9498   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9499       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9500       .addReg(RISCV::X0);
9501 
9502   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9503       .addReg(HiReg)
9504       .addReg(ReadAgainReg)
9505       .addMBB(LoopMBB);
9506 
9507   LoopMBB->addSuccessor(LoopMBB);
9508   LoopMBB->addSuccessor(DoneMBB);
9509 
9510   MI.eraseFromParent();
9511 
9512   return DoneMBB;
9513 }
9514 
9515 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9516                                              MachineBasicBlock *BB) {
9517   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9518 
9519   MachineFunction &MF = *BB->getParent();
9520   DebugLoc DL = MI.getDebugLoc();
9521   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9522   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9523   Register LoReg = MI.getOperand(0).getReg();
9524   Register HiReg = MI.getOperand(1).getReg();
9525   Register SrcReg = MI.getOperand(2).getReg();
9526   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9527   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9528 
9529   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9530                           RI);
9531   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9532   MachineMemOperand *MMOLo =
9533       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9534   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9535       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9536   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9537       .addFrameIndex(FI)
9538       .addImm(0)
9539       .addMemOperand(MMOLo);
9540   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9541       .addFrameIndex(FI)
9542       .addImm(4)
9543       .addMemOperand(MMOHi);
9544   MI.eraseFromParent(); // The pseudo instruction is gone now.
9545   return BB;
9546 }
9547 
9548 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9549                                                  MachineBasicBlock *BB) {
9550   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9551          "Unexpected instruction");
9552 
9553   MachineFunction &MF = *BB->getParent();
9554   DebugLoc DL = MI.getDebugLoc();
9555   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9556   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9557   Register DstReg = MI.getOperand(0).getReg();
9558   Register LoReg = MI.getOperand(1).getReg();
9559   Register HiReg = MI.getOperand(2).getReg();
9560   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9561   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9562 
9563   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9564   MachineMemOperand *MMOLo =
9565       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9566   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9567       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9568   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9569       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9570       .addFrameIndex(FI)
9571       .addImm(0)
9572       .addMemOperand(MMOLo);
9573   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9574       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9575       .addFrameIndex(FI)
9576       .addImm(4)
9577       .addMemOperand(MMOHi);
9578   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9579   MI.eraseFromParent(); // The pseudo instruction is gone now.
9580   return BB;
9581 }
9582 
9583 static bool isSelectPseudo(MachineInstr &MI) {
9584   switch (MI.getOpcode()) {
9585   default:
9586     return false;
9587   case RISCV::Select_GPR_Using_CC_GPR:
9588   case RISCV::Select_FPR16_Using_CC_GPR:
9589   case RISCV::Select_FPR32_Using_CC_GPR:
9590   case RISCV::Select_FPR64_Using_CC_GPR:
9591     return true;
9592   }
9593 }
9594 
9595 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9596                                         unsigned RelOpcode, unsigned EqOpcode,
9597                                         const RISCVSubtarget &Subtarget) {
9598   DebugLoc DL = MI.getDebugLoc();
9599   Register DstReg = MI.getOperand(0).getReg();
9600   Register Src1Reg = MI.getOperand(1).getReg();
9601   Register Src2Reg = MI.getOperand(2).getReg();
9602   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9603   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9604   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9605 
9606   // Save the current FFLAGS.
9607   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9608 
9609   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9610                  .addReg(Src1Reg)
9611                  .addReg(Src2Reg);
9612   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9613     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9614 
9615   // Restore the FFLAGS.
9616   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9617       .addReg(SavedFFlags, RegState::Kill);
9618 
9619   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9620   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9621                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9622                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9623   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9624     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9625 
9626   // Erase the pseudoinstruction.
9627   MI.eraseFromParent();
9628   return BB;
9629 }
9630 
9631 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9632                                            MachineBasicBlock *BB,
9633                                            const RISCVSubtarget &Subtarget) {
9634   // To "insert" Select_* instructions, we actually have to insert the triangle
9635   // control-flow pattern.  The incoming instructions know the destination vreg
9636   // to set, the condition code register to branch on, the true/false values to
9637   // select between, and the condcode to use to select the appropriate branch.
9638   //
9639   // We produce the following control flow:
9640   //     HeadMBB
9641   //     |  \
9642   //     |  IfFalseMBB
9643   //     | /
9644   //    TailMBB
9645   //
9646   // When we find a sequence of selects we attempt to optimize their emission
9647   // by sharing the control flow. Currently we only handle cases where we have
9648   // multiple selects with the exact same condition (same LHS, RHS and CC).
9649   // The selects may be interleaved with other instructions if the other
9650   // instructions meet some requirements we deem safe:
9651   // - They are debug instructions. Otherwise,
9652   // - They do not have side-effects, do not access memory and their inputs do
9653   //   not depend on the results of the select pseudo-instructions.
9654   // The TrueV/FalseV operands of the selects cannot depend on the result of
9655   // previous selects in the sequence.
9656   // These conditions could be further relaxed. See the X86 target for a
9657   // related approach and more information.
9658   Register LHS = MI.getOperand(1).getReg();
9659   Register RHS = MI.getOperand(2).getReg();
9660   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9661 
9662   SmallVector<MachineInstr *, 4> SelectDebugValues;
9663   SmallSet<Register, 4> SelectDests;
9664   SelectDests.insert(MI.getOperand(0).getReg());
9665 
9666   MachineInstr *LastSelectPseudo = &MI;
9667 
9668   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9669        SequenceMBBI != E; ++SequenceMBBI) {
9670     if (SequenceMBBI->isDebugInstr())
9671       continue;
9672     if (isSelectPseudo(*SequenceMBBI)) {
9673       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9674           SequenceMBBI->getOperand(2).getReg() != RHS ||
9675           SequenceMBBI->getOperand(3).getImm() != CC ||
9676           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9677           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9678         break;
9679       LastSelectPseudo = &*SequenceMBBI;
9680       SequenceMBBI->collectDebugValues(SelectDebugValues);
9681       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9682     } else {
9683       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9684           SequenceMBBI->mayLoadOrStore())
9685         break;
9686       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9687             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9688           }))
9689         break;
9690     }
9691   }
9692 
9693   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9694   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9695   DebugLoc DL = MI.getDebugLoc();
9696   MachineFunction::iterator I = ++BB->getIterator();
9697 
9698   MachineBasicBlock *HeadMBB = BB;
9699   MachineFunction *F = BB->getParent();
9700   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9701   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9702 
9703   F->insert(I, IfFalseMBB);
9704   F->insert(I, TailMBB);
9705 
9706   // Transfer debug instructions associated with the selects to TailMBB.
9707   for (MachineInstr *DebugInstr : SelectDebugValues) {
9708     TailMBB->push_back(DebugInstr->removeFromParent());
9709   }
9710 
9711   // Move all instructions after the sequence to TailMBB.
9712   TailMBB->splice(TailMBB->end(), HeadMBB,
9713                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9714   // Update machine-CFG edges by transferring all successors of the current
9715   // block to the new block which will contain the Phi nodes for the selects.
9716   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9717   // Set the successors for HeadMBB.
9718   HeadMBB->addSuccessor(IfFalseMBB);
9719   HeadMBB->addSuccessor(TailMBB);
9720 
9721   // Insert appropriate branch.
9722   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9723     .addReg(LHS)
9724     .addReg(RHS)
9725     .addMBB(TailMBB);
9726 
9727   // IfFalseMBB just falls through to TailMBB.
9728   IfFalseMBB->addSuccessor(TailMBB);
9729 
9730   // Create PHIs for all of the select pseudo-instructions.
9731   auto SelectMBBI = MI.getIterator();
9732   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9733   auto InsertionPoint = TailMBB->begin();
9734   while (SelectMBBI != SelectEnd) {
9735     auto Next = std::next(SelectMBBI);
9736     if (isSelectPseudo(*SelectMBBI)) {
9737       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9738       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9739               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9740           .addReg(SelectMBBI->getOperand(4).getReg())
9741           .addMBB(HeadMBB)
9742           .addReg(SelectMBBI->getOperand(5).getReg())
9743           .addMBB(IfFalseMBB);
9744       SelectMBBI->eraseFromParent();
9745     }
9746     SelectMBBI = Next;
9747   }
9748 
9749   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9750   return TailMBB;
9751 }
9752 
9753 MachineBasicBlock *
9754 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9755                                                  MachineBasicBlock *BB) const {
9756   switch (MI.getOpcode()) {
9757   default:
9758     llvm_unreachable("Unexpected instr type to insert");
9759   case RISCV::ReadCycleWide:
9760     assert(!Subtarget.is64Bit() &&
9761            "ReadCycleWrite is only to be used on riscv32");
9762     return emitReadCycleWidePseudo(MI, BB);
9763   case RISCV::Select_GPR_Using_CC_GPR:
9764   case RISCV::Select_FPR16_Using_CC_GPR:
9765   case RISCV::Select_FPR32_Using_CC_GPR:
9766   case RISCV::Select_FPR64_Using_CC_GPR:
9767     return emitSelectPseudo(MI, BB, Subtarget);
9768   case RISCV::BuildPairF64Pseudo:
9769     return emitBuildPairF64Pseudo(MI, BB);
9770   case RISCV::SplitF64Pseudo:
9771     return emitSplitF64Pseudo(MI, BB);
9772   case RISCV::PseudoQuietFLE_H:
9773     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9774   case RISCV::PseudoQuietFLT_H:
9775     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9776   case RISCV::PseudoQuietFLE_S:
9777     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9778   case RISCV::PseudoQuietFLT_S:
9779     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9780   case RISCV::PseudoQuietFLE_D:
9781     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9782   case RISCV::PseudoQuietFLT_D:
9783     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9784   }
9785 }
9786 
9787 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9788                                                         SDNode *Node) const {
9789   // Add FRM dependency to any instructions with dynamic rounding mode.
9790   unsigned Opc = MI.getOpcode();
9791   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9792   if (Idx < 0)
9793     return;
9794   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9795     return;
9796   // If the instruction already reads FRM, don't add another read.
9797   if (MI.readsRegister(RISCV::FRM))
9798     return;
9799   MI.addOperand(
9800       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9801 }
9802 
9803 // Calling Convention Implementation.
9804 // The expectations for frontend ABI lowering vary from target to target.
9805 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9806 // details, but this is a longer term goal. For now, we simply try to keep the
9807 // role of the frontend as simple and well-defined as possible. The rules can
9808 // be summarised as:
9809 // * Never split up large scalar arguments. We handle them here.
9810 // * If a hardfloat calling convention is being used, and the struct may be
9811 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9812 // available, then pass as two separate arguments. If either the GPRs or FPRs
9813 // are exhausted, then pass according to the rule below.
9814 // * If a struct could never be passed in registers or directly in a stack
9815 // slot (as it is larger than 2*XLEN and the floating point rules don't
9816 // apply), then pass it using a pointer with the byval attribute.
9817 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9818 // word-sized array or a 2*XLEN scalar (depending on alignment).
9819 // * The frontend can determine whether a struct is returned by reference or
9820 // not based on its size and fields. If it will be returned by reference, the
9821 // frontend must modify the prototype so a pointer with the sret annotation is
9822 // passed as the first argument. This is not necessary for large scalar
9823 // returns.
9824 // * Struct return values and varargs should be coerced to structs containing
9825 // register-size fields in the same situations they would be for fixed
9826 // arguments.
9827 
9828 static const MCPhysReg ArgGPRs[] = {
9829   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9830   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9831 };
9832 static const MCPhysReg ArgFPR16s[] = {
9833   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9834   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9835 };
9836 static const MCPhysReg ArgFPR32s[] = {
9837   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9838   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9839 };
9840 static const MCPhysReg ArgFPR64s[] = {
9841   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9842   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9843 };
9844 // This is an interim calling convention and it may be changed in the future.
9845 static const MCPhysReg ArgVRs[] = {
9846     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9847     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9848     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9849 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9850                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9851                                      RISCV::V20M2, RISCV::V22M2};
9852 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9853                                      RISCV::V20M4};
9854 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9855 
9856 // Pass a 2*XLEN argument that has been split into two XLEN values through
9857 // registers or the stack as necessary.
9858 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9859                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9860                                 MVT ValVT2, MVT LocVT2,
9861                                 ISD::ArgFlagsTy ArgFlags2) {
9862   unsigned XLenInBytes = XLen / 8;
9863   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9864     // At least one half can be passed via register.
9865     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9866                                      VA1.getLocVT(), CCValAssign::Full));
9867   } else {
9868     // Both halves must be passed on the stack, with proper alignment.
9869     Align StackAlign =
9870         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9871     State.addLoc(
9872         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9873                             State.AllocateStack(XLenInBytes, StackAlign),
9874                             VA1.getLocVT(), CCValAssign::Full));
9875     State.addLoc(CCValAssign::getMem(
9876         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9877         LocVT2, CCValAssign::Full));
9878     return false;
9879   }
9880 
9881   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9882     // The second half can also be passed via register.
9883     State.addLoc(
9884         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9885   } else {
9886     // The second half is passed via the stack, without additional alignment.
9887     State.addLoc(CCValAssign::getMem(
9888         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9889         LocVT2, CCValAssign::Full));
9890   }
9891 
9892   return false;
9893 }
9894 
9895 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9896                                Optional<unsigned> FirstMaskArgument,
9897                                CCState &State, const RISCVTargetLowering &TLI) {
9898   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9899   if (RC == &RISCV::VRRegClass) {
9900     // Assign the first mask argument to V0.
9901     // This is an interim calling convention and it may be changed in the
9902     // future.
9903     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
9904       return State.AllocateReg(RISCV::V0);
9905     return State.AllocateReg(ArgVRs);
9906   }
9907   if (RC == &RISCV::VRM2RegClass)
9908     return State.AllocateReg(ArgVRM2s);
9909   if (RC == &RISCV::VRM4RegClass)
9910     return State.AllocateReg(ArgVRM4s);
9911   if (RC == &RISCV::VRM8RegClass)
9912     return State.AllocateReg(ArgVRM8s);
9913   llvm_unreachable("Unhandled register class for ValueType");
9914 }
9915 
9916 // Implements the RISC-V calling convention. Returns true upon failure.
9917 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9918                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9919                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9920                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9921                      Optional<unsigned> FirstMaskArgument) {
9922   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9923   assert(XLen == 32 || XLen == 64);
9924   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9925 
9926   // Any return value split in to more than two values can't be returned
9927   // directly. Vectors are returned via the available vector registers.
9928   if (!LocVT.isVector() && IsRet && ValNo > 1)
9929     return true;
9930 
9931   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9932   // variadic argument, or if no F16/F32 argument registers are available.
9933   bool UseGPRForF16_F32 = true;
9934   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9935   // variadic argument, or if no F64 argument registers are available.
9936   bool UseGPRForF64 = true;
9937 
9938   switch (ABI) {
9939   default:
9940     llvm_unreachable("Unexpected ABI");
9941   case RISCVABI::ABI_ILP32:
9942   case RISCVABI::ABI_LP64:
9943     break;
9944   case RISCVABI::ABI_ILP32F:
9945   case RISCVABI::ABI_LP64F:
9946     UseGPRForF16_F32 = !IsFixed;
9947     break;
9948   case RISCVABI::ABI_ILP32D:
9949   case RISCVABI::ABI_LP64D:
9950     UseGPRForF16_F32 = !IsFixed;
9951     UseGPRForF64 = !IsFixed;
9952     break;
9953   }
9954 
9955   // FPR16, FPR32, and FPR64 alias each other.
9956   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9957     UseGPRForF16_F32 = true;
9958     UseGPRForF64 = true;
9959   }
9960 
9961   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9962   // similar local variables rather than directly checking against the target
9963   // ABI.
9964 
9965   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9966     LocVT = XLenVT;
9967     LocInfo = CCValAssign::BCvt;
9968   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9969     LocVT = MVT::i64;
9970     LocInfo = CCValAssign::BCvt;
9971   }
9972 
9973   // If this is a variadic argument, the RISC-V calling convention requires
9974   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9975   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9976   // be used regardless of whether the original argument was split during
9977   // legalisation or not. The argument will not be passed by registers if the
9978   // original type is larger than 2*XLEN, so the register alignment rule does
9979   // not apply.
9980   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9981   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9982       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9983     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9984     // Skip 'odd' register if necessary.
9985     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9986       State.AllocateReg(ArgGPRs);
9987   }
9988 
9989   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9990   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9991       State.getPendingArgFlags();
9992 
9993   assert(PendingLocs.size() == PendingArgFlags.size() &&
9994          "PendingLocs and PendingArgFlags out of sync");
9995 
9996   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9997   // registers are exhausted.
9998   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9999     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
10000            "Can't lower f64 if it is split");
10001     // Depending on available argument GPRS, f64 may be passed in a pair of
10002     // GPRs, split between a GPR and the stack, or passed completely on the
10003     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10004     // cases.
10005     Register Reg = State.AllocateReg(ArgGPRs);
10006     LocVT = MVT::i32;
10007     if (!Reg) {
10008       unsigned StackOffset = State.AllocateStack(8, Align(8));
10009       State.addLoc(
10010           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10011       return false;
10012     }
10013     if (!State.AllocateReg(ArgGPRs))
10014       State.AllocateStack(4, Align(4));
10015     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10016     return false;
10017   }
10018 
10019   // Fixed-length vectors are located in the corresponding scalable-vector
10020   // container types.
10021   if (ValVT.isFixedLengthVector())
10022     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10023 
10024   // Split arguments might be passed indirectly, so keep track of the pending
10025   // values. Split vectors are passed via a mix of registers and indirectly, so
10026   // treat them as we would any other argument.
10027   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10028     LocVT = XLenVT;
10029     LocInfo = CCValAssign::Indirect;
10030     PendingLocs.push_back(
10031         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10032     PendingArgFlags.push_back(ArgFlags);
10033     if (!ArgFlags.isSplitEnd()) {
10034       return false;
10035     }
10036   }
10037 
10038   // If the split argument only had two elements, it should be passed directly
10039   // in registers or on the stack.
10040   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10041       PendingLocs.size() <= 2) {
10042     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10043     // Apply the normal calling convention rules to the first half of the
10044     // split argument.
10045     CCValAssign VA = PendingLocs[0];
10046     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10047     PendingLocs.clear();
10048     PendingArgFlags.clear();
10049     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10050                                ArgFlags);
10051   }
10052 
10053   // Allocate to a register if possible, or else a stack slot.
10054   Register Reg;
10055   unsigned StoreSizeBytes = XLen / 8;
10056   Align StackAlign = Align(XLen / 8);
10057 
10058   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10059     Reg = State.AllocateReg(ArgFPR16s);
10060   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10061     Reg = State.AllocateReg(ArgFPR32s);
10062   else if (ValVT == MVT::f64 && !UseGPRForF64)
10063     Reg = State.AllocateReg(ArgFPR64s);
10064   else if (ValVT.isVector()) {
10065     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10066     if (!Reg) {
10067       // For return values, the vector must be passed fully via registers or
10068       // via the stack.
10069       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10070       // but we're using all of them.
10071       if (IsRet)
10072         return true;
10073       // Try using a GPR to pass the address
10074       if ((Reg = State.AllocateReg(ArgGPRs))) {
10075         LocVT = XLenVT;
10076         LocInfo = CCValAssign::Indirect;
10077       } else if (ValVT.isScalableVector()) {
10078         LocVT = XLenVT;
10079         LocInfo = CCValAssign::Indirect;
10080       } else {
10081         // Pass fixed-length vectors on the stack.
10082         LocVT = ValVT;
10083         StoreSizeBytes = ValVT.getStoreSize();
10084         // Align vectors to their element sizes, being careful for vXi1
10085         // vectors.
10086         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10087       }
10088     }
10089   } else {
10090     Reg = State.AllocateReg(ArgGPRs);
10091   }
10092 
10093   unsigned StackOffset =
10094       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10095 
10096   // If we reach this point and PendingLocs is non-empty, we must be at the
10097   // end of a split argument that must be passed indirectly.
10098   if (!PendingLocs.empty()) {
10099     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10100     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10101 
10102     for (auto &It : PendingLocs) {
10103       if (Reg)
10104         It.convertToReg(Reg);
10105       else
10106         It.convertToMem(StackOffset);
10107       State.addLoc(It);
10108     }
10109     PendingLocs.clear();
10110     PendingArgFlags.clear();
10111     return false;
10112   }
10113 
10114   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10115           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10116          "Expected an XLenVT or vector types at this stage");
10117 
10118   if (Reg) {
10119     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10120     return false;
10121   }
10122 
10123   // When a floating-point value is passed on the stack, no bit-conversion is
10124   // needed.
10125   if (ValVT.isFloatingPoint()) {
10126     LocVT = ValVT;
10127     LocInfo = CCValAssign::Full;
10128   }
10129   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10130   return false;
10131 }
10132 
10133 template <typename ArgTy>
10134 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10135   for (const auto &ArgIdx : enumerate(Args)) {
10136     MVT ArgVT = ArgIdx.value().VT;
10137     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10138       return ArgIdx.index();
10139   }
10140   return None;
10141 }
10142 
10143 void RISCVTargetLowering::analyzeInputArgs(
10144     MachineFunction &MF, CCState &CCInfo,
10145     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10146     RISCVCCAssignFn Fn) const {
10147   unsigned NumArgs = Ins.size();
10148   FunctionType *FType = MF.getFunction().getFunctionType();
10149 
10150   Optional<unsigned> FirstMaskArgument;
10151   if (Subtarget.hasVInstructions())
10152     FirstMaskArgument = preAssignMask(Ins);
10153 
10154   for (unsigned i = 0; i != NumArgs; ++i) {
10155     MVT ArgVT = Ins[i].VT;
10156     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10157 
10158     Type *ArgTy = nullptr;
10159     if (IsRet)
10160       ArgTy = FType->getReturnType();
10161     else if (Ins[i].isOrigArg())
10162       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10163 
10164     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10165     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10166            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10167            FirstMaskArgument)) {
10168       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10169                         << EVT(ArgVT).getEVTString() << '\n');
10170       llvm_unreachable(nullptr);
10171     }
10172   }
10173 }
10174 
10175 void RISCVTargetLowering::analyzeOutputArgs(
10176     MachineFunction &MF, CCState &CCInfo,
10177     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10178     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10179   unsigned NumArgs = Outs.size();
10180 
10181   Optional<unsigned> FirstMaskArgument;
10182   if (Subtarget.hasVInstructions())
10183     FirstMaskArgument = preAssignMask(Outs);
10184 
10185   for (unsigned i = 0; i != NumArgs; i++) {
10186     MVT ArgVT = Outs[i].VT;
10187     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10188     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10189 
10190     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10191     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10192            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10193            FirstMaskArgument)) {
10194       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10195                         << EVT(ArgVT).getEVTString() << "\n");
10196       llvm_unreachable(nullptr);
10197     }
10198   }
10199 }
10200 
10201 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10202 // values.
10203 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10204                                    const CCValAssign &VA, const SDLoc &DL,
10205                                    const RISCVSubtarget &Subtarget) {
10206   switch (VA.getLocInfo()) {
10207   default:
10208     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10209   case CCValAssign::Full:
10210     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10211       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10212     break;
10213   case CCValAssign::BCvt:
10214     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10215       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10216     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10217       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10218     else
10219       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10220     break;
10221   }
10222   return Val;
10223 }
10224 
10225 // The caller is responsible for loading the full value if the argument is
10226 // passed with CCValAssign::Indirect.
10227 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10228                                 const CCValAssign &VA, const SDLoc &DL,
10229                                 const RISCVTargetLowering &TLI) {
10230   MachineFunction &MF = DAG.getMachineFunction();
10231   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10232   EVT LocVT = VA.getLocVT();
10233   SDValue Val;
10234   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10235   Register VReg = RegInfo.createVirtualRegister(RC);
10236   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10237   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10238 
10239   if (VA.getLocInfo() == CCValAssign::Indirect)
10240     return Val;
10241 
10242   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10243 }
10244 
10245 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10246                                    const CCValAssign &VA, const SDLoc &DL,
10247                                    const RISCVSubtarget &Subtarget) {
10248   EVT LocVT = VA.getLocVT();
10249 
10250   switch (VA.getLocInfo()) {
10251   default:
10252     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10253   case CCValAssign::Full:
10254     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10255       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10256     break;
10257   case CCValAssign::BCvt:
10258     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10259       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10260     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10261       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10262     else
10263       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10264     break;
10265   }
10266   return Val;
10267 }
10268 
10269 // The caller is responsible for loading the full value if the argument is
10270 // passed with CCValAssign::Indirect.
10271 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10272                                 const CCValAssign &VA, const SDLoc &DL) {
10273   MachineFunction &MF = DAG.getMachineFunction();
10274   MachineFrameInfo &MFI = MF.getFrameInfo();
10275   EVT LocVT = VA.getLocVT();
10276   EVT ValVT = VA.getValVT();
10277   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10278   if (ValVT.isScalableVector()) {
10279     // When the value is a scalable vector, we save the pointer which points to
10280     // the scalable vector value in the stack. The ValVT will be the pointer
10281     // type, instead of the scalable vector type.
10282     ValVT = LocVT;
10283   }
10284   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10285                                  /*IsImmutable=*/true);
10286   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10287   SDValue Val;
10288 
10289   ISD::LoadExtType ExtType;
10290   switch (VA.getLocInfo()) {
10291   default:
10292     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10293   case CCValAssign::Full:
10294   case CCValAssign::Indirect:
10295   case CCValAssign::BCvt:
10296     ExtType = ISD::NON_EXTLOAD;
10297     break;
10298   }
10299   Val = DAG.getExtLoad(
10300       ExtType, DL, LocVT, Chain, FIN,
10301       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10302   return Val;
10303 }
10304 
10305 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10306                                        const CCValAssign &VA, const SDLoc &DL) {
10307   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10308          "Unexpected VA");
10309   MachineFunction &MF = DAG.getMachineFunction();
10310   MachineFrameInfo &MFI = MF.getFrameInfo();
10311   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10312 
10313   if (VA.isMemLoc()) {
10314     // f64 is passed on the stack.
10315     int FI =
10316         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10317     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10318     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10319                        MachinePointerInfo::getFixedStack(MF, FI));
10320   }
10321 
10322   assert(VA.isRegLoc() && "Expected register VA assignment");
10323 
10324   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10325   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10326   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10327   SDValue Hi;
10328   if (VA.getLocReg() == RISCV::X17) {
10329     // Second half of f64 is passed on the stack.
10330     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10331     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10332     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10333                      MachinePointerInfo::getFixedStack(MF, FI));
10334   } else {
10335     // Second half of f64 is passed in another GPR.
10336     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10337     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10338     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10339   }
10340   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10341 }
10342 
10343 // FastCC has less than 1% performance improvement for some particular
10344 // benchmark. But theoretically, it may has benenfit for some cases.
10345 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10346                             unsigned ValNo, MVT ValVT, MVT LocVT,
10347                             CCValAssign::LocInfo LocInfo,
10348                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10349                             bool IsFixed, bool IsRet, Type *OrigTy,
10350                             const RISCVTargetLowering &TLI,
10351                             Optional<unsigned> FirstMaskArgument) {
10352 
10353   // X5 and X6 might be used for save-restore libcall.
10354   static const MCPhysReg GPRList[] = {
10355       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10356       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10357       RISCV::X29, RISCV::X30, RISCV::X31};
10358 
10359   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10360     if (unsigned Reg = State.AllocateReg(GPRList)) {
10361       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10362       return false;
10363     }
10364   }
10365 
10366   if (LocVT == MVT::f16) {
10367     static const MCPhysReg FPR16List[] = {
10368         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10369         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10370         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10371         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10372     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10373       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10374       return false;
10375     }
10376   }
10377 
10378   if (LocVT == MVT::f32) {
10379     static const MCPhysReg FPR32List[] = {
10380         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10381         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10382         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10383         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10384     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10385       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10386       return false;
10387     }
10388   }
10389 
10390   if (LocVT == MVT::f64) {
10391     static const MCPhysReg FPR64List[] = {
10392         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10393         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10394         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10395         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10396     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10397       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10398       return false;
10399     }
10400   }
10401 
10402   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10403     unsigned Offset4 = State.AllocateStack(4, Align(4));
10404     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10405     return false;
10406   }
10407 
10408   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10409     unsigned Offset5 = State.AllocateStack(8, Align(8));
10410     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10411     return false;
10412   }
10413 
10414   if (LocVT.isVector()) {
10415     if (unsigned Reg =
10416             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10417       // Fixed-length vectors are located in the corresponding scalable-vector
10418       // container types.
10419       if (ValVT.isFixedLengthVector())
10420         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10421       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10422     } else {
10423       // Try and pass the address via a "fast" GPR.
10424       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10425         LocInfo = CCValAssign::Indirect;
10426         LocVT = TLI.getSubtarget().getXLenVT();
10427         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10428       } else if (ValVT.isFixedLengthVector()) {
10429         auto StackAlign =
10430             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10431         unsigned StackOffset =
10432             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10433         State.addLoc(
10434             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10435       } else {
10436         // Can't pass scalable vectors on the stack.
10437         return true;
10438       }
10439     }
10440 
10441     return false;
10442   }
10443 
10444   return true; // CC didn't match.
10445 }
10446 
10447 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10448                          CCValAssign::LocInfo LocInfo,
10449                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10450 
10451   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10452     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10453     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10454     static const MCPhysReg GPRList[] = {
10455         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10456         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10457     if (unsigned Reg = State.AllocateReg(GPRList)) {
10458       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10459       return false;
10460     }
10461   }
10462 
10463   if (LocVT == MVT::f32) {
10464     // Pass in STG registers: F1, ..., F6
10465     //                        fs0 ... fs5
10466     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10467                                           RISCV::F18_F, RISCV::F19_F,
10468                                           RISCV::F20_F, RISCV::F21_F};
10469     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10470       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10471       return false;
10472     }
10473   }
10474 
10475   if (LocVT == MVT::f64) {
10476     // Pass in STG registers: D1, ..., D6
10477     //                        fs6 ... fs11
10478     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10479                                           RISCV::F24_D, RISCV::F25_D,
10480                                           RISCV::F26_D, RISCV::F27_D};
10481     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10482       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10483       return false;
10484     }
10485   }
10486 
10487   report_fatal_error("No registers left in GHC calling convention");
10488   return true;
10489 }
10490 
10491 // Transform physical registers into virtual registers.
10492 SDValue RISCVTargetLowering::LowerFormalArguments(
10493     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10494     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10495     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10496 
10497   MachineFunction &MF = DAG.getMachineFunction();
10498 
10499   switch (CallConv) {
10500   default:
10501     report_fatal_error("Unsupported calling convention");
10502   case CallingConv::C:
10503   case CallingConv::Fast:
10504     break;
10505   case CallingConv::GHC:
10506     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10507         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10508       report_fatal_error(
10509         "GHC calling convention requires the F and D instruction set extensions");
10510   }
10511 
10512   const Function &Func = MF.getFunction();
10513   if (Func.hasFnAttribute("interrupt")) {
10514     if (!Func.arg_empty())
10515       report_fatal_error(
10516         "Functions with the interrupt attribute cannot have arguments!");
10517 
10518     StringRef Kind =
10519       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10520 
10521     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10522       report_fatal_error(
10523         "Function interrupt attribute argument not supported!");
10524   }
10525 
10526   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10527   MVT XLenVT = Subtarget.getXLenVT();
10528   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10529   // Used with vargs to acumulate store chains.
10530   std::vector<SDValue> OutChains;
10531 
10532   // Assign locations to all of the incoming arguments.
10533   SmallVector<CCValAssign, 16> ArgLocs;
10534   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10535 
10536   if (CallConv == CallingConv::GHC)
10537     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10538   else
10539     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10540                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10541                                                    : CC_RISCV);
10542 
10543   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10544     CCValAssign &VA = ArgLocs[i];
10545     SDValue ArgValue;
10546     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10547     // case.
10548     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10549       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10550     else if (VA.isRegLoc())
10551       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10552     else
10553       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10554 
10555     if (VA.getLocInfo() == CCValAssign::Indirect) {
10556       // If the original argument was split and passed by reference (e.g. i128
10557       // on RV32), we need to load all parts of it here (using the same
10558       // address). Vectors may be partly split to registers and partly to the
10559       // stack, in which case the base address is partly offset and subsequent
10560       // stores are relative to that.
10561       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10562                                    MachinePointerInfo()));
10563       unsigned ArgIndex = Ins[i].OrigArgIndex;
10564       unsigned ArgPartOffset = Ins[i].PartOffset;
10565       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10566       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10567         CCValAssign &PartVA = ArgLocs[i + 1];
10568         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10569         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10570         if (PartVA.getValVT().isScalableVector())
10571           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10572         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10573         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10574                                      MachinePointerInfo()));
10575         ++i;
10576       }
10577       continue;
10578     }
10579     InVals.push_back(ArgValue);
10580   }
10581 
10582   if (IsVarArg) {
10583     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10584     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10585     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10586     MachineFrameInfo &MFI = MF.getFrameInfo();
10587     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10588     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10589 
10590     // Offset of the first variable argument from stack pointer, and size of
10591     // the vararg save area. For now, the varargs save area is either zero or
10592     // large enough to hold a0-a7.
10593     int VaArgOffset, VarArgsSaveSize;
10594 
10595     // If all registers are allocated, then all varargs must be passed on the
10596     // stack and we don't need to save any argregs.
10597     if (ArgRegs.size() == Idx) {
10598       VaArgOffset = CCInfo.getNextStackOffset();
10599       VarArgsSaveSize = 0;
10600     } else {
10601       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10602       VaArgOffset = -VarArgsSaveSize;
10603     }
10604 
10605     // Record the frame index of the first variable argument
10606     // which is a value necessary to VASTART.
10607     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10608     RVFI->setVarArgsFrameIndex(FI);
10609 
10610     // If saving an odd number of registers then create an extra stack slot to
10611     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10612     // offsets to even-numbered registered remain 2*XLEN-aligned.
10613     if (Idx % 2) {
10614       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10615       VarArgsSaveSize += XLenInBytes;
10616     }
10617 
10618     // Copy the integer registers that may have been used for passing varargs
10619     // to the vararg save area.
10620     for (unsigned I = Idx; I < ArgRegs.size();
10621          ++I, VaArgOffset += XLenInBytes) {
10622       const Register Reg = RegInfo.createVirtualRegister(RC);
10623       RegInfo.addLiveIn(ArgRegs[I], Reg);
10624       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10625       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10626       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10627       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10628                                    MachinePointerInfo::getFixedStack(MF, FI));
10629       cast<StoreSDNode>(Store.getNode())
10630           ->getMemOperand()
10631           ->setValue((Value *)nullptr);
10632       OutChains.push_back(Store);
10633     }
10634     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10635   }
10636 
10637   // All stores are grouped in one node to allow the matching between
10638   // the size of Ins and InVals. This only happens for vararg functions.
10639   if (!OutChains.empty()) {
10640     OutChains.push_back(Chain);
10641     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10642   }
10643 
10644   return Chain;
10645 }
10646 
10647 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10648 /// for tail call optimization.
10649 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10650 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10651     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10652     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10653 
10654   auto &Callee = CLI.Callee;
10655   auto CalleeCC = CLI.CallConv;
10656   auto &Outs = CLI.Outs;
10657   auto &Caller = MF.getFunction();
10658   auto CallerCC = Caller.getCallingConv();
10659 
10660   // Exception-handling functions need a special set of instructions to
10661   // indicate a return to the hardware. Tail-calling another function would
10662   // probably break this.
10663   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10664   // should be expanded as new function attributes are introduced.
10665   if (Caller.hasFnAttribute("interrupt"))
10666     return false;
10667 
10668   // Do not tail call opt if the stack is used to pass parameters.
10669   if (CCInfo.getNextStackOffset() != 0)
10670     return false;
10671 
10672   // Do not tail call opt if any parameters need to be passed indirectly.
10673   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10674   // passed indirectly. So the address of the value will be passed in a
10675   // register, or if not available, then the address is put on the stack. In
10676   // order to pass indirectly, space on the stack often needs to be allocated
10677   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10678   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10679   // are passed CCValAssign::Indirect.
10680   for (auto &VA : ArgLocs)
10681     if (VA.getLocInfo() == CCValAssign::Indirect)
10682       return false;
10683 
10684   // Do not tail call opt if either caller or callee uses struct return
10685   // semantics.
10686   auto IsCallerStructRet = Caller.hasStructRetAttr();
10687   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10688   if (IsCallerStructRet || IsCalleeStructRet)
10689     return false;
10690 
10691   // Externally-defined functions with weak linkage should not be
10692   // tail-called. The behaviour of branch instructions in this situation (as
10693   // used for tail calls) is implementation-defined, so we cannot rely on the
10694   // linker replacing the tail call with a return.
10695   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10696     const GlobalValue *GV = G->getGlobal();
10697     if (GV->hasExternalWeakLinkage())
10698       return false;
10699   }
10700 
10701   // The callee has to preserve all registers the caller needs to preserve.
10702   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10703   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10704   if (CalleeCC != CallerCC) {
10705     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10706     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10707       return false;
10708   }
10709 
10710   // Byval parameters hand the function a pointer directly into the stack area
10711   // we want to reuse during a tail call. Working around this *is* possible
10712   // but less efficient and uglier in LowerCall.
10713   for (auto &Arg : Outs)
10714     if (Arg.Flags.isByVal())
10715       return false;
10716 
10717   return true;
10718 }
10719 
10720 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10721   return DAG.getDataLayout().getPrefTypeAlign(
10722       VT.getTypeForEVT(*DAG.getContext()));
10723 }
10724 
10725 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10726 // and output parameter nodes.
10727 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10728                                        SmallVectorImpl<SDValue> &InVals) const {
10729   SelectionDAG &DAG = CLI.DAG;
10730   SDLoc &DL = CLI.DL;
10731   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10732   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10733   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10734   SDValue Chain = CLI.Chain;
10735   SDValue Callee = CLI.Callee;
10736   bool &IsTailCall = CLI.IsTailCall;
10737   CallingConv::ID CallConv = CLI.CallConv;
10738   bool IsVarArg = CLI.IsVarArg;
10739   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10740   MVT XLenVT = Subtarget.getXLenVT();
10741 
10742   MachineFunction &MF = DAG.getMachineFunction();
10743 
10744   // Analyze the operands of the call, assigning locations to each operand.
10745   SmallVector<CCValAssign, 16> ArgLocs;
10746   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10747 
10748   if (CallConv == CallingConv::GHC)
10749     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10750   else
10751     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10752                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10753                                                     : CC_RISCV);
10754 
10755   // Check if it's really possible to do a tail call.
10756   if (IsTailCall)
10757     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10758 
10759   if (IsTailCall)
10760     ++NumTailCalls;
10761   else if (CLI.CB && CLI.CB->isMustTailCall())
10762     report_fatal_error("failed to perform tail call elimination on a call "
10763                        "site marked musttail");
10764 
10765   // Get a count of how many bytes are to be pushed on the stack.
10766   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10767 
10768   // Create local copies for byval args
10769   SmallVector<SDValue, 8> ByValArgs;
10770   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10771     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10772     if (!Flags.isByVal())
10773       continue;
10774 
10775     SDValue Arg = OutVals[i];
10776     unsigned Size = Flags.getByValSize();
10777     Align Alignment = Flags.getNonZeroByValAlign();
10778 
10779     int FI =
10780         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10781     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10782     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10783 
10784     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10785                           /*IsVolatile=*/false,
10786                           /*AlwaysInline=*/false, IsTailCall,
10787                           MachinePointerInfo(), MachinePointerInfo());
10788     ByValArgs.push_back(FIPtr);
10789   }
10790 
10791   if (!IsTailCall)
10792     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10793 
10794   // Copy argument values to their designated locations.
10795   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10796   SmallVector<SDValue, 8> MemOpChains;
10797   SDValue StackPtr;
10798   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10799     CCValAssign &VA = ArgLocs[i];
10800     SDValue ArgValue = OutVals[i];
10801     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10802 
10803     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10804     bool IsF64OnRV32DSoftABI =
10805         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10806     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10807       SDValue SplitF64 = DAG.getNode(
10808           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10809       SDValue Lo = SplitF64.getValue(0);
10810       SDValue Hi = SplitF64.getValue(1);
10811 
10812       Register RegLo = VA.getLocReg();
10813       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10814 
10815       if (RegLo == RISCV::X17) {
10816         // Second half of f64 is passed on the stack.
10817         // Work out the address of the stack slot.
10818         if (!StackPtr.getNode())
10819           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10820         // Emit the store.
10821         MemOpChains.push_back(
10822             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10823       } else {
10824         // Second half of f64 is passed in another GPR.
10825         assert(RegLo < RISCV::X31 && "Invalid register pair");
10826         Register RegHigh = RegLo + 1;
10827         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10828       }
10829       continue;
10830     }
10831 
10832     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10833     // as any other MemLoc.
10834 
10835     // Promote the value if needed.
10836     // For now, only handle fully promoted and indirect arguments.
10837     if (VA.getLocInfo() == CCValAssign::Indirect) {
10838       // Store the argument in a stack slot and pass its address.
10839       Align StackAlign =
10840           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10841                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10842       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10843       // If the original argument was split (e.g. i128), we need
10844       // to store the required parts of it here (and pass just one address).
10845       // Vectors may be partly split to registers and partly to the stack, in
10846       // which case the base address is partly offset and subsequent stores are
10847       // relative to that.
10848       unsigned ArgIndex = Outs[i].OrigArgIndex;
10849       unsigned ArgPartOffset = Outs[i].PartOffset;
10850       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10851       // Calculate the total size to store. We don't have access to what we're
10852       // actually storing other than performing the loop and collecting the
10853       // info.
10854       SmallVector<std::pair<SDValue, SDValue>> Parts;
10855       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10856         SDValue PartValue = OutVals[i + 1];
10857         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10858         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10859         EVT PartVT = PartValue.getValueType();
10860         if (PartVT.isScalableVector())
10861           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10862         StoredSize += PartVT.getStoreSize();
10863         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10864         Parts.push_back(std::make_pair(PartValue, Offset));
10865         ++i;
10866       }
10867       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10868       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10869       MemOpChains.push_back(
10870           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10871                        MachinePointerInfo::getFixedStack(MF, FI)));
10872       for (const auto &Part : Parts) {
10873         SDValue PartValue = Part.first;
10874         SDValue PartOffset = Part.second;
10875         SDValue Address =
10876             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10877         MemOpChains.push_back(
10878             DAG.getStore(Chain, DL, PartValue, Address,
10879                          MachinePointerInfo::getFixedStack(MF, FI)));
10880       }
10881       ArgValue = SpillSlot;
10882     } else {
10883       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10884     }
10885 
10886     // Use local copy if it is a byval arg.
10887     if (Flags.isByVal())
10888       ArgValue = ByValArgs[j++];
10889 
10890     if (VA.isRegLoc()) {
10891       // Queue up the argument copies and emit them at the end.
10892       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10893     } else {
10894       assert(VA.isMemLoc() && "Argument not register or memory");
10895       assert(!IsTailCall && "Tail call not allowed if stack is used "
10896                             "for passing parameters");
10897 
10898       // Work out the address of the stack slot.
10899       if (!StackPtr.getNode())
10900         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10901       SDValue Address =
10902           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10903                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10904 
10905       // Emit the store.
10906       MemOpChains.push_back(
10907           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10908     }
10909   }
10910 
10911   // Join the stores, which are independent of one another.
10912   if (!MemOpChains.empty())
10913     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10914 
10915   SDValue Glue;
10916 
10917   // Build a sequence of copy-to-reg nodes, chained and glued together.
10918   for (auto &Reg : RegsToPass) {
10919     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10920     Glue = Chain.getValue(1);
10921   }
10922 
10923   // Validate that none of the argument registers have been marked as
10924   // reserved, if so report an error. Do the same for the return address if this
10925   // is not a tailcall.
10926   validateCCReservedRegs(RegsToPass, MF);
10927   if (!IsTailCall &&
10928       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10929     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10930         MF.getFunction(),
10931         "Return address register required, but has been reserved."});
10932 
10933   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10934   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10935   // split it and then direct call can be matched by PseudoCALL.
10936   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10937     const GlobalValue *GV = S->getGlobal();
10938 
10939     unsigned OpFlags = RISCVII::MO_CALL;
10940     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10941       OpFlags = RISCVII::MO_PLT;
10942 
10943     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10944   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10945     unsigned OpFlags = RISCVII::MO_CALL;
10946 
10947     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10948                                                  nullptr))
10949       OpFlags = RISCVII::MO_PLT;
10950 
10951     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10952   }
10953 
10954   // The first call operand is the chain and the second is the target address.
10955   SmallVector<SDValue, 8> Ops;
10956   Ops.push_back(Chain);
10957   Ops.push_back(Callee);
10958 
10959   // Add argument registers to the end of the list so that they are
10960   // known live into the call.
10961   for (auto &Reg : RegsToPass)
10962     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10963 
10964   if (!IsTailCall) {
10965     // Add a register mask operand representing the call-preserved registers.
10966     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10967     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10968     assert(Mask && "Missing call preserved mask for calling convention");
10969     Ops.push_back(DAG.getRegisterMask(Mask));
10970   }
10971 
10972   // Glue the call to the argument copies, if any.
10973   if (Glue.getNode())
10974     Ops.push_back(Glue);
10975 
10976   // Emit the call.
10977   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10978 
10979   if (IsTailCall) {
10980     MF.getFrameInfo().setHasTailCall();
10981     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10982   }
10983 
10984   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10985   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10986   Glue = Chain.getValue(1);
10987 
10988   // Mark the end of the call, which is glued to the call itself.
10989   Chain = DAG.getCALLSEQ_END(Chain,
10990                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10991                              DAG.getConstant(0, DL, PtrVT, true),
10992                              Glue, DL);
10993   Glue = Chain.getValue(1);
10994 
10995   // Assign locations to each value returned by this call.
10996   SmallVector<CCValAssign, 16> RVLocs;
10997   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10998   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10999 
11000   // Copy all of the result registers out of their specified physreg.
11001   for (auto &VA : RVLocs) {
11002     // Copy the value out
11003     SDValue RetValue =
11004         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11005     // Glue the RetValue to the end of the call sequence
11006     Chain = RetValue.getValue(1);
11007     Glue = RetValue.getValue(2);
11008 
11009     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11010       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11011       SDValue RetValue2 =
11012           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11013       Chain = RetValue2.getValue(1);
11014       Glue = RetValue2.getValue(2);
11015       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11016                              RetValue2);
11017     }
11018 
11019     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11020 
11021     InVals.push_back(RetValue);
11022   }
11023 
11024   return Chain;
11025 }
11026 
11027 bool RISCVTargetLowering::CanLowerReturn(
11028     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11029     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11030   SmallVector<CCValAssign, 16> RVLocs;
11031   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11032 
11033   Optional<unsigned> FirstMaskArgument;
11034   if (Subtarget.hasVInstructions())
11035     FirstMaskArgument = preAssignMask(Outs);
11036 
11037   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11038     MVT VT = Outs[i].VT;
11039     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11040     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11041     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11042                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11043                  *this, FirstMaskArgument))
11044       return false;
11045   }
11046   return true;
11047 }
11048 
11049 SDValue
11050 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11051                                  bool IsVarArg,
11052                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11053                                  const SmallVectorImpl<SDValue> &OutVals,
11054                                  const SDLoc &DL, SelectionDAG &DAG) const {
11055   const MachineFunction &MF = DAG.getMachineFunction();
11056   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11057 
11058   // Stores the assignment of the return value to a location.
11059   SmallVector<CCValAssign, 16> RVLocs;
11060 
11061   // Info about the registers and stack slot.
11062   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11063                  *DAG.getContext());
11064 
11065   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11066                     nullptr, CC_RISCV);
11067 
11068   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11069     report_fatal_error("GHC functions return void only");
11070 
11071   SDValue Glue;
11072   SmallVector<SDValue, 4> RetOps(1, Chain);
11073 
11074   // Copy the result values into the output registers.
11075   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11076     SDValue Val = OutVals[i];
11077     CCValAssign &VA = RVLocs[i];
11078     assert(VA.isRegLoc() && "Can only return in registers!");
11079 
11080     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11081       // Handle returning f64 on RV32D with a soft float ABI.
11082       assert(VA.isRegLoc() && "Expected return via registers");
11083       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11084                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11085       SDValue Lo = SplitF64.getValue(0);
11086       SDValue Hi = SplitF64.getValue(1);
11087       Register RegLo = VA.getLocReg();
11088       assert(RegLo < RISCV::X31 && "Invalid register pair");
11089       Register RegHi = RegLo + 1;
11090 
11091       if (STI.isRegisterReservedByUser(RegLo) ||
11092           STI.isRegisterReservedByUser(RegHi))
11093         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11094             MF.getFunction(),
11095             "Return value register required, but has been reserved."});
11096 
11097       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11098       Glue = Chain.getValue(1);
11099       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11100       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11101       Glue = Chain.getValue(1);
11102       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11103     } else {
11104       // Handle a 'normal' return.
11105       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11106       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11107 
11108       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11109         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11110             MF.getFunction(),
11111             "Return value register required, but has been reserved."});
11112 
11113       // Guarantee that all emitted copies are stuck together.
11114       Glue = Chain.getValue(1);
11115       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11116     }
11117   }
11118 
11119   RetOps[0] = Chain; // Update chain.
11120 
11121   // Add the glue node if we have it.
11122   if (Glue.getNode()) {
11123     RetOps.push_back(Glue);
11124   }
11125 
11126   unsigned RetOpc = RISCVISD::RET_FLAG;
11127   // Interrupt service routines use different return instructions.
11128   const Function &Func = DAG.getMachineFunction().getFunction();
11129   if (Func.hasFnAttribute("interrupt")) {
11130     if (!Func.getReturnType()->isVoidTy())
11131       report_fatal_error(
11132           "Functions with the interrupt attribute must have void return type!");
11133 
11134     MachineFunction &MF = DAG.getMachineFunction();
11135     StringRef Kind =
11136       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11137 
11138     if (Kind == "user")
11139       RetOpc = RISCVISD::URET_FLAG;
11140     else if (Kind == "supervisor")
11141       RetOpc = RISCVISD::SRET_FLAG;
11142     else
11143       RetOpc = RISCVISD::MRET_FLAG;
11144   }
11145 
11146   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11147 }
11148 
11149 void RISCVTargetLowering::validateCCReservedRegs(
11150     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11151     MachineFunction &MF) const {
11152   const Function &F = MF.getFunction();
11153   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11154 
11155   if (llvm::any_of(Regs, [&STI](auto Reg) {
11156         return STI.isRegisterReservedByUser(Reg.first);
11157       }))
11158     F.getContext().diagnose(DiagnosticInfoUnsupported{
11159         F, "Argument register required, but has been reserved."});
11160 }
11161 
11162 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11163   return CI->isTailCall();
11164 }
11165 
11166 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11167 #define NODE_NAME_CASE(NODE)                                                   \
11168   case RISCVISD::NODE:                                                         \
11169     return "RISCVISD::" #NODE;
11170   // clang-format off
11171   switch ((RISCVISD::NodeType)Opcode) {
11172   case RISCVISD::FIRST_NUMBER:
11173     break;
11174   NODE_NAME_CASE(RET_FLAG)
11175   NODE_NAME_CASE(URET_FLAG)
11176   NODE_NAME_CASE(SRET_FLAG)
11177   NODE_NAME_CASE(MRET_FLAG)
11178   NODE_NAME_CASE(CALL)
11179   NODE_NAME_CASE(SELECT_CC)
11180   NODE_NAME_CASE(BR_CC)
11181   NODE_NAME_CASE(BuildPairF64)
11182   NODE_NAME_CASE(SplitF64)
11183   NODE_NAME_CASE(TAIL)
11184   NODE_NAME_CASE(ADD_LO)
11185   NODE_NAME_CASE(HI)
11186   NODE_NAME_CASE(LLA)
11187   NODE_NAME_CASE(ADD_TPREL)
11188   NODE_NAME_CASE(MULHSU)
11189   NODE_NAME_CASE(SLLW)
11190   NODE_NAME_CASE(SRAW)
11191   NODE_NAME_CASE(SRLW)
11192   NODE_NAME_CASE(DIVW)
11193   NODE_NAME_CASE(DIVUW)
11194   NODE_NAME_CASE(REMUW)
11195   NODE_NAME_CASE(ROLW)
11196   NODE_NAME_CASE(RORW)
11197   NODE_NAME_CASE(CLZW)
11198   NODE_NAME_CASE(CTZW)
11199   NODE_NAME_CASE(FSLW)
11200   NODE_NAME_CASE(FSRW)
11201   NODE_NAME_CASE(FSL)
11202   NODE_NAME_CASE(FSR)
11203   NODE_NAME_CASE(FMV_H_X)
11204   NODE_NAME_CASE(FMV_X_ANYEXTH)
11205   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11206   NODE_NAME_CASE(FMV_W_X_RV64)
11207   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11208   NODE_NAME_CASE(FCVT_X)
11209   NODE_NAME_CASE(FCVT_XU)
11210   NODE_NAME_CASE(FCVT_W_RV64)
11211   NODE_NAME_CASE(FCVT_WU_RV64)
11212   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11213   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11214   NODE_NAME_CASE(READ_CYCLE_WIDE)
11215   NODE_NAME_CASE(GREV)
11216   NODE_NAME_CASE(GREVW)
11217   NODE_NAME_CASE(GORC)
11218   NODE_NAME_CASE(GORCW)
11219   NODE_NAME_CASE(SHFL)
11220   NODE_NAME_CASE(SHFLW)
11221   NODE_NAME_CASE(UNSHFL)
11222   NODE_NAME_CASE(UNSHFLW)
11223   NODE_NAME_CASE(BFP)
11224   NODE_NAME_CASE(BFPW)
11225   NODE_NAME_CASE(BCOMPRESS)
11226   NODE_NAME_CASE(BCOMPRESSW)
11227   NODE_NAME_CASE(BDECOMPRESS)
11228   NODE_NAME_CASE(BDECOMPRESSW)
11229   NODE_NAME_CASE(VMV_V_X_VL)
11230   NODE_NAME_CASE(VFMV_V_F_VL)
11231   NODE_NAME_CASE(VMV_X_S)
11232   NODE_NAME_CASE(VMV_S_X_VL)
11233   NODE_NAME_CASE(VFMV_S_F_VL)
11234   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11235   NODE_NAME_CASE(READ_VLENB)
11236   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11237   NODE_NAME_CASE(VSLIDEUP_VL)
11238   NODE_NAME_CASE(VSLIDE1UP_VL)
11239   NODE_NAME_CASE(VSLIDEDOWN_VL)
11240   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11241   NODE_NAME_CASE(VID_VL)
11242   NODE_NAME_CASE(VFNCVT_ROD_VL)
11243   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11244   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11245   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11246   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11247   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11248   NODE_NAME_CASE(VECREDUCE_AND_VL)
11249   NODE_NAME_CASE(VECREDUCE_OR_VL)
11250   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11251   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11252   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11253   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11254   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11255   NODE_NAME_CASE(ADD_VL)
11256   NODE_NAME_CASE(AND_VL)
11257   NODE_NAME_CASE(MUL_VL)
11258   NODE_NAME_CASE(OR_VL)
11259   NODE_NAME_CASE(SDIV_VL)
11260   NODE_NAME_CASE(SHL_VL)
11261   NODE_NAME_CASE(SREM_VL)
11262   NODE_NAME_CASE(SRA_VL)
11263   NODE_NAME_CASE(SRL_VL)
11264   NODE_NAME_CASE(SUB_VL)
11265   NODE_NAME_CASE(UDIV_VL)
11266   NODE_NAME_CASE(UREM_VL)
11267   NODE_NAME_CASE(XOR_VL)
11268   NODE_NAME_CASE(SADDSAT_VL)
11269   NODE_NAME_CASE(UADDSAT_VL)
11270   NODE_NAME_CASE(SSUBSAT_VL)
11271   NODE_NAME_CASE(USUBSAT_VL)
11272   NODE_NAME_CASE(FADD_VL)
11273   NODE_NAME_CASE(FSUB_VL)
11274   NODE_NAME_CASE(FMUL_VL)
11275   NODE_NAME_CASE(FDIV_VL)
11276   NODE_NAME_CASE(FNEG_VL)
11277   NODE_NAME_CASE(FABS_VL)
11278   NODE_NAME_CASE(FSQRT_VL)
11279   NODE_NAME_CASE(FMA_VL)
11280   NODE_NAME_CASE(FCOPYSIGN_VL)
11281   NODE_NAME_CASE(SMIN_VL)
11282   NODE_NAME_CASE(SMAX_VL)
11283   NODE_NAME_CASE(UMIN_VL)
11284   NODE_NAME_CASE(UMAX_VL)
11285   NODE_NAME_CASE(FMINNUM_VL)
11286   NODE_NAME_CASE(FMAXNUM_VL)
11287   NODE_NAME_CASE(MULHS_VL)
11288   NODE_NAME_CASE(MULHU_VL)
11289   NODE_NAME_CASE(FP_TO_SINT_VL)
11290   NODE_NAME_CASE(FP_TO_UINT_VL)
11291   NODE_NAME_CASE(SINT_TO_FP_VL)
11292   NODE_NAME_CASE(UINT_TO_FP_VL)
11293   NODE_NAME_CASE(FP_EXTEND_VL)
11294   NODE_NAME_CASE(FP_ROUND_VL)
11295   NODE_NAME_CASE(VWMUL_VL)
11296   NODE_NAME_CASE(VWMULU_VL)
11297   NODE_NAME_CASE(VWMULSU_VL)
11298   NODE_NAME_CASE(VWADD_VL)
11299   NODE_NAME_CASE(VWADDU_VL)
11300   NODE_NAME_CASE(VWSUB_VL)
11301   NODE_NAME_CASE(VWSUBU_VL)
11302   NODE_NAME_CASE(VWADD_W_VL)
11303   NODE_NAME_CASE(VWADDU_W_VL)
11304   NODE_NAME_CASE(VWSUB_W_VL)
11305   NODE_NAME_CASE(VWSUBU_W_VL)
11306   NODE_NAME_CASE(SETCC_VL)
11307   NODE_NAME_CASE(VSELECT_VL)
11308   NODE_NAME_CASE(VP_MERGE_VL)
11309   NODE_NAME_CASE(VMAND_VL)
11310   NODE_NAME_CASE(VMOR_VL)
11311   NODE_NAME_CASE(VMXOR_VL)
11312   NODE_NAME_CASE(VMCLR_VL)
11313   NODE_NAME_CASE(VMSET_VL)
11314   NODE_NAME_CASE(VRGATHER_VX_VL)
11315   NODE_NAME_CASE(VRGATHER_VV_VL)
11316   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11317   NODE_NAME_CASE(VSEXT_VL)
11318   NODE_NAME_CASE(VZEXT_VL)
11319   NODE_NAME_CASE(VCPOP_VL)
11320   NODE_NAME_CASE(READ_CSR)
11321   NODE_NAME_CASE(WRITE_CSR)
11322   NODE_NAME_CASE(SWAP_CSR)
11323   }
11324   // clang-format on
11325   return nullptr;
11326 #undef NODE_NAME_CASE
11327 }
11328 
11329 /// getConstraintType - Given a constraint letter, return the type of
11330 /// constraint it is for this target.
11331 RISCVTargetLowering::ConstraintType
11332 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11333   if (Constraint.size() == 1) {
11334     switch (Constraint[0]) {
11335     default:
11336       break;
11337     case 'f':
11338       return C_RegisterClass;
11339     case 'I':
11340     case 'J':
11341     case 'K':
11342       return C_Immediate;
11343     case 'A':
11344       return C_Memory;
11345     case 'S': // A symbolic address
11346       return C_Other;
11347     }
11348   } else {
11349     if (Constraint == "vr" || Constraint == "vm")
11350       return C_RegisterClass;
11351   }
11352   return TargetLowering::getConstraintType(Constraint);
11353 }
11354 
11355 std::pair<unsigned, const TargetRegisterClass *>
11356 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11357                                                   StringRef Constraint,
11358                                                   MVT VT) const {
11359   // First, see if this is a constraint that directly corresponds to a
11360   // RISCV register class.
11361   if (Constraint.size() == 1) {
11362     switch (Constraint[0]) {
11363     case 'r':
11364       // TODO: Support fixed vectors up to XLen for P extension?
11365       if (VT.isVector())
11366         break;
11367       return std::make_pair(0U, &RISCV::GPRRegClass);
11368     case 'f':
11369       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11370         return std::make_pair(0U, &RISCV::FPR16RegClass);
11371       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11372         return std::make_pair(0U, &RISCV::FPR32RegClass);
11373       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11374         return std::make_pair(0U, &RISCV::FPR64RegClass);
11375       break;
11376     default:
11377       break;
11378     }
11379   } else if (Constraint == "vr") {
11380     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11381                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11382       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11383         return std::make_pair(0U, RC);
11384     }
11385   } else if (Constraint == "vm") {
11386     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11387       return std::make_pair(0U, &RISCV::VMV0RegClass);
11388   }
11389 
11390   // Clang will correctly decode the usage of register name aliases into their
11391   // official names. However, other frontends like `rustc` do not. This allows
11392   // users of these frontends to use the ABI names for registers in LLVM-style
11393   // register constraints.
11394   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11395                                .Case("{zero}", RISCV::X0)
11396                                .Case("{ra}", RISCV::X1)
11397                                .Case("{sp}", RISCV::X2)
11398                                .Case("{gp}", RISCV::X3)
11399                                .Case("{tp}", RISCV::X4)
11400                                .Case("{t0}", RISCV::X5)
11401                                .Case("{t1}", RISCV::X6)
11402                                .Case("{t2}", RISCV::X7)
11403                                .Cases("{s0}", "{fp}", RISCV::X8)
11404                                .Case("{s1}", RISCV::X9)
11405                                .Case("{a0}", RISCV::X10)
11406                                .Case("{a1}", RISCV::X11)
11407                                .Case("{a2}", RISCV::X12)
11408                                .Case("{a3}", RISCV::X13)
11409                                .Case("{a4}", RISCV::X14)
11410                                .Case("{a5}", RISCV::X15)
11411                                .Case("{a6}", RISCV::X16)
11412                                .Case("{a7}", RISCV::X17)
11413                                .Case("{s2}", RISCV::X18)
11414                                .Case("{s3}", RISCV::X19)
11415                                .Case("{s4}", RISCV::X20)
11416                                .Case("{s5}", RISCV::X21)
11417                                .Case("{s6}", RISCV::X22)
11418                                .Case("{s7}", RISCV::X23)
11419                                .Case("{s8}", RISCV::X24)
11420                                .Case("{s9}", RISCV::X25)
11421                                .Case("{s10}", RISCV::X26)
11422                                .Case("{s11}", RISCV::X27)
11423                                .Case("{t3}", RISCV::X28)
11424                                .Case("{t4}", RISCV::X29)
11425                                .Case("{t5}", RISCV::X30)
11426                                .Case("{t6}", RISCV::X31)
11427                                .Default(RISCV::NoRegister);
11428   if (XRegFromAlias != RISCV::NoRegister)
11429     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11430 
11431   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11432   // TableGen record rather than the AsmName to choose registers for InlineAsm
11433   // constraints, plus we want to match those names to the widest floating point
11434   // register type available, manually select floating point registers here.
11435   //
11436   // The second case is the ABI name of the register, so that frontends can also
11437   // use the ABI names in register constraint lists.
11438   if (Subtarget.hasStdExtF()) {
11439     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11440                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11441                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11442                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11443                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11444                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11445                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11446                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11447                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11448                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11449                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11450                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11451                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11452                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11453                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11454                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11455                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11456                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11457                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11458                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11459                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11460                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11461                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11462                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11463                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11464                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11465                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11466                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11467                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11468                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11469                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11470                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11471                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11472                         .Default(RISCV::NoRegister);
11473     if (FReg != RISCV::NoRegister) {
11474       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11475       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11476         unsigned RegNo = FReg - RISCV::F0_F;
11477         unsigned DReg = RISCV::F0_D + RegNo;
11478         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11479       }
11480       if (VT == MVT::f32 || VT == MVT::Other)
11481         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11482       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11483         unsigned RegNo = FReg - RISCV::F0_F;
11484         unsigned HReg = RISCV::F0_H + RegNo;
11485         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11486       }
11487     }
11488   }
11489 
11490   if (Subtarget.hasVInstructions()) {
11491     Register VReg = StringSwitch<Register>(Constraint.lower())
11492                         .Case("{v0}", RISCV::V0)
11493                         .Case("{v1}", RISCV::V1)
11494                         .Case("{v2}", RISCV::V2)
11495                         .Case("{v3}", RISCV::V3)
11496                         .Case("{v4}", RISCV::V4)
11497                         .Case("{v5}", RISCV::V5)
11498                         .Case("{v6}", RISCV::V6)
11499                         .Case("{v7}", RISCV::V7)
11500                         .Case("{v8}", RISCV::V8)
11501                         .Case("{v9}", RISCV::V9)
11502                         .Case("{v10}", RISCV::V10)
11503                         .Case("{v11}", RISCV::V11)
11504                         .Case("{v12}", RISCV::V12)
11505                         .Case("{v13}", RISCV::V13)
11506                         .Case("{v14}", RISCV::V14)
11507                         .Case("{v15}", RISCV::V15)
11508                         .Case("{v16}", RISCV::V16)
11509                         .Case("{v17}", RISCV::V17)
11510                         .Case("{v18}", RISCV::V18)
11511                         .Case("{v19}", RISCV::V19)
11512                         .Case("{v20}", RISCV::V20)
11513                         .Case("{v21}", RISCV::V21)
11514                         .Case("{v22}", RISCV::V22)
11515                         .Case("{v23}", RISCV::V23)
11516                         .Case("{v24}", RISCV::V24)
11517                         .Case("{v25}", RISCV::V25)
11518                         .Case("{v26}", RISCV::V26)
11519                         .Case("{v27}", RISCV::V27)
11520                         .Case("{v28}", RISCV::V28)
11521                         .Case("{v29}", RISCV::V29)
11522                         .Case("{v30}", RISCV::V30)
11523                         .Case("{v31}", RISCV::V31)
11524                         .Default(RISCV::NoRegister);
11525     if (VReg != RISCV::NoRegister) {
11526       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11527         return std::make_pair(VReg, &RISCV::VMRegClass);
11528       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11529         return std::make_pair(VReg, &RISCV::VRRegClass);
11530       for (const auto *RC :
11531            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11532         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11533           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11534           return std::make_pair(VReg, RC);
11535         }
11536       }
11537     }
11538   }
11539 
11540   std::pair<Register, const TargetRegisterClass *> Res =
11541       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11542 
11543   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11544   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11545   // Subtarget into account.
11546   if (Res.second == &RISCV::GPRF16RegClass ||
11547       Res.second == &RISCV::GPRF32RegClass ||
11548       Res.second == &RISCV::GPRF64RegClass)
11549     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11550 
11551   return Res;
11552 }
11553 
11554 unsigned
11555 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11556   // Currently only support length 1 constraints.
11557   if (ConstraintCode.size() == 1) {
11558     switch (ConstraintCode[0]) {
11559     case 'A':
11560       return InlineAsm::Constraint_A;
11561     default:
11562       break;
11563     }
11564   }
11565 
11566   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11567 }
11568 
11569 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11570     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11571     SelectionDAG &DAG) const {
11572   // Currently only support length 1 constraints.
11573   if (Constraint.length() == 1) {
11574     switch (Constraint[0]) {
11575     case 'I':
11576       // Validate & create a 12-bit signed immediate operand.
11577       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11578         uint64_t CVal = C->getSExtValue();
11579         if (isInt<12>(CVal))
11580           Ops.push_back(
11581               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11582       }
11583       return;
11584     case 'J':
11585       // Validate & create an integer zero operand.
11586       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11587         if (C->getZExtValue() == 0)
11588           Ops.push_back(
11589               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11590       return;
11591     case 'K':
11592       // Validate & create a 5-bit unsigned immediate operand.
11593       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11594         uint64_t CVal = C->getZExtValue();
11595         if (isUInt<5>(CVal))
11596           Ops.push_back(
11597               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11598       }
11599       return;
11600     case 'S':
11601       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11602         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11603                                                  GA->getValueType(0)));
11604       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11605         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11606                                                 BA->getValueType(0)));
11607       }
11608       return;
11609     default:
11610       break;
11611     }
11612   }
11613   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11614 }
11615 
11616 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11617                                                    Instruction *Inst,
11618                                                    AtomicOrdering Ord) const {
11619   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11620     return Builder.CreateFence(Ord);
11621   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11622     return Builder.CreateFence(AtomicOrdering::Release);
11623   return nullptr;
11624 }
11625 
11626 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11627                                                     Instruction *Inst,
11628                                                     AtomicOrdering Ord) const {
11629   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11630     return Builder.CreateFence(AtomicOrdering::Acquire);
11631   return nullptr;
11632 }
11633 
11634 TargetLowering::AtomicExpansionKind
11635 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11636   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11637   // point operations can't be used in an lr/sc sequence without breaking the
11638   // forward-progress guarantee.
11639   if (AI->isFloatingPointOperation())
11640     return AtomicExpansionKind::CmpXChg;
11641 
11642   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11643   if (Size == 8 || Size == 16)
11644     return AtomicExpansionKind::MaskedIntrinsic;
11645   return AtomicExpansionKind::None;
11646 }
11647 
11648 static Intrinsic::ID
11649 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11650   if (XLen == 32) {
11651     switch (BinOp) {
11652     default:
11653       llvm_unreachable("Unexpected AtomicRMW BinOp");
11654     case AtomicRMWInst::Xchg:
11655       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11656     case AtomicRMWInst::Add:
11657       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11658     case AtomicRMWInst::Sub:
11659       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11660     case AtomicRMWInst::Nand:
11661       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11662     case AtomicRMWInst::Max:
11663       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11664     case AtomicRMWInst::Min:
11665       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11666     case AtomicRMWInst::UMax:
11667       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11668     case AtomicRMWInst::UMin:
11669       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11670     }
11671   }
11672 
11673   if (XLen == 64) {
11674     switch (BinOp) {
11675     default:
11676       llvm_unreachable("Unexpected AtomicRMW BinOp");
11677     case AtomicRMWInst::Xchg:
11678       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11679     case AtomicRMWInst::Add:
11680       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11681     case AtomicRMWInst::Sub:
11682       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11683     case AtomicRMWInst::Nand:
11684       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11685     case AtomicRMWInst::Max:
11686       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11687     case AtomicRMWInst::Min:
11688       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11689     case AtomicRMWInst::UMax:
11690       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11691     case AtomicRMWInst::UMin:
11692       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11693     }
11694   }
11695 
11696   llvm_unreachable("Unexpected XLen\n");
11697 }
11698 
11699 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11700     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11701     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11702   unsigned XLen = Subtarget.getXLen();
11703   Value *Ordering =
11704       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11705   Type *Tys[] = {AlignedAddr->getType()};
11706   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11707       AI->getModule(),
11708       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11709 
11710   if (XLen == 64) {
11711     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11712     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11713     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11714   }
11715 
11716   Value *Result;
11717 
11718   // Must pass the shift amount needed to sign extend the loaded value prior
11719   // to performing a signed comparison for min/max. ShiftAmt is the number of
11720   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11721   // is the number of bits to left+right shift the value in order to
11722   // sign-extend.
11723   if (AI->getOperation() == AtomicRMWInst::Min ||
11724       AI->getOperation() == AtomicRMWInst::Max) {
11725     const DataLayout &DL = AI->getModule()->getDataLayout();
11726     unsigned ValWidth =
11727         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11728     Value *SextShamt =
11729         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11730     Result = Builder.CreateCall(LrwOpScwLoop,
11731                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11732   } else {
11733     Result =
11734         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11735   }
11736 
11737   if (XLen == 64)
11738     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11739   return Result;
11740 }
11741 
11742 TargetLowering::AtomicExpansionKind
11743 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11744     AtomicCmpXchgInst *CI) const {
11745   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11746   if (Size == 8 || Size == 16)
11747     return AtomicExpansionKind::MaskedIntrinsic;
11748   return AtomicExpansionKind::None;
11749 }
11750 
11751 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11752     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11753     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11754   unsigned XLen = Subtarget.getXLen();
11755   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11756   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11757   if (XLen == 64) {
11758     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11759     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11760     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11761     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11762   }
11763   Type *Tys[] = {AlignedAddr->getType()};
11764   Function *MaskedCmpXchg =
11765       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11766   Value *Result = Builder.CreateCall(
11767       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11768   if (XLen == 64)
11769     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11770   return Result;
11771 }
11772 
11773 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
11774                                                         EVT DataVT) const {
11775   return false;
11776 }
11777 
11778 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11779                                                EVT VT) const {
11780   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11781     return false;
11782 
11783   switch (FPVT.getSimpleVT().SimpleTy) {
11784   case MVT::f16:
11785     return Subtarget.hasStdExtZfh();
11786   case MVT::f32:
11787     return Subtarget.hasStdExtF();
11788   case MVT::f64:
11789     return Subtarget.hasStdExtD();
11790   default:
11791     return false;
11792   }
11793 }
11794 
11795 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11796   // If we are using the small code model, we can reduce size of jump table
11797   // entry to 4 bytes.
11798   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11799       getTargetMachine().getCodeModel() == CodeModel::Small) {
11800     return MachineJumpTableInfo::EK_Custom32;
11801   }
11802   return TargetLowering::getJumpTableEncoding();
11803 }
11804 
11805 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11806     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11807     unsigned uid, MCContext &Ctx) const {
11808   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11809          getTargetMachine().getCodeModel() == CodeModel::Small);
11810   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11811 }
11812 
11813 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11814                                                      EVT VT) const {
11815   VT = VT.getScalarType();
11816 
11817   if (!VT.isSimple())
11818     return false;
11819 
11820   switch (VT.getSimpleVT().SimpleTy) {
11821   case MVT::f16:
11822     return Subtarget.hasStdExtZfh();
11823   case MVT::f32:
11824     return Subtarget.hasStdExtF();
11825   case MVT::f64:
11826     return Subtarget.hasStdExtD();
11827   default:
11828     break;
11829   }
11830 
11831   return false;
11832 }
11833 
11834 Register RISCVTargetLowering::getExceptionPointerRegister(
11835     const Constant *PersonalityFn) const {
11836   return RISCV::X10;
11837 }
11838 
11839 Register RISCVTargetLowering::getExceptionSelectorRegister(
11840     const Constant *PersonalityFn) const {
11841   return RISCV::X11;
11842 }
11843 
11844 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11845   // Return false to suppress the unnecessary extensions if the LibCall
11846   // arguments or return value is f32 type for LP64 ABI.
11847   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11848   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11849     return false;
11850 
11851   return true;
11852 }
11853 
11854 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11855   if (Subtarget.is64Bit() && Type == MVT::i32)
11856     return true;
11857 
11858   return IsSigned;
11859 }
11860 
11861 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11862                                                  SDValue C) const {
11863   // Check integral scalar types.
11864   if (VT.isScalarInteger()) {
11865     // Omit the optimization if the sub target has the M extension and the data
11866     // size exceeds XLen.
11867     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11868       return false;
11869     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11870       // Break the MUL to a SLLI and an ADD/SUB.
11871       const APInt &Imm = ConstNode->getAPIntValue();
11872       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11873           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11874         return true;
11875       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11876       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11877           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11878            (Imm - 8).isPowerOf2()))
11879         return true;
11880       // Omit the following optimization if the sub target has the M extension
11881       // and the data size >= XLen.
11882       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11883         return false;
11884       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11885       // a pair of LUI/ADDI.
11886       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11887         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11888         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11889             (1 - ImmS).isPowerOf2())
11890         return true;
11891       }
11892     }
11893   }
11894 
11895   return false;
11896 }
11897 
11898 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11899                                                       SDValue ConstNode) const {
11900   // Let the DAGCombiner decide for vectors.
11901   EVT VT = AddNode.getValueType();
11902   if (VT.isVector())
11903     return true;
11904 
11905   // Let the DAGCombiner decide for larger types.
11906   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11907     return true;
11908 
11909   // It is worse if c1 is simm12 while c1*c2 is not.
11910   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11911   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11912   const APInt &C1 = C1Node->getAPIntValue();
11913   const APInt &C2 = C2Node->getAPIntValue();
11914   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11915     return false;
11916 
11917   // Default to true and let the DAGCombiner decide.
11918   return true;
11919 }
11920 
11921 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11922     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11923     bool *Fast) const {
11924   if (!VT.isVector()) {
11925     if (Fast)
11926       *Fast = false;
11927     return Subtarget.enableUnalignedScalarMem();
11928   }
11929 
11930   // All vector implementations must support element alignment
11931   EVT ElemVT = VT.getVectorElementType();
11932   if (Alignment >= ElemVT.getStoreSize()) {
11933     if (Fast)
11934       *Fast = true;
11935     return true;
11936   }
11937 
11938   return false;
11939 }
11940 
11941 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11942     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11943     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11944   bool IsABIRegCopy = CC.has_value();
11945   EVT ValueVT = Val.getValueType();
11946   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11947     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11948     // and cast to f32.
11949     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11950     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11951     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11952                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11953     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11954     Parts[0] = Val;
11955     return true;
11956   }
11957 
11958   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11959     LLVMContext &Context = *DAG.getContext();
11960     EVT ValueEltVT = ValueVT.getVectorElementType();
11961     EVT PartEltVT = PartVT.getVectorElementType();
11962     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11963     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11964     if (PartVTBitSize % ValueVTBitSize == 0) {
11965       assert(PartVTBitSize >= ValueVTBitSize);
11966       // If the element types are different, bitcast to the same element type of
11967       // PartVT first.
11968       // Give an example here, we want copy a <vscale x 1 x i8> value to
11969       // <vscale x 4 x i16>.
11970       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11971       // subvector, then we can bitcast to <vscale x 4 x i16>.
11972       if (ValueEltVT != PartEltVT) {
11973         if (PartVTBitSize > ValueVTBitSize) {
11974           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11975           assert(Count != 0 && "The number of element should not be zero.");
11976           EVT SameEltTypeVT =
11977               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11978           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11979                             DAG.getUNDEF(SameEltTypeVT), Val,
11980                             DAG.getVectorIdxConstant(0, DL));
11981         }
11982         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11983       } else {
11984         Val =
11985             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11986                         Val, DAG.getVectorIdxConstant(0, DL));
11987       }
11988       Parts[0] = Val;
11989       return true;
11990     }
11991   }
11992   return false;
11993 }
11994 
11995 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11996     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11997     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11998   bool IsABIRegCopy = CC.has_value();
11999   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12000     SDValue Val = Parts[0];
12001 
12002     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12003     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12004     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12005     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12006     return Val;
12007   }
12008 
12009   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12010     LLVMContext &Context = *DAG.getContext();
12011     SDValue Val = Parts[0];
12012     EVT ValueEltVT = ValueVT.getVectorElementType();
12013     EVT PartEltVT = PartVT.getVectorElementType();
12014     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12015     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12016     if (PartVTBitSize % ValueVTBitSize == 0) {
12017       assert(PartVTBitSize >= ValueVTBitSize);
12018       EVT SameEltTypeVT = ValueVT;
12019       // If the element types are different, convert it to the same element type
12020       // of PartVT.
12021       // Give an example here, we want copy a <vscale x 1 x i8> value from
12022       // <vscale x 4 x i16>.
12023       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12024       // then we can extract <vscale x 1 x i8>.
12025       if (ValueEltVT != PartEltVT) {
12026         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12027         assert(Count != 0 && "The number of element should not be zero.");
12028         SameEltTypeVT =
12029             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12030         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12031       }
12032       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12033                         DAG.getVectorIdxConstant(0, DL));
12034       return Val;
12035     }
12036   }
12037   return SDValue();
12038 }
12039 
12040 SDValue
12041 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12042                                    SelectionDAG &DAG,
12043                                    SmallVectorImpl<SDNode *> &Created) const {
12044   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12045   if (isIntDivCheap(N->getValueType(0), Attr))
12046     return SDValue(N, 0); // Lower SDIV as SDIV
12047 
12048   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12049          "Unexpected divisor!");
12050 
12051   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12052   if (!Subtarget.hasStdExtZbt())
12053     return SDValue();
12054 
12055   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12056   // Besides, more critical path instructions will be generated when dividing
12057   // by 2. So we keep using the original DAGs for these cases.
12058   unsigned Lg2 = Divisor.countTrailingZeros();
12059   if (Lg2 == 1 || Lg2 >= 12)
12060     return SDValue();
12061 
12062   // fold (sdiv X, pow2)
12063   EVT VT = N->getValueType(0);
12064   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12065     return SDValue();
12066 
12067   SDLoc DL(N);
12068   SDValue N0 = N->getOperand(0);
12069   SDValue Zero = DAG.getConstant(0, DL, VT);
12070   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12071 
12072   // Add (N0 < 0) ? Pow2 - 1 : 0;
12073   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12074   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12075   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12076 
12077   Created.push_back(Cmp.getNode());
12078   Created.push_back(Add.getNode());
12079   Created.push_back(Sel.getNode());
12080 
12081   // Divide by pow2.
12082   SDValue SRA =
12083       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12084 
12085   // If we're dividing by a positive value, we're done.  Otherwise, we must
12086   // negate the result.
12087   if (Divisor.isNonNegative())
12088     return SRA;
12089 
12090   Created.push_back(SRA.getNode());
12091   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12092 }
12093 
12094 #define GET_REGISTER_MATCHER
12095 #include "RISCVGenAsmMatcher.inc"
12096 
12097 Register
12098 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12099                                        const MachineFunction &MF) const {
12100   Register Reg = MatchRegisterAltName(RegName);
12101   if (Reg == RISCV::NoRegister)
12102     Reg = MatchRegisterName(RegName);
12103   if (Reg == RISCV::NoRegister)
12104     report_fatal_error(
12105         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12106   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12107   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12108     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12109                              StringRef(RegName) + "\"."));
12110   return Reg;
12111 }
12112 
12113 namespace llvm {
12114 namespace RISCVVIntrinsicsTable {
12115 
12116 #define GET_RISCVVIntrinsicsTable_IMPL
12117 #include "RISCVGenSearchableTables.inc"
12118 
12119 } // namespace RISCVVIntrinsicsTable
12120 
12121 } // namespace llvm
12122