1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       // Disable the smallest fractional LMUL types if ELEN is less than
116       // RVVBitsPerBlock.
117       unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN();
118       if (VT.getVectorMinNumElements() < MinElts)
119         return;
120 
121       unsigned Size = VT.getSizeInBits().getKnownMinValue();
122       const TargetRegisterClass *RC;
123       if (Size <= RISCV::RVVBitsPerBlock)
124         RC = &RISCV::VRRegClass;
125       else if (Size == 2 * RISCV::RVVBitsPerBlock)
126         RC = &RISCV::VRM2RegClass;
127       else if (Size == 4 * RISCV::RVVBitsPerBlock)
128         RC = &RISCV::VRM4RegClass;
129       else if (Size == 8 * RISCV::RVVBitsPerBlock)
130         RC = &RISCV::VRM8RegClass;
131       else
132         llvm_unreachable("Unexpected size");
133 
134       addRegisterClass(VT, RC);
135     };
136 
137     for (MVT VT : BoolVecVTs)
138       addRegClassForRVV(VT);
139     for (MVT VT : IntVecVTs) {
140       if (VT.getVectorElementType() == MVT::i64 &&
141           !Subtarget.hasVInstructionsI64())
142         continue;
143       addRegClassForRVV(VT);
144     }
145 
146     if (Subtarget.hasVInstructionsF16())
147       for (MVT VT : F16VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.hasVInstructionsF32())
151       for (MVT VT : F32VecVTs)
152         addRegClassForRVV(VT);
153 
154     if (Subtarget.hasVInstructionsF64())
155       for (MVT VT : F64VecVTs)
156         addRegClassForRVV(VT);
157 
158     if (Subtarget.useRVVForFixedLengthVectors()) {
159       auto addRegClassForFixedVectors = [this](MVT VT) {
160         MVT ContainerVT = getContainerForFixedLengthVector(VT);
161         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
162         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
163         addRegisterClass(VT, TRI.getRegClass(RCID));
164       };
165       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
166         if (useRVVForFixedLengthVectorVT(VT))
167           addRegClassForFixedVectors(VT);
168 
169       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
170         if (useRVVForFixedLengthVectorVT(VT))
171           addRegClassForFixedVectors(VT);
172     }
173   }
174 
175   // Compute derived properties from the register classes.
176   computeRegisterProperties(STI.getRegisterInfo());
177 
178   setStackPointerRegisterToSaveRestore(RISCV::X2);
179 
180   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
181                    MVT::i1, Promote);
182 
183   // TODO: add all necessary setOperationAction calls.
184   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
185 
186   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187   setOperationAction(ISD::BR_CC, XLenVT, Expand);
188   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
189   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
190 
191   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
192 
193   setOperationAction(ISD::VASTART, MVT::Other, Custom);
194   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
195 
196   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
197 
198   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
199 
200   if (!Subtarget.hasStdExtZbb())
201     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
202 
203   if (Subtarget.is64Bit()) {
204     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
205 
206     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
207                        MVT::i32, Custom);
208 
209     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
210                        MVT::i32, Custom);
211   } else {
212     setLibcallName(
213         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
214         nullptr);
215     setLibcallName(RTLIB::MULO_I64, nullptr);
216   }
217 
218   if (!Subtarget.hasStdExtM()) {
219     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
220                         ISD::SREM, ISD::UREM},
221                        XLenVT, Expand);
222   } else {
223     if (Subtarget.is64Bit()) {
224       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
225 
226       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
227                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
228     } else {
229       setOperationAction(ISD::MUL, MVT::i64, Custom);
230     }
231   }
232 
233   setOperationAction(
234       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
235       Expand);
236 
237   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
238                      Custom);
239 
240   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
241       Subtarget.hasStdExtZbkb()) {
242     if (Subtarget.is64Bit())
243       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
244   } else {
245     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
246   }
247 
248   if (Subtarget.hasStdExtZbp()) {
249     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
250     // more combining.
251     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
252 
253     // BSWAP i8 doesn't exist.
254     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
255 
256     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
257 
258     if (Subtarget.is64Bit())
259       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
260   } else {
261     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
262     // pattern match it directly in isel.
263     setOperationAction(ISD::BSWAP, XLenVT,
264                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
265                            ? Legal
266                            : Expand);
267     // Zbkb can use rev8+brev8 to implement bitreverse.
268     setOperationAction(ISD::BITREVERSE, XLenVT,
269                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
270   }
271 
272   if (Subtarget.hasStdExtZbb()) {
273     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
274                        Legal);
275 
276     if (Subtarget.is64Bit())
277       setOperationAction(
278           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
279           MVT::i32, Custom);
280   } else {
281     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
282 
283     if (Subtarget.is64Bit())
284       setOperationAction(ISD::ABS, MVT::i32, Custom);
285   }
286 
287   if (Subtarget.hasStdExtZbt()) {
288     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
289     setOperationAction(ISD::SELECT, XLenVT, Legal);
290 
291     if (Subtarget.is64Bit())
292       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
293   } else {
294     setOperationAction(ISD::SELECT, XLenVT, Custom);
295   }
296 
297   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
298       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
299       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
300       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
301       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
302       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
303       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
304 
305   static const ISD::CondCode FPCCToExpand[] = {
306       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
307       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
308       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
309 
310   static const ISD::NodeType FPOpToExpand[] = {
311       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
312       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
313 
314   if (Subtarget.hasStdExtZfh())
315     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
316 
317   if (Subtarget.hasStdExtZfh()) {
318     for (auto NT : FPLegalNodeTypes)
319       setOperationAction(NT, MVT::f16, Legal);
320     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
321     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
322     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
323     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
324     setOperationAction(ISD::SELECT, MVT::f16, Custom);
325     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
326 
327     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
328                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
329                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
330                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
331                         ISD::FLOG2, ISD::FLOG10},
332                        MVT::f16, Promote);
333 
334     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
335     // complete support for all operations in LegalizeDAG.
336 
337     // We need to custom promote this.
338     if (Subtarget.is64Bit())
339       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
340   }
341 
342   if (Subtarget.hasStdExtF()) {
343     for (auto NT : FPLegalNodeTypes)
344       setOperationAction(NT, MVT::f32, Legal);
345     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
346     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
347     setOperationAction(ISD::SELECT, MVT::f32, Custom);
348     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
349     for (auto Op : FPOpToExpand)
350       setOperationAction(Op, MVT::f32, Expand);
351     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
352     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
353   }
354 
355   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
356     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
357 
358   if (Subtarget.hasStdExtD()) {
359     for (auto NT : FPLegalNodeTypes)
360       setOperationAction(NT, MVT::f64, Legal);
361     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
362     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
363     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
364     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
365     setOperationAction(ISD::SELECT, MVT::f64, Custom);
366     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
367     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
368     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
369     for (auto Op : FPOpToExpand)
370       setOperationAction(Op, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373   }
374 
375   if (Subtarget.is64Bit())
376     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
377                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
378                        MVT::i32, Custom);
379 
380   if (Subtarget.hasStdExtF()) {
381     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
382                        Custom);
383 
384     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
385                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
386                        XLenVT, Legal);
387 
388     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
389     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
390   }
391 
392   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
393                       ISD::JumpTable},
394                      XLenVT, Custom);
395 
396   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
397 
398   if (Subtarget.is64Bit())
399     setOperationAction(ISD::Constant, MVT::i64, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408   if (Subtarget.is64Bit())
409     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
410 
411   if (Subtarget.hasStdExtA()) {
412     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
413     setMinCmpXchgSizeInBits(32);
414   } else {
415     setMaxAtomicSizeInBitsSupported(0);
416   }
417 
418   setBooleanContents(ZeroOrOneBooleanContent);
419 
420   if (Subtarget.hasVInstructions()) {
421     setBooleanVectorContents(ZeroOrOneBooleanContent);
422 
423     setOperationAction(ISD::VSCALE, XLenVT, Custom);
424 
425     // RVV intrinsics may have illegal operands.
426     // We also need to custom legalize vmv.x.s.
427     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
428                        {MVT::i8, MVT::i16}, Custom);
429     if (Subtarget.is64Bit())
430       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
431     else
432       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
433                          MVT::i64, Custom);
434 
435     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
436                        MVT::Other, Custom);
437 
438     static const unsigned IntegerVPOps[] = {
439         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
440         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
441         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
442         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
443         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
444         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
445         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
446         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
447         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
448         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
449 
450     static const unsigned FloatingPointVPOps[] = {
451         ISD::VP_FADD,        ISD::VP_FSUB,
452         ISD::VP_FMUL,        ISD::VP_FDIV,
453         ISD::VP_FNEG,        ISD::VP_FMA,
454         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
455         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
456         ISD::VP_MERGE,       ISD::VP_SELECT,
457         ISD::VP_SITOFP,      ISD::VP_UITOFP,
458         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
459         ISD::VP_FP_EXTEND};
460 
461     if (!Subtarget.is64Bit()) {
462       // We must custom-lower certain vXi64 operations on RV32 due to the vector
463       // element type being illegal.
464       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
465                          MVT::i64, Custom);
466 
467       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
468                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
469                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
470                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
471                          MVT::i64, Custom);
472 
473       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
474                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
475                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
476                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
477                          MVT::i64, Custom);
478     }
479 
480     for (MVT VT : BoolVecVTs) {
481       if (!isTypeLegal(VT))
482         continue;
483 
484       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
485 
486       // Mask VTs are custom-expanded into a series of standard nodes
487       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
488                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
489                          VT, Custom);
490 
491       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
492                          Custom);
493 
494       setOperationAction(ISD::SELECT, VT, Custom);
495       setOperationAction(
496           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
497           Expand);
498 
499       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
500 
501       setOperationAction(
502           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
503           Custom);
504 
505       setOperationAction(
506           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
507           Custom);
508 
509       // RVV has native int->float & float->int conversions where the
510       // element type sizes are within one power-of-two of each other. Any
511       // wider distances between type sizes have to be lowered as sequences
512       // which progressively narrow the gap in stages.
513       setOperationAction(
514           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
515           VT, Custom);
516 
517       // Expand all extending loads to types larger than this, and truncating
518       // stores from types larger than this.
519       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
520         setTruncStoreAction(OtherVT, VT, Expand);
521         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
522                          VT, Expand);
523       }
524 
525       setOperationAction(
526           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
527           Custom);
528       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
529 
530       setOperationPromotedToType(
531           ISD::VECTOR_SPLICE, VT,
532           MVT::getVectorVT(MVT::i8, VT.getVectorElementCount()));
533     }
534 
535     for (MVT VT : IntVecVTs) {
536       if (!isTypeLegal(VT))
537         continue;
538 
539       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
540       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
541 
542       // Vectors implement MULHS/MULHU.
543       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
544 
545       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
546       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
547         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
548 
549       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
550                          Legal);
551 
552       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
553 
554       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
555                          Expand);
556 
557       setOperationAction(ISD::BSWAP, VT, Expand);
558 
559       // Custom-lower extensions and truncations from/to mask types.
560       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
561                          VT, Custom);
562 
563       // RVV has native int->float & float->int conversions where the
564       // element type sizes are within one power-of-two of each other. Any
565       // wider distances between type sizes have to be lowered as sequences
566       // which progressively narrow the gap in stages.
567       setOperationAction(
568           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
569           VT, Custom);
570 
571       setOperationAction(
572           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
573 
574       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
575       // nodes which truncate by one power of two at a time.
576       setOperationAction(ISD::TRUNCATE, VT, Custom);
577 
578       // Custom-lower insert/extract operations to simplify patterns.
579       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
580                          Custom);
581 
582       // Custom-lower reduction operations to set up the corresponding custom
583       // nodes' operands.
584       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
585                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
586                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
587                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
588                          VT, Custom);
589 
590       setOperationAction(IntegerVPOps, VT, Custom);
591 
592       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
593 
594       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
595                          VT, Custom);
596 
597       setOperationAction(
598           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
599           Custom);
600 
601       setOperationAction(
602           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
603           VT, Custom);
604 
605       setOperationAction(ISD::SELECT, VT, Custom);
606       setOperationAction(ISD::SELECT_CC, VT, Expand);
607 
608       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
609 
610       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
611         setTruncStoreAction(VT, OtherVT, Expand);
612         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
613                          VT, Expand);
614       }
615 
616       // Splice
617       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
618 
619       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
620       // type that can represent the value exactly.
621       if (VT.getVectorElementType() != MVT::i64) {
622         MVT FloatEltVT =
623             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
624         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
625         if (isTypeLegal(FloatVT)) {
626           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
627                              Custom);
628         }
629       }
630     }
631 
632     // Expand various CCs to best match the RVV ISA, which natively supports UNE
633     // but no other unordered comparisons, and supports all ordered comparisons
634     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
635     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
636     // and we pattern-match those back to the "original", swapping operands once
637     // more. This way we catch both operations and both "vf" and "fv" forms with
638     // fewer patterns.
639     static const ISD::CondCode VFPCCToExpand[] = {
640         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
641         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
642         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
643     };
644 
645     // Sets common operation actions on RVV floating-point vector types.
646     const auto SetCommonVFPActions = [&](MVT VT) {
647       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
648       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
649       // sizes are within one power-of-two of each other. Therefore conversions
650       // between vXf16 and vXf64 must be lowered as sequences which convert via
651       // vXf32.
652       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
653       // Custom-lower insert/extract operations to simplify patterns.
654       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
655                          Custom);
656       // Expand various condition codes (explained above).
657       setCondCodeAction(VFPCCToExpand, VT, Expand);
658 
659       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
660 
661       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
662                          VT, Custom);
663 
664       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
665                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
666                          VT, Custom);
667 
668       // Expand FP operations that need libcalls.
669       setOperationAction(ISD::FREM, VT, Expand);
670       setOperationAction(ISD::FPOW, VT, Expand);
671       setOperationAction(ISD::FCOS, VT, Expand);
672       setOperationAction(ISD::FSIN, VT, Expand);
673       setOperationAction(ISD::FSINCOS, VT, Expand);
674       setOperationAction(ISD::FEXP, VT, Expand);
675       setOperationAction(ISD::FEXP2, VT, Expand);
676       setOperationAction(ISD::FLOG, VT, Expand);
677       setOperationAction(ISD::FLOG2, VT, Expand);
678       setOperationAction(ISD::FLOG10, VT, Expand);
679       setOperationAction(ISD::FRINT, VT, Expand);
680       setOperationAction(ISD::FNEARBYINT, VT, Expand);
681 
682       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
683       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
684       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
685       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
686 
687       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
688 
689       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
690 
691       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
692                          VT, Custom);
693 
694       setOperationAction(
695           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
696           Custom);
697 
698       setOperationAction(ISD::SELECT, VT, Custom);
699       setOperationAction(ISD::SELECT_CC, VT, Expand);
700 
701       setOperationAction(
702           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
703           VT, Custom);
704 
705       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
706 
707       setOperationAction(FloatingPointVPOps, VT, Custom);
708     };
709 
710     // Sets common extload/truncstore actions on RVV floating-point vector
711     // types.
712     const auto SetCommonVFPExtLoadTruncStoreActions =
713         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
714           for (auto SmallVT : SmallerVTs) {
715             setTruncStoreAction(VT, SmallVT, Expand);
716             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
717           }
718         };
719 
720     if (Subtarget.hasVInstructionsF16()) {
721       for (MVT VT : F16VecVTs) {
722         if (!isTypeLegal(VT))
723           continue;
724         SetCommonVFPActions(VT);
725       }
726     }
727 
728     if (Subtarget.hasVInstructionsF32()) {
729       for (MVT VT : F32VecVTs) {
730         if (!isTypeLegal(VT))
731           continue;
732         SetCommonVFPActions(VT);
733         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
734       }
735     }
736 
737     if (Subtarget.hasVInstructionsF64()) {
738       for (MVT VT : F64VecVTs) {
739         if (!isTypeLegal(VT))
740           continue;
741         SetCommonVFPActions(VT);
742         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
743         SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
744       }
745     }
746 
747     if (Subtarget.useRVVForFixedLengthVectors()) {
748       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
749         if (!useRVVForFixedLengthVectorVT(VT))
750           continue;
751 
752         // By default everything must be expanded.
753         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
754           setOperationAction(Op, VT, Expand);
755         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
756           setTruncStoreAction(VT, OtherVT, Expand);
757           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
758                            OtherVT, VT, Expand);
759         }
760 
761         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
762         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
763                            Custom);
764 
765         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
766                            Custom);
767 
768         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
769                            VT, Custom);
770 
771         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
772 
773         setOperationAction(ISD::SETCC, VT, Custom);
774 
775         setOperationAction(ISD::SELECT, VT, Custom);
776 
777         setOperationAction(ISD::TRUNCATE, VT, Custom);
778 
779         setOperationAction(ISD::BITCAST, VT, Custom);
780 
781         setOperationAction(
782             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
783             Custom);
784 
785         setOperationAction(
786             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
787             Custom);
788 
789         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
790                             ISD::FP_TO_UINT},
791                            VT, Custom);
792 
793         // Operations below are different for between masks and other vectors.
794         if (VT.getVectorElementType() == MVT::i1) {
795           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
796                               ISD::OR, ISD::XOR},
797                              VT, Custom);
798 
799           setOperationAction(
800               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
801               VT, Custom);
802           continue;
803         }
804 
805         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
806         // it before type legalization for i64 vectors on RV32. It will then be
807         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
808         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
809         // improvements first.
810         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
811           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
812           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
813         }
814 
815         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
816         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
817 
818         setOperationAction(
819             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
820 
821         setOperationAction(
822             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
823             Custom);
824 
825         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
826                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
827                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
828                            VT, Custom);
829 
830         setOperationAction(
831             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
832 
833         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
834         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
835           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
836 
837         setOperationAction(
838             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
839             Custom);
840 
841         setOperationAction(ISD::VSELECT, VT, Custom);
842         setOperationAction(ISD::SELECT_CC, VT, Expand);
843 
844         setOperationAction(
845             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
846 
847         // Custom-lower reduction operations to set up the corresponding custom
848         // nodes' operands.
849         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
850                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
851                             ISD::VECREDUCE_UMIN},
852                            VT, Custom);
853 
854         setOperationAction(IntegerVPOps, VT, Custom);
855 
856         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
857         // type that can represent the value exactly.
858         if (VT.getVectorElementType() != MVT::i64) {
859           MVT FloatEltVT =
860               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
861           EVT FloatVT =
862               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
863           if (isTypeLegal(FloatVT))
864             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
865                                Custom);
866         }
867       }
868 
869       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
870         if (!useRVVForFixedLengthVectorVT(VT))
871           continue;
872 
873         // By default everything must be expanded.
874         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
875           setOperationAction(Op, VT, Expand);
876         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
877           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
878           setTruncStoreAction(VT, OtherVT, Expand);
879         }
880 
881         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
882         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
883                            Custom);
884 
885         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
886                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
887                             ISD::EXTRACT_VECTOR_ELT},
888                            VT, Custom);
889 
890         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
891                             ISD::MGATHER, ISD::MSCATTER},
892                            VT, Custom);
893 
894         setOperationAction(
895             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
896             Custom);
897 
898         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
899                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
900                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
901                            VT, Custom);
902 
903         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
904 
905         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
906                            VT, Custom);
907 
908         for (auto CC : VFPCCToExpand)
909           setCondCodeAction(CC, VT, Expand);
910 
911         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
912         setOperationAction(ISD::SELECT_CC, VT, Expand);
913 
914         setOperationAction(ISD::BITCAST, VT, Custom);
915 
916         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
917                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
918                            VT, Custom);
919 
920         setOperationAction(FloatingPointVPOps, VT, Custom);
921       }
922 
923       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
924       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
925                          Custom);
926       if (Subtarget.hasStdExtZfh())
927         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
928       if (Subtarget.hasStdExtF())
929         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
930       if (Subtarget.hasStdExtD())
931         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
932     }
933   }
934 
935   // Function alignments.
936   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
937   setMinFunctionAlignment(FunctionAlignment);
938   setPrefFunctionAlignment(FunctionAlignment);
939 
940   setMinimumJumpTableEntries(5);
941 
942   // Jumps are expensive, compared to logic
943   setJumpIsExpensive();
944 
945   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
946                        ISD::OR, ISD::XOR});
947   if (Subtarget.is64Bit())
948     setTargetDAGCombine(ISD::SRA);
949 
950   if (Subtarget.hasStdExtF())
951     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
952 
953   if (Subtarget.hasStdExtZbp())
954     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
955 
956   if (Subtarget.hasStdExtZbb())
957     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
958 
959   if (Subtarget.hasStdExtZbkb())
960     setTargetDAGCombine(ISD::BITREVERSE);
961   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
962     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
963   if (Subtarget.hasStdExtF())
964     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
965                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
966   if (Subtarget.hasVInstructions())
967     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
968                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
969                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
970   if (Subtarget.useRVVForFixedLengthVectors())
971     setTargetDAGCombine(ISD::BITCAST);
972 
973   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
974   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
975 }
976 
977 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
978                                             LLVMContext &Context,
979                                             EVT VT) const {
980   if (!VT.isVector())
981     return getPointerTy(DL);
982   if (Subtarget.hasVInstructions() &&
983       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
984     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
985   return VT.changeVectorElementTypeToInteger();
986 }
987 
988 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
989   return Subtarget.getXLenVT();
990 }
991 
992 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
993                                              const CallInst &I,
994                                              MachineFunction &MF,
995                                              unsigned Intrinsic) const {
996   auto &DL = I.getModule()->getDataLayout();
997   switch (Intrinsic) {
998   default:
999     return false;
1000   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1001   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1002   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1003   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1004   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1005   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1006   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1007   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1008   case Intrinsic::riscv_masked_cmpxchg_i32:
1009     Info.opc = ISD::INTRINSIC_W_CHAIN;
1010     Info.memVT = MVT::i32;
1011     Info.ptrVal = I.getArgOperand(0);
1012     Info.offset = 0;
1013     Info.align = Align(4);
1014     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1015                  MachineMemOperand::MOVolatile;
1016     return true;
1017   case Intrinsic::riscv_masked_strided_load:
1018     Info.opc = ISD::INTRINSIC_W_CHAIN;
1019     Info.ptrVal = I.getArgOperand(1);
1020     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1021     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1022     Info.size = MemoryLocation::UnknownSize;
1023     Info.flags |= MachineMemOperand::MOLoad;
1024     return true;
1025   case Intrinsic::riscv_masked_strided_store:
1026     Info.opc = ISD::INTRINSIC_VOID;
1027     Info.ptrVal = I.getArgOperand(1);
1028     Info.memVT =
1029         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1030     Info.align = Align(
1031         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1032         8);
1033     Info.size = MemoryLocation::UnknownSize;
1034     Info.flags |= MachineMemOperand::MOStore;
1035     return true;
1036   case Intrinsic::riscv_seg2_load:
1037   case Intrinsic::riscv_seg3_load:
1038   case Intrinsic::riscv_seg4_load:
1039   case Intrinsic::riscv_seg5_load:
1040   case Intrinsic::riscv_seg6_load:
1041   case Intrinsic::riscv_seg7_load:
1042   case Intrinsic::riscv_seg8_load:
1043     Info.opc = ISD::INTRINSIC_W_CHAIN;
1044     Info.ptrVal = I.getArgOperand(0);
1045     Info.memVT =
1046         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1047     Info.align =
1048         Align(DL.getTypeSizeInBits(
1049                   I.getType()->getStructElementType(0)->getScalarType()) /
1050               8);
1051     Info.size = MemoryLocation::UnknownSize;
1052     Info.flags |= MachineMemOperand::MOLoad;
1053     return true;
1054   }
1055 }
1056 
1057 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1058                                                 const AddrMode &AM, Type *Ty,
1059                                                 unsigned AS,
1060                                                 Instruction *I) const {
1061   // No global is ever allowed as a base.
1062   if (AM.BaseGV)
1063     return false;
1064 
1065   // RVV instructions only support register addressing.
1066   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1067     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1068 
1069   // Require a 12-bit signed offset.
1070   if (!isInt<12>(AM.BaseOffs))
1071     return false;
1072 
1073   switch (AM.Scale) {
1074   case 0: // "r+i" or just "i", depending on HasBaseReg.
1075     break;
1076   case 1:
1077     if (!AM.HasBaseReg) // allow "r+i".
1078       break;
1079     return false; // disallow "r+r" or "r+r+i".
1080   default:
1081     return false;
1082   }
1083 
1084   return true;
1085 }
1086 
1087 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1088   return isInt<12>(Imm);
1089 }
1090 
1091 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1092   return isInt<12>(Imm);
1093 }
1094 
1095 // On RV32, 64-bit integers are split into their high and low parts and held
1096 // in two different registers, so the trunc is free since the low register can
1097 // just be used.
1098 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1099   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1100     return false;
1101   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1102   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1103   return (SrcBits == 64 && DestBits == 32);
1104 }
1105 
1106 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1107   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1108       !SrcVT.isInteger() || !DstVT.isInteger())
1109     return false;
1110   unsigned SrcBits = SrcVT.getSizeInBits();
1111   unsigned DestBits = DstVT.getSizeInBits();
1112   return (SrcBits == 64 && DestBits == 32);
1113 }
1114 
1115 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1116   // Zexts are free if they can be combined with a load.
1117   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1118   // poorly with type legalization of compares preferring sext.
1119   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1120     EVT MemVT = LD->getMemoryVT();
1121     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1122         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1123          LD->getExtensionType() == ISD::ZEXTLOAD))
1124       return true;
1125   }
1126 
1127   return TargetLowering::isZExtFree(Val, VT2);
1128 }
1129 
1130 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1131   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1132 }
1133 
1134 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1135   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1136 }
1137 
1138 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1139   return Subtarget.hasStdExtZbb();
1140 }
1141 
1142 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1143   return Subtarget.hasStdExtZbb();
1144 }
1145 
1146 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1147   EVT VT = Y.getValueType();
1148 
1149   // FIXME: Support vectors once we have tests.
1150   if (VT.isVector())
1151     return false;
1152 
1153   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1154           Subtarget.hasStdExtZbkb()) &&
1155          !isa<ConstantSDNode>(Y);
1156 }
1157 
1158 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1159   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1160   auto *C = dyn_cast<ConstantSDNode>(Y);
1161   return C && C->getAPIntValue().ule(10);
1162 }
1163 
1164 bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1165                                                             Type *Ty) const {
1166   assert(Ty->isIntegerTy());
1167 
1168   unsigned BitSize = Ty->getIntegerBitWidth();
1169   if (BitSize > Subtarget.getXLen())
1170     return false;
1171 
1172   // Fast path, assume 32-bit immediates are cheap.
1173   int64_t Val = Imm.getSExtValue();
1174   if (isInt<32>(Val))
1175     return true;
1176 
1177   // A constant pool entry may be more aligned thant he load we're trying to
1178   // replace. If we don't support unaligned scalar mem, prefer the constant
1179   // pool.
1180   // TODO: Can the caller pass down the alignment?
1181   if (!Subtarget.enableUnalignedScalarMem())
1182     return true;
1183 
1184   // Prefer to keep the load if it would require many instructions.
1185   // This uses the same threshold we use for constant pools but doesn't
1186   // check useConstantPoolForLargeInts.
1187   // TODO: Should we keep the load only when we're definitely going to emit a
1188   // constant pool?
1189 
1190   RISCVMatInt::InstSeq Seq =
1191       RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits());
1192   return Seq.size() <= Subtarget.getMaxBuildIntsCost();
1193 }
1194 
1195 bool RISCVTargetLowering::
1196     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1197         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1198         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1199         SelectionDAG &DAG) const {
1200   // One interesting pattern that we'd want to form is 'bit extract':
1201   //   ((1 >> Y) & 1) ==/!= 0
1202   // But we also need to be careful not to try to reverse that fold.
1203 
1204   // Is this '((1 >> Y) & 1)'?
1205   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1206     return false; // Keep the 'bit extract' pattern.
1207 
1208   // Will this be '((1 >> Y) & 1)' after the transform?
1209   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1210     return true; // Do form the 'bit extract' pattern.
1211 
1212   // If 'X' is a constant, and we transform, then we will immediately
1213   // try to undo the fold, thus causing endless combine loop.
1214   // So only do the transform if X is not a constant. This matches the default
1215   // implementation of this function.
1216   return !XC;
1217 }
1218 
1219 /// Check if sinking \p I's operands to I's basic block is profitable, because
1220 /// the operands can be folded into a target instruction, e.g.
1221 /// splats of scalars can fold into vector instructions.
1222 bool RISCVTargetLowering::shouldSinkOperands(
1223     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1224   using namespace llvm::PatternMatch;
1225 
1226   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1227     return false;
1228 
1229   auto IsSinker = [&](Instruction *I, int Operand) {
1230     switch (I->getOpcode()) {
1231     case Instruction::Add:
1232     case Instruction::Sub:
1233     case Instruction::Mul:
1234     case Instruction::And:
1235     case Instruction::Or:
1236     case Instruction::Xor:
1237     case Instruction::FAdd:
1238     case Instruction::FSub:
1239     case Instruction::FMul:
1240     case Instruction::FDiv:
1241     case Instruction::ICmp:
1242     case Instruction::FCmp:
1243       return true;
1244     case Instruction::Shl:
1245     case Instruction::LShr:
1246     case Instruction::AShr:
1247     case Instruction::UDiv:
1248     case Instruction::SDiv:
1249     case Instruction::URem:
1250     case Instruction::SRem:
1251       return Operand == 1;
1252     case Instruction::Call:
1253       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1254         switch (II->getIntrinsicID()) {
1255         case Intrinsic::fma:
1256         case Intrinsic::vp_fma:
1257           return Operand == 0 || Operand == 1;
1258         // FIXME: Our patterns can only match vx/vf instructions when the splat
1259         // it on the RHS, because TableGen doesn't recognize our VP operations
1260         // as commutative.
1261         case Intrinsic::vp_add:
1262         case Intrinsic::vp_mul:
1263         case Intrinsic::vp_and:
1264         case Intrinsic::vp_or:
1265         case Intrinsic::vp_xor:
1266         case Intrinsic::vp_fadd:
1267         case Intrinsic::vp_fmul:
1268         case Intrinsic::vp_shl:
1269         case Intrinsic::vp_lshr:
1270         case Intrinsic::vp_ashr:
1271         case Intrinsic::vp_udiv:
1272         case Intrinsic::vp_sdiv:
1273         case Intrinsic::vp_urem:
1274         case Intrinsic::vp_srem:
1275           return Operand == 1;
1276         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1277         // explicit patterns for both LHS and RHS (as 'vr' versions).
1278         case Intrinsic::vp_sub:
1279         case Intrinsic::vp_fsub:
1280         case Intrinsic::vp_fdiv:
1281           return Operand == 0 || Operand == 1;
1282         default:
1283           return false;
1284         }
1285       }
1286       return false;
1287     default:
1288       return false;
1289     }
1290   };
1291 
1292   for (auto OpIdx : enumerate(I->operands())) {
1293     if (!IsSinker(I, OpIdx.index()))
1294       continue;
1295 
1296     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1297     // Make sure we are not already sinking this operand
1298     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1299       continue;
1300 
1301     // We are looking for a splat that can be sunk.
1302     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1303                              m_Undef(), m_ZeroMask())))
1304       continue;
1305 
1306     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1307     // and vector registers
1308     for (Use &U : Op->uses()) {
1309       Instruction *Insn = cast<Instruction>(U.getUser());
1310       if (!IsSinker(Insn, U.getOperandNo()))
1311         return false;
1312     }
1313 
1314     Ops.push_back(&Op->getOperandUse(0));
1315     Ops.push_back(&OpIdx.value());
1316   }
1317   return true;
1318 }
1319 
1320 bool RISCVTargetLowering::isOffsetFoldingLegal(
1321     const GlobalAddressSDNode *GA) const {
1322   // In order to maximise the opportunity for common subexpression elimination,
1323   // keep a separate ADD node for the global address offset instead of folding
1324   // it in the global address node. Later peephole optimisations may choose to
1325   // fold it back in when profitable.
1326   return false;
1327 }
1328 
1329 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1330                                        bool ForCodeSize) const {
1331   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1332   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1333     return false;
1334   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1335     return false;
1336   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1337     return false;
1338   return Imm.isZero();
1339 }
1340 
1341 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1342   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1343          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1344          (VT == MVT::f64 && Subtarget.hasStdExtD());
1345 }
1346 
1347 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1348                                                       CallingConv::ID CC,
1349                                                       EVT VT) const {
1350   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1351   // We might still end up using a GPR but that will be decided based on ABI.
1352   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1353   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1354     return MVT::f32;
1355 
1356   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1357 }
1358 
1359 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1360                                                            CallingConv::ID CC,
1361                                                            EVT VT) const {
1362   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1363   // We might still end up using a GPR but that will be decided based on ABI.
1364   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1365   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1366     return 1;
1367 
1368   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1369 }
1370 
1371 // Changes the condition code and swaps operands if necessary, so the SetCC
1372 // operation matches one of the comparisons supported directly by branches
1373 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1374 // with 1/-1.
1375 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1376                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1377   // Convert X > -1 to X >= 0.
1378   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1379     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1380     CC = ISD::SETGE;
1381     return;
1382   }
1383   // Convert X < 1 to 0 >= X.
1384   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1385     RHS = LHS;
1386     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1387     CC = ISD::SETGE;
1388     return;
1389   }
1390 
1391   switch (CC) {
1392   default:
1393     break;
1394   case ISD::SETGT:
1395   case ISD::SETLE:
1396   case ISD::SETUGT:
1397   case ISD::SETULE:
1398     CC = ISD::getSetCCSwappedOperands(CC);
1399     std::swap(LHS, RHS);
1400     break;
1401   }
1402 }
1403 
1404 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1405   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1406   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1407   if (VT.getVectorElementType() == MVT::i1)
1408     KnownSize *= 8;
1409 
1410   switch (KnownSize) {
1411   default:
1412     llvm_unreachable("Invalid LMUL.");
1413   case 8:
1414     return RISCVII::VLMUL::LMUL_F8;
1415   case 16:
1416     return RISCVII::VLMUL::LMUL_F4;
1417   case 32:
1418     return RISCVII::VLMUL::LMUL_F2;
1419   case 64:
1420     return RISCVII::VLMUL::LMUL_1;
1421   case 128:
1422     return RISCVII::VLMUL::LMUL_2;
1423   case 256:
1424     return RISCVII::VLMUL::LMUL_4;
1425   case 512:
1426     return RISCVII::VLMUL::LMUL_8;
1427   }
1428 }
1429 
1430 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1431   switch (LMul) {
1432   default:
1433     llvm_unreachable("Invalid LMUL.");
1434   case RISCVII::VLMUL::LMUL_F8:
1435   case RISCVII::VLMUL::LMUL_F4:
1436   case RISCVII::VLMUL::LMUL_F2:
1437   case RISCVII::VLMUL::LMUL_1:
1438     return RISCV::VRRegClassID;
1439   case RISCVII::VLMUL::LMUL_2:
1440     return RISCV::VRM2RegClassID;
1441   case RISCVII::VLMUL::LMUL_4:
1442     return RISCV::VRM4RegClassID;
1443   case RISCVII::VLMUL::LMUL_8:
1444     return RISCV::VRM8RegClassID;
1445   }
1446 }
1447 
1448 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1449   RISCVII::VLMUL LMUL = getLMUL(VT);
1450   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1451       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1452       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1453       LMUL == RISCVII::VLMUL::LMUL_1) {
1454     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1455                   "Unexpected subreg numbering");
1456     return RISCV::sub_vrm1_0 + Index;
1457   }
1458   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1459     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1460                   "Unexpected subreg numbering");
1461     return RISCV::sub_vrm2_0 + Index;
1462   }
1463   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1464     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1465                   "Unexpected subreg numbering");
1466     return RISCV::sub_vrm4_0 + Index;
1467   }
1468   llvm_unreachable("Invalid vector type.");
1469 }
1470 
1471 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1472   if (VT.getVectorElementType() == MVT::i1)
1473     return RISCV::VRRegClassID;
1474   return getRegClassIDForLMUL(getLMUL(VT));
1475 }
1476 
1477 // Attempt to decompose a subvector insert/extract between VecVT and
1478 // SubVecVT via subregister indices. Returns the subregister index that
1479 // can perform the subvector insert/extract with the given element index, as
1480 // well as the index corresponding to any leftover subvectors that must be
1481 // further inserted/extracted within the register class for SubVecVT.
1482 std::pair<unsigned, unsigned>
1483 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1484     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1485     const RISCVRegisterInfo *TRI) {
1486   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1487                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1488                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1489                 "Register classes not ordered");
1490   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1491   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1492   // Try to compose a subregister index that takes us from the incoming
1493   // LMUL>1 register class down to the outgoing one. At each step we half
1494   // the LMUL:
1495   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1496   // Note that this is not guaranteed to find a subregister index, such as
1497   // when we are extracting from one VR type to another.
1498   unsigned SubRegIdx = RISCV::NoSubRegister;
1499   for (const unsigned RCID :
1500        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1501     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1502       VecVT = VecVT.getHalfNumVectorElementsVT();
1503       bool IsHi =
1504           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1505       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1506                                             getSubregIndexByMVT(VecVT, IsHi));
1507       if (IsHi)
1508         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1509     }
1510   return {SubRegIdx, InsertExtractIdx};
1511 }
1512 
1513 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1514 // stores for those types.
1515 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1516   return !Subtarget.useRVVForFixedLengthVectors() ||
1517          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1518 }
1519 
1520 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1521   if (ScalarTy->isPointerTy())
1522     return true;
1523 
1524   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1525       ScalarTy->isIntegerTy(32))
1526     return true;
1527 
1528   if (ScalarTy->isIntegerTy(64))
1529     return Subtarget.hasVInstructionsI64();
1530 
1531   if (ScalarTy->isHalfTy())
1532     return Subtarget.hasVInstructionsF16();
1533   if (ScalarTy->isFloatTy())
1534     return Subtarget.hasVInstructionsF32();
1535   if (ScalarTy->isDoubleTy())
1536     return Subtarget.hasVInstructionsF64();
1537 
1538   return false;
1539 }
1540 
1541 static SDValue getVLOperand(SDValue Op) {
1542   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1543           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1544          "Unexpected opcode");
1545   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1546   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1547   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1548       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1549   if (!II)
1550     return SDValue();
1551   return Op.getOperand(II->VLOperand + 1 + HasChain);
1552 }
1553 
1554 static bool useRVVForFixedLengthVectorVT(MVT VT,
1555                                          const RISCVSubtarget &Subtarget) {
1556   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1557   if (!Subtarget.useRVVForFixedLengthVectors())
1558     return false;
1559 
1560   // We only support a set of vector types with a consistent maximum fixed size
1561   // across all supported vector element types to avoid legalization issues.
1562   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1563   // fixed-length vector type we support is 1024 bytes.
1564   if (VT.getFixedSizeInBits() > 1024 * 8)
1565     return false;
1566 
1567   unsigned MinVLen = Subtarget.getRealMinVLen();
1568 
1569   MVT EltVT = VT.getVectorElementType();
1570 
1571   // Don't use RVV for vectors we cannot scalarize if required.
1572   switch (EltVT.SimpleTy) {
1573   // i1 is supported but has different rules.
1574   default:
1575     return false;
1576   case MVT::i1:
1577     // Masks can only use a single register.
1578     if (VT.getVectorNumElements() > MinVLen)
1579       return false;
1580     MinVLen /= 8;
1581     break;
1582   case MVT::i8:
1583   case MVT::i16:
1584   case MVT::i32:
1585     break;
1586   case MVT::i64:
1587     if (!Subtarget.hasVInstructionsI64())
1588       return false;
1589     break;
1590   case MVT::f16:
1591     if (!Subtarget.hasVInstructionsF16())
1592       return false;
1593     break;
1594   case MVT::f32:
1595     if (!Subtarget.hasVInstructionsF32())
1596       return false;
1597     break;
1598   case MVT::f64:
1599     if (!Subtarget.hasVInstructionsF64())
1600       return false;
1601     break;
1602   }
1603 
1604   // Reject elements larger than ELEN.
1605   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1606     return false;
1607 
1608   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1609   // Don't use RVV for types that don't fit.
1610   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1611     return false;
1612 
1613   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1614   // the base fixed length RVV support in place.
1615   if (!VT.isPow2VectorType())
1616     return false;
1617 
1618   return true;
1619 }
1620 
1621 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1622   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1623 }
1624 
1625 // Return the largest legal scalable vector type that matches VT's element type.
1626 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1627                                             const RISCVSubtarget &Subtarget) {
1628   // This may be called before legal types are setup.
1629   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1630           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1631          "Expected legal fixed length vector!");
1632 
1633   unsigned MinVLen = Subtarget.getRealMinVLen();
1634   unsigned MaxELen = Subtarget.getELEN();
1635 
1636   MVT EltVT = VT.getVectorElementType();
1637   switch (EltVT.SimpleTy) {
1638   default:
1639     llvm_unreachable("unexpected element type for RVV container");
1640   case MVT::i1:
1641   case MVT::i8:
1642   case MVT::i16:
1643   case MVT::i32:
1644   case MVT::i64:
1645   case MVT::f16:
1646   case MVT::f32:
1647   case MVT::f64: {
1648     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1649     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1650     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1651     unsigned NumElts =
1652         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1653     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1654     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1655     return MVT::getScalableVectorVT(EltVT, NumElts);
1656   }
1657   }
1658 }
1659 
1660 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1661                                             const RISCVSubtarget &Subtarget) {
1662   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1663                                           Subtarget);
1664 }
1665 
1666 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1667   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1668 }
1669 
1670 // Grow V to consume an entire RVV register.
1671 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1672                                        const RISCVSubtarget &Subtarget) {
1673   assert(VT.isScalableVector() &&
1674          "Expected to convert into a scalable vector!");
1675   assert(V.getValueType().isFixedLengthVector() &&
1676          "Expected a fixed length vector operand!");
1677   SDLoc DL(V);
1678   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1679   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1680 }
1681 
1682 // Shrink V so it's just big enough to maintain a VT's worth of data.
1683 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1684                                          const RISCVSubtarget &Subtarget) {
1685   assert(VT.isFixedLengthVector() &&
1686          "Expected to convert into a fixed length vector!");
1687   assert(V.getValueType().isScalableVector() &&
1688          "Expected a scalable vector operand!");
1689   SDLoc DL(V);
1690   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1691   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1692 }
1693 
1694 /// Return the type of the mask type suitable for masking the provided
1695 /// vector type.  This is simply an i1 element type vector of the same
1696 /// (possibly scalable) length.
1697 static MVT getMaskTypeFor(MVT VecVT) {
1698   assert(VecVT.isVector());
1699   ElementCount EC = VecVT.getVectorElementCount();
1700   return MVT::getVectorVT(MVT::i1, EC);
1701 }
1702 
1703 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1704 /// vector length VL.  .
1705 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1706                               SelectionDAG &DAG) {
1707   MVT MaskVT = getMaskTypeFor(VecVT);
1708   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1709 }
1710 
1711 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1712 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1713 // the vector type that it is contained in.
1714 static std::pair<SDValue, SDValue>
1715 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1716                 const RISCVSubtarget &Subtarget) {
1717   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1718   MVT XLenVT = Subtarget.getXLenVT();
1719   SDValue VL = VecVT.isFixedLengthVector()
1720                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1721                    : DAG.getRegister(RISCV::X0, XLenVT);
1722   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1723   return {Mask, VL};
1724 }
1725 
1726 // As above but assuming the given type is a scalable vector type.
1727 static std::pair<SDValue, SDValue>
1728 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1729                         const RISCVSubtarget &Subtarget) {
1730   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1731   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1732 }
1733 
1734 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1735 // of either is (currently) supported. This can get us into an infinite loop
1736 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1737 // as a ..., etc.
1738 // Until either (or both) of these can reliably lower any node, reporting that
1739 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1740 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1741 // which is not desirable.
1742 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1743     EVT VT, unsigned DefinedValues) const {
1744   return false;
1745 }
1746 
1747 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1748                                   const RISCVSubtarget &Subtarget) {
1749   // RISCV FP-to-int conversions saturate to the destination register size, but
1750   // don't produce 0 for nan. We can use a conversion instruction and fix the
1751   // nan case with a compare and a select.
1752   SDValue Src = Op.getOperand(0);
1753 
1754   EVT DstVT = Op.getValueType();
1755   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1756 
1757   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1758   unsigned Opc;
1759   if (SatVT == DstVT)
1760     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1761   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1762     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1763   else
1764     return SDValue();
1765   // FIXME: Support other SatVTs by clamping before or after the conversion.
1766 
1767   SDLoc DL(Op);
1768   SDValue FpToInt = DAG.getNode(
1769       Opc, DL, DstVT, Src,
1770       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1771 
1772   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1773   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1774 }
1775 
1776 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1777 // and back. Taking care to avoid converting values that are nan or already
1778 // correct.
1779 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1780 // have FRM dependencies modeled yet.
1781 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1782   MVT VT = Op.getSimpleValueType();
1783   assert(VT.isVector() && "Unexpected type");
1784 
1785   SDLoc DL(Op);
1786 
1787   // Freeze the source since we are increasing the number of uses.
1788   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1789 
1790   // Truncate to integer and convert back to FP.
1791   MVT IntVT = VT.changeVectorElementTypeToInteger();
1792   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1793   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1794 
1795   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1796 
1797   if (Op.getOpcode() == ISD::FCEIL) {
1798     // If the truncated value is the greater than or equal to the original
1799     // value, we've computed the ceil. Otherwise, we went the wrong way and
1800     // need to increase by 1.
1801     // FIXME: This should use a masked operation. Handle here or in isel?
1802     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1803                                  DAG.getConstantFP(1.0, DL, VT));
1804     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1805     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1806   } else if (Op.getOpcode() == ISD::FFLOOR) {
1807     // If the truncated value is the less than or equal to the original value,
1808     // we've computed the floor. Otherwise, we went the wrong way and need to
1809     // decrease by 1.
1810     // FIXME: This should use a masked operation. Handle here or in isel?
1811     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1812                                  DAG.getConstantFP(1.0, DL, VT));
1813     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1814     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1815   }
1816 
1817   // Restore the original sign so that -0.0 is preserved.
1818   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1819 
1820   // Determine the largest integer that can be represented exactly. This and
1821   // values larger than it don't have any fractional bits so don't need to
1822   // be converted.
1823   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1824   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1825   APFloat MaxVal = APFloat(FltSem);
1826   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1827                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1828   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1829 
1830   // If abs(Src) was larger than MaxVal or nan, keep it.
1831   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1832   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1833   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1834 }
1835 
1836 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1837 // This mode isn't supported in vector hardware on RISCV. But as long as we
1838 // aren't compiling with trapping math, we can emulate this with
1839 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1840 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1841 // dependencies modeled yet.
1842 // FIXME: Use masked operations to avoid final merge.
1843 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1844   MVT VT = Op.getSimpleValueType();
1845   assert(VT.isVector() && "Unexpected type");
1846 
1847   SDLoc DL(Op);
1848 
1849   // Freeze the source since we are increasing the number of uses.
1850   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1851 
1852   // We do the conversion on the absolute value and fix the sign at the end.
1853   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1854 
1855   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1856   bool Ignored;
1857   APFloat Point5Pred = APFloat(0.5f);
1858   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1859   Point5Pred.next(/*nextDown*/ true);
1860 
1861   // Add the adjustment.
1862   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1863                                DAG.getConstantFP(Point5Pred, DL, VT));
1864 
1865   // Truncate to integer and convert back to fp.
1866   MVT IntVT = VT.changeVectorElementTypeToInteger();
1867   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1868   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1869 
1870   // Restore the original sign.
1871   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1872 
1873   // Determine the largest integer that can be represented exactly. This and
1874   // values larger than it don't have any fractional bits so don't need to
1875   // be converted.
1876   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1877   APFloat MaxVal = APFloat(FltSem);
1878   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1879                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1880   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1881 
1882   // If abs(Src) was larger than MaxVal or nan, keep it.
1883   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1884   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1885   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1886 }
1887 
1888 struct VIDSequence {
1889   int64_t StepNumerator;
1890   unsigned StepDenominator;
1891   int64_t Addend;
1892 };
1893 
1894 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1895 // to the (non-zero) step S and start value X. This can be then lowered as the
1896 // RVV sequence (VID * S) + X, for example.
1897 // The step S is represented as an integer numerator divided by a positive
1898 // denominator. Note that the implementation currently only identifies
1899 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1900 // cannot detect 2/3, for example.
1901 // Note that this method will also match potentially unappealing index
1902 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1903 // determine whether this is worth generating code for.
1904 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1905   unsigned NumElts = Op.getNumOperands();
1906   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1907   if (!Op.getValueType().isInteger())
1908     return None;
1909 
1910   Optional<unsigned> SeqStepDenom;
1911   Optional<int64_t> SeqStepNum, SeqAddend;
1912   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1913   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1914   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1915     // Assume undef elements match the sequence; we just have to be careful
1916     // when interpolating across them.
1917     if (Op.getOperand(Idx).isUndef())
1918       continue;
1919     // The BUILD_VECTOR must be all constants.
1920     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1921       return None;
1922 
1923     uint64_t Val = Op.getConstantOperandVal(Idx) &
1924                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1925 
1926     if (PrevElt) {
1927       // Calculate the step since the last non-undef element, and ensure
1928       // it's consistent across the entire sequence.
1929       unsigned IdxDiff = Idx - PrevElt->second;
1930       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1931 
1932       // A zero-value value difference means that we're somewhere in the middle
1933       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1934       // step change before evaluating the sequence.
1935       if (ValDiff == 0)
1936         continue;
1937 
1938       int64_t Remainder = ValDiff % IdxDiff;
1939       // Normalize the step if it's greater than 1.
1940       if (Remainder != ValDiff) {
1941         // The difference must cleanly divide the element span.
1942         if (Remainder != 0)
1943           return None;
1944         ValDiff /= IdxDiff;
1945         IdxDiff = 1;
1946       }
1947 
1948       if (!SeqStepNum)
1949         SeqStepNum = ValDiff;
1950       else if (ValDiff != SeqStepNum)
1951         return None;
1952 
1953       if (!SeqStepDenom)
1954         SeqStepDenom = IdxDiff;
1955       else if (IdxDiff != *SeqStepDenom)
1956         return None;
1957     }
1958 
1959     // Record this non-undef element for later.
1960     if (!PrevElt || PrevElt->first != Val)
1961       PrevElt = std::make_pair(Val, Idx);
1962   }
1963 
1964   // We need to have logged a step for this to count as a legal index sequence.
1965   if (!SeqStepNum || !SeqStepDenom)
1966     return None;
1967 
1968   // Loop back through the sequence and validate elements we might have skipped
1969   // while waiting for a valid step. While doing this, log any sequence addend.
1970   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1971     if (Op.getOperand(Idx).isUndef())
1972       continue;
1973     uint64_t Val = Op.getConstantOperandVal(Idx) &
1974                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1975     uint64_t ExpectedVal =
1976         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1977     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1978     if (!SeqAddend)
1979       SeqAddend = Addend;
1980     else if (Addend != SeqAddend)
1981       return None;
1982   }
1983 
1984   assert(SeqAddend && "Must have an addend if we have a step");
1985 
1986   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1987 }
1988 
1989 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1990 // and lower it as a VRGATHER_VX_VL from the source vector.
1991 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1992                                   SelectionDAG &DAG,
1993                                   const RISCVSubtarget &Subtarget) {
1994   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1995     return SDValue();
1996   SDValue Vec = SplatVal.getOperand(0);
1997   // Only perform this optimization on vectors of the same size for simplicity.
1998   // Don't perform this optimization for i1 vectors.
1999   // FIXME: Support i1 vectors, maybe by promoting to i8?
2000   if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
2001     return SDValue();
2002   SDValue Idx = SplatVal.getOperand(1);
2003   // The index must be a legal type.
2004   if (Idx.getValueType() != Subtarget.getXLenVT())
2005     return SDValue();
2006 
2007   MVT ContainerVT = VT;
2008   if (VT.isFixedLengthVector()) {
2009     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2010     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2011   }
2012 
2013   SDValue Mask, VL;
2014   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2015 
2016   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2017                                Idx, Mask, DAG.getUNDEF(ContainerVT), VL);
2018 
2019   if (!VT.isFixedLengthVector())
2020     return Gather;
2021 
2022   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2023 }
2024 
2025 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2026                                  const RISCVSubtarget &Subtarget) {
2027   MVT VT = Op.getSimpleValueType();
2028   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2029 
2030   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2031 
2032   SDLoc DL(Op);
2033   SDValue Mask, VL;
2034   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2035 
2036   MVT XLenVT = Subtarget.getXLenVT();
2037   unsigned NumElts = Op.getNumOperands();
2038 
2039   if (VT.getVectorElementType() == MVT::i1) {
2040     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2041       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2042       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2043     }
2044 
2045     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2046       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2047       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2048     }
2049 
2050     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2051     // scalar integer chunks whose bit-width depends on the number of mask
2052     // bits and XLEN.
2053     // First, determine the most appropriate scalar integer type to use. This
2054     // is at most XLenVT, but may be shrunk to a smaller vector element type
2055     // according to the size of the final vector - use i8 chunks rather than
2056     // XLenVT if we're producing a v8i1. This results in more consistent
2057     // codegen across RV32 and RV64.
2058     unsigned NumViaIntegerBits =
2059         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2060     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2061     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2062       // If we have to use more than one INSERT_VECTOR_ELT then this
2063       // optimization is likely to increase code size; avoid peforming it in
2064       // such a case. We can use a load from a constant pool in this case.
2065       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2066         return SDValue();
2067       // Now we can create our integer vector type. Note that it may be larger
2068       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2069       MVT IntegerViaVecVT =
2070           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2071                            divideCeil(NumElts, NumViaIntegerBits));
2072 
2073       uint64_t Bits = 0;
2074       unsigned BitPos = 0, IntegerEltIdx = 0;
2075       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2076 
2077       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2078         // Once we accumulate enough bits to fill our scalar type, insert into
2079         // our vector and clear our accumulated data.
2080         if (I != 0 && I % NumViaIntegerBits == 0) {
2081           if (NumViaIntegerBits <= 32)
2082             Bits = SignExtend64<32>(Bits);
2083           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2084           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2085                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2086           Bits = 0;
2087           BitPos = 0;
2088           IntegerEltIdx++;
2089         }
2090         SDValue V = Op.getOperand(I);
2091         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2092         Bits |= ((uint64_t)BitValue << BitPos);
2093       }
2094 
2095       // Insert the (remaining) scalar value into position in our integer
2096       // vector type.
2097       if (NumViaIntegerBits <= 32)
2098         Bits = SignExtend64<32>(Bits);
2099       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2100       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2101                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2102 
2103       if (NumElts < NumViaIntegerBits) {
2104         // If we're producing a smaller vector than our minimum legal integer
2105         // type, bitcast to the equivalent (known-legal) mask type, and extract
2106         // our final mask.
2107         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2108         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2109         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2110                           DAG.getConstant(0, DL, XLenVT));
2111       } else {
2112         // Else we must have produced an integer type with the same size as the
2113         // mask type; bitcast for the final result.
2114         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2115         Vec = DAG.getBitcast(VT, Vec);
2116       }
2117 
2118       return Vec;
2119     }
2120 
2121     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2122     // vector type, we have a legal equivalently-sized i8 type, so we can use
2123     // that.
2124     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2125     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2126 
2127     SDValue WideVec;
2128     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2129       // For a splat, perform a scalar truncate before creating the wider
2130       // vector.
2131       assert(Splat.getValueType() == XLenVT &&
2132              "Unexpected type for i1 splat value");
2133       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2134                           DAG.getConstant(1, DL, XLenVT));
2135       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2136     } else {
2137       SmallVector<SDValue, 8> Ops(Op->op_values());
2138       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2139       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2140       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2141     }
2142 
2143     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2144   }
2145 
2146   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2147     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2148       return Gather;
2149     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2150                                         : RISCVISD::VMV_V_X_VL;
2151     Splat =
2152         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2153     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2154   }
2155 
2156   // Try and match index sequences, which we can lower to the vid instruction
2157   // with optional modifications. An all-undef vector is matched by
2158   // getSplatValue, above.
2159   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2160     int64_t StepNumerator = SimpleVID->StepNumerator;
2161     unsigned StepDenominator = SimpleVID->StepDenominator;
2162     int64_t Addend = SimpleVID->Addend;
2163 
2164     assert(StepNumerator != 0 && "Invalid step");
2165     bool Negate = false;
2166     int64_t SplatStepVal = StepNumerator;
2167     unsigned StepOpcode = ISD::MUL;
2168     if (StepNumerator != 1) {
2169       if (isPowerOf2_64(std::abs(StepNumerator))) {
2170         Negate = StepNumerator < 0;
2171         StepOpcode = ISD::SHL;
2172         SplatStepVal = Log2_64(std::abs(StepNumerator));
2173       }
2174     }
2175 
2176     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2177     // threshold since it's the immediate value many RVV instructions accept.
2178     // There is no vmul.vi instruction so ensure multiply constant can fit in
2179     // a single addi instruction.
2180     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2181          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2182         isPowerOf2_32(StepDenominator) &&
2183         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2184       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2185       // Convert right out of the scalable type so we can use standard ISD
2186       // nodes for the rest of the computation. If we used scalable types with
2187       // these, we'd lose the fixed-length vector info and generate worse
2188       // vsetvli code.
2189       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2190       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2191           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2192         SDValue SplatStep = DAG.getSplatBuildVector(
2193             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2194         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2195       }
2196       if (StepDenominator != 1) {
2197         SDValue SplatStep = DAG.getSplatBuildVector(
2198             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2199         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2200       }
2201       if (Addend != 0 || Negate) {
2202         SDValue SplatAddend = DAG.getSplatBuildVector(
2203             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2204         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2205       }
2206       return VID;
2207     }
2208   }
2209 
2210   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2211   // when re-interpreted as a vector with a larger element type. For example,
2212   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2213   // could be instead splat as
2214   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2215   // TODO: This optimization could also work on non-constant splats, but it
2216   // would require bit-manipulation instructions to construct the splat value.
2217   SmallVector<SDValue> Sequence;
2218   unsigned EltBitSize = VT.getScalarSizeInBits();
2219   const auto *BV = cast<BuildVectorSDNode>(Op);
2220   if (VT.isInteger() && EltBitSize < 64 &&
2221       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2222       BV->getRepeatedSequence(Sequence) &&
2223       (Sequence.size() * EltBitSize) <= 64) {
2224     unsigned SeqLen = Sequence.size();
2225     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2226     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2227     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2228             ViaIntVT == MVT::i64) &&
2229            "Unexpected sequence type");
2230 
2231     unsigned EltIdx = 0;
2232     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2233     uint64_t SplatValue = 0;
2234     // Construct the amalgamated value which can be splatted as this larger
2235     // vector type.
2236     for (const auto &SeqV : Sequence) {
2237       if (!SeqV.isUndef())
2238         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2239                        << (EltIdx * EltBitSize));
2240       EltIdx++;
2241     }
2242 
2243     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2244     // achieve better constant materializion.
2245     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2246       SplatValue = SignExtend64<32>(SplatValue);
2247 
2248     // Since we can't introduce illegal i64 types at this stage, we can only
2249     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2250     // way we can use RVV instructions to splat.
2251     assert((ViaIntVT.bitsLE(XLenVT) ||
2252             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2253            "Unexpected bitcast sequence");
2254     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2255       SDValue ViaVL =
2256           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2257       MVT ViaContainerVT =
2258           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2259       SDValue Splat =
2260           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2261                       DAG.getUNDEF(ViaContainerVT),
2262                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2263       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2264       return DAG.getBitcast(VT, Splat);
2265     }
2266   }
2267 
2268   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2269   // which constitute a large proportion of the elements. In such cases we can
2270   // splat a vector with the dominant element and make up the shortfall with
2271   // INSERT_VECTOR_ELTs.
2272   // Note that this includes vectors of 2 elements by association. The
2273   // upper-most element is the "dominant" one, allowing us to use a splat to
2274   // "insert" the upper element, and an insert of the lower element at position
2275   // 0, which improves codegen.
2276   SDValue DominantValue;
2277   unsigned MostCommonCount = 0;
2278   DenseMap<SDValue, unsigned> ValueCounts;
2279   unsigned NumUndefElts =
2280       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2281 
2282   // Track the number of scalar loads we know we'd be inserting, estimated as
2283   // any non-zero floating-point constant. Other kinds of element are either
2284   // already in registers or are materialized on demand. The threshold at which
2285   // a vector load is more desirable than several scalar materializion and
2286   // vector-insertion instructions is not known.
2287   unsigned NumScalarLoads = 0;
2288 
2289   for (SDValue V : Op->op_values()) {
2290     if (V.isUndef())
2291       continue;
2292 
2293     ValueCounts.insert(std::make_pair(V, 0));
2294     unsigned &Count = ValueCounts[V];
2295 
2296     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2297       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2298 
2299     // Is this value dominant? In case of a tie, prefer the highest element as
2300     // it's cheaper to insert near the beginning of a vector than it is at the
2301     // end.
2302     if (++Count >= MostCommonCount) {
2303       DominantValue = V;
2304       MostCommonCount = Count;
2305     }
2306   }
2307 
2308   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2309   unsigned NumDefElts = NumElts - NumUndefElts;
2310   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2311 
2312   // Don't perform this optimization when optimizing for size, since
2313   // materializing elements and inserting them tends to cause code bloat.
2314   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2315       ((MostCommonCount > DominantValueCountThreshold) ||
2316        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2317     // Start by splatting the most common element.
2318     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2319 
2320     DenseSet<SDValue> Processed{DominantValue};
2321     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2322     for (const auto &OpIdx : enumerate(Op->ops())) {
2323       const SDValue &V = OpIdx.value();
2324       if (V.isUndef() || !Processed.insert(V).second)
2325         continue;
2326       if (ValueCounts[V] == 1) {
2327         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2328                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2329       } else {
2330         // Blend in all instances of this value using a VSELECT, using a
2331         // mask where each bit signals whether that element is the one
2332         // we're after.
2333         SmallVector<SDValue> Ops;
2334         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2335           return DAG.getConstant(V == V1, DL, XLenVT);
2336         });
2337         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2338                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2339                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2340       }
2341     }
2342 
2343     return Vec;
2344   }
2345 
2346   return SDValue();
2347 }
2348 
2349 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2350                                    SDValue Lo, SDValue Hi, SDValue VL,
2351                                    SelectionDAG &DAG) {
2352   if (!Passthru)
2353     Passthru = DAG.getUNDEF(VT);
2354   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2355     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2356     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2357     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2358     // node in order to try and match RVV vector/scalar instructions.
2359     if ((LoC >> 31) == HiC)
2360       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2361 
2362     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2363     // vmv.v.x whose EEW = 32 to lower it.
2364     auto *Const = dyn_cast<ConstantSDNode>(VL);
2365     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2366       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2367       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2368       // access the subtarget here now.
2369       auto InterVec = DAG.getNode(
2370           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2371                                   DAG.getRegister(RISCV::X0, MVT::i32));
2372       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2373     }
2374   }
2375 
2376   // Fall back to a stack store and stride x0 vector load.
2377   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2378                      Hi, VL);
2379 }
2380 
2381 // Called by type legalization to handle splat of i64 on RV32.
2382 // FIXME: We can optimize this when the type has sign or zero bits in one
2383 // of the halves.
2384 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2385                                    SDValue Scalar, SDValue VL,
2386                                    SelectionDAG &DAG) {
2387   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2388   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2389                            DAG.getConstant(0, DL, MVT::i32));
2390   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2391                            DAG.getConstant(1, DL, MVT::i32));
2392   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2393 }
2394 
2395 // This function lowers a splat of a scalar operand Splat with the vector
2396 // length VL. It ensures the final sequence is type legal, which is useful when
2397 // lowering a splat after type legalization.
2398 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2399                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2400                                 const RISCVSubtarget &Subtarget) {
2401   bool HasPassthru = Passthru && !Passthru.isUndef();
2402   if (!HasPassthru && !Passthru)
2403     Passthru = DAG.getUNDEF(VT);
2404   if (VT.isFloatingPoint()) {
2405     // If VL is 1, we could use vfmv.s.f.
2406     if (isOneConstant(VL))
2407       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2408     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2409   }
2410 
2411   MVT XLenVT = Subtarget.getXLenVT();
2412 
2413   // Simplest case is that the operand needs to be promoted to XLenVT.
2414   if (Scalar.getValueType().bitsLE(XLenVT)) {
2415     // If the operand is a constant, sign extend to increase our chances
2416     // of being able to use a .vi instruction. ANY_EXTEND would become a
2417     // a zero extend and the simm5 check in isel would fail.
2418     // FIXME: Should we ignore the upper bits in isel instead?
2419     unsigned ExtOpc =
2420         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2421     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2422     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2423     // If VL is 1 and the scalar value won't benefit from immediate, we could
2424     // use vmv.s.x.
2425     if (isOneConstant(VL) &&
2426         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2427       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2428     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2429   }
2430 
2431   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2432          "Unexpected scalar for splat lowering!");
2433 
2434   if (isOneConstant(VL) && isNullConstant(Scalar))
2435     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2436                        DAG.getConstant(0, DL, XLenVT), VL);
2437 
2438   // Otherwise use the more complicated splatting algorithm.
2439   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2440 }
2441 
2442 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2443                                 const RISCVSubtarget &Subtarget) {
2444   // We need to be able to widen elements to the next larger integer type.
2445   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2446     return false;
2447 
2448   int Size = Mask.size();
2449   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2450 
2451   int Srcs[] = {-1, -1};
2452   for (int i = 0; i != Size; ++i) {
2453     // Ignore undef elements.
2454     if (Mask[i] < 0)
2455       continue;
2456 
2457     // Is this an even or odd element.
2458     int Pol = i % 2;
2459 
2460     // Ensure we consistently use the same source for this element polarity.
2461     int Src = Mask[i] / Size;
2462     if (Srcs[Pol] < 0)
2463       Srcs[Pol] = Src;
2464     if (Srcs[Pol] != Src)
2465       return false;
2466 
2467     // Make sure the element within the source is appropriate for this element
2468     // in the destination.
2469     int Elt = Mask[i] % Size;
2470     if (Elt != i / 2)
2471       return false;
2472   }
2473 
2474   // We need to find a source for each polarity and they can't be the same.
2475   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2476     return false;
2477 
2478   // Swap the sources if the second source was in the even polarity.
2479   SwapSources = Srcs[0] > Srcs[1];
2480 
2481   return true;
2482 }
2483 
2484 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2485 /// and then extract the original number of elements from the rotated result.
2486 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2487 /// returned rotation amount is for a rotate right, where elements move from
2488 /// higher elements to lower elements. \p LoSrc indicates the first source
2489 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2490 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2491 /// 0 or 1 if a rotation is found.
2492 ///
2493 /// NOTE: We talk about rotate to the right which matches how bit shift and
2494 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2495 /// and the table below write vectors with the lowest elements on the left.
2496 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2497   int Size = Mask.size();
2498 
2499   // We need to detect various ways of spelling a rotation:
2500   //   [11, 12, 13, 14, 15,  0,  1,  2]
2501   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2502   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2503   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2504   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2505   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2506   int Rotation = 0;
2507   LoSrc = -1;
2508   HiSrc = -1;
2509   for (int i = 0; i != Size; ++i) {
2510     int M = Mask[i];
2511     if (M < 0)
2512       continue;
2513 
2514     // Determine where a rotate vector would have started.
2515     int StartIdx = i - (M % Size);
2516     // The identity rotation isn't interesting, stop.
2517     if (StartIdx == 0)
2518       return -1;
2519 
2520     // If we found the tail of a vector the rotation must be the missing
2521     // front. If we found the head of a vector, it must be how much of the
2522     // head.
2523     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2524 
2525     if (Rotation == 0)
2526       Rotation = CandidateRotation;
2527     else if (Rotation != CandidateRotation)
2528       // The rotations don't match, so we can't match this mask.
2529       return -1;
2530 
2531     // Compute which value this mask is pointing at.
2532     int MaskSrc = M < Size ? 0 : 1;
2533 
2534     // Compute which of the two target values this index should be assigned to.
2535     // This reflects whether the high elements are remaining or the low elemnts
2536     // are remaining.
2537     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2538 
2539     // Either set up this value if we've not encountered it before, or check
2540     // that it remains consistent.
2541     if (TargetSrc < 0)
2542       TargetSrc = MaskSrc;
2543     else if (TargetSrc != MaskSrc)
2544       // This may be a rotation, but it pulls from the inputs in some
2545       // unsupported interleaving.
2546       return -1;
2547   }
2548 
2549   // Check that we successfully analyzed the mask, and normalize the results.
2550   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2551   assert((LoSrc >= 0 || HiSrc >= 0) &&
2552          "Failed to find a rotated input vector!");
2553 
2554   return Rotation;
2555 }
2556 
2557 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2558                                    const RISCVSubtarget &Subtarget) {
2559   SDValue V1 = Op.getOperand(0);
2560   SDValue V2 = Op.getOperand(1);
2561   SDLoc DL(Op);
2562   MVT XLenVT = Subtarget.getXLenVT();
2563   MVT VT = Op.getSimpleValueType();
2564   unsigned NumElts = VT.getVectorNumElements();
2565   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2566 
2567   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2568 
2569   SDValue TrueMask, VL;
2570   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2571 
2572   if (SVN->isSplat()) {
2573     const int Lane = SVN->getSplatIndex();
2574     if (Lane >= 0) {
2575       MVT SVT = VT.getVectorElementType();
2576 
2577       // Turn splatted vector load into a strided load with an X0 stride.
2578       SDValue V = V1;
2579       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2580       // with undef.
2581       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2582       int Offset = Lane;
2583       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2584         int OpElements =
2585             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2586         V = V.getOperand(Offset / OpElements);
2587         Offset %= OpElements;
2588       }
2589 
2590       // We need to ensure the load isn't atomic or volatile.
2591       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2592         auto *Ld = cast<LoadSDNode>(V);
2593         Offset *= SVT.getStoreSize();
2594         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2595                                                    TypeSize::Fixed(Offset), DL);
2596 
2597         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2598         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2599           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2600           SDValue IntID =
2601               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2602           SDValue Ops[] = {Ld->getChain(),
2603                            IntID,
2604                            DAG.getUNDEF(ContainerVT),
2605                            NewAddr,
2606                            DAG.getRegister(RISCV::X0, XLenVT),
2607                            VL};
2608           SDValue NewLoad = DAG.getMemIntrinsicNode(
2609               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2610               DAG.getMachineFunction().getMachineMemOperand(
2611                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2612           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2613           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2614         }
2615 
2616         // Otherwise use a scalar load and splat. This will give the best
2617         // opportunity to fold a splat into the operation. ISel can turn it into
2618         // the x0 strided load if we aren't able to fold away the select.
2619         if (SVT.isFloatingPoint())
2620           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2621                           Ld->getPointerInfo().getWithOffset(Offset),
2622                           Ld->getOriginalAlign(),
2623                           Ld->getMemOperand()->getFlags());
2624         else
2625           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2626                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2627                              Ld->getOriginalAlign(),
2628                              Ld->getMemOperand()->getFlags());
2629         DAG.makeEquivalentMemoryOrdering(Ld, V);
2630 
2631         unsigned Opc =
2632             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2633         SDValue Splat =
2634             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2635         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2636       }
2637 
2638       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2639       assert(Lane < (int)NumElts && "Unexpected lane!");
2640       SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
2641                                    V1, DAG.getConstant(Lane, DL, XLenVT),
2642                                    TrueMask, DAG.getUNDEF(ContainerVT), VL);
2643       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2644     }
2645   }
2646 
2647   ArrayRef<int> Mask = SVN->getMask();
2648 
2649   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2650   // be undef which can be handled with a single SLIDEDOWN/UP.
2651   int LoSrc, HiSrc;
2652   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2653   if (Rotation > 0) {
2654     SDValue LoV, HiV;
2655     if (LoSrc >= 0) {
2656       LoV = LoSrc == 0 ? V1 : V2;
2657       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2658     }
2659     if (HiSrc >= 0) {
2660       HiV = HiSrc == 0 ? V1 : V2;
2661       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2662     }
2663 
2664     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2665     // to slide LoV up by (NumElts - Rotation).
2666     unsigned InvRotate = NumElts - Rotation;
2667 
2668     SDValue Res = DAG.getUNDEF(ContainerVT);
2669     if (HiV) {
2670       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2671       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2672       // causes multiple vsetvlis in some test cases such as lowering
2673       // reduce.mul
2674       SDValue DownVL = VL;
2675       if (LoV)
2676         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2677       Res =
2678           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2679                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2680     }
2681     if (LoV)
2682       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2683                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2684 
2685     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2686   }
2687 
2688   // Detect an interleave shuffle and lower to
2689   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2690   bool SwapSources;
2691   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2692     // Swap sources if needed.
2693     if (SwapSources)
2694       std::swap(V1, V2);
2695 
2696     // Extract the lower half of the vectors.
2697     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2698     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2699                      DAG.getConstant(0, DL, XLenVT));
2700     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2701                      DAG.getConstant(0, DL, XLenVT));
2702 
2703     // Double the element width and halve the number of elements in an int type.
2704     unsigned EltBits = VT.getScalarSizeInBits();
2705     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2706     MVT WideIntVT =
2707         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2708     // Convert this to a scalable vector. We need to base this on the
2709     // destination size to ensure there's always a type with a smaller LMUL.
2710     MVT WideIntContainerVT =
2711         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2712 
2713     // Convert sources to scalable vectors with the same element count as the
2714     // larger type.
2715     MVT HalfContainerVT = MVT::getVectorVT(
2716         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2717     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2718     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2719 
2720     // Cast sources to integer.
2721     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2722     MVT IntHalfVT =
2723         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2724     V1 = DAG.getBitcast(IntHalfVT, V1);
2725     V2 = DAG.getBitcast(IntHalfVT, V2);
2726 
2727     // Freeze V2 since we use it twice and we need to be sure that the add and
2728     // multiply see the same value.
2729     V2 = DAG.getFreeze(V2);
2730 
2731     // Recreate TrueMask using the widened type's element count.
2732     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2733 
2734     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2735     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2736                               V2, TrueMask, VL);
2737     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2738     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2739                                      DAG.getUNDEF(IntHalfVT),
2740                                      DAG.getAllOnesConstant(DL, XLenVT));
2741     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2742                                    V2, Multiplier, TrueMask, VL);
2743     // Add the new copies to our previous addition giving us 2^eltbits copies of
2744     // V2. This is equivalent to shifting V2 left by eltbits. This should
2745     // combine with the vwmulu.vv above to form vwmaccu.vv.
2746     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2747                       TrueMask, VL);
2748     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2749     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2750     // vector VT.
2751     ContainerVT =
2752         MVT::getVectorVT(VT.getVectorElementType(),
2753                          WideIntContainerVT.getVectorElementCount() * 2);
2754     Add = DAG.getBitcast(ContainerVT, Add);
2755     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2756   }
2757 
2758   // Detect shuffles which can be re-expressed as vector selects; these are
2759   // shuffles in which each element in the destination is taken from an element
2760   // at the corresponding index in either source vectors.
2761   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2762     int MaskIndex = MaskIdx.value();
2763     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2764   });
2765 
2766   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2767 
2768   SmallVector<SDValue> MaskVals;
2769   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2770   // merged with a second vrgather.
2771   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2772 
2773   // By default we preserve the original operand order, and use a mask to
2774   // select LHS as true and RHS as false. However, since RVV vector selects may
2775   // feature splats but only on the LHS, we may choose to invert our mask and
2776   // instead select between RHS and LHS.
2777   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2778   bool InvertMask = IsSelect == SwapOps;
2779 
2780   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2781   // half.
2782   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2783 
2784   // Now construct the mask that will be used by the vselect or blended
2785   // vrgather operation. For vrgathers, construct the appropriate indices into
2786   // each vector.
2787   for (int MaskIndex : Mask) {
2788     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2789     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2790     if (!IsSelect) {
2791       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2792       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2793                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2794                                      : DAG.getUNDEF(XLenVT));
2795       GatherIndicesRHS.push_back(
2796           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2797                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2798       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2799         ++LHSIndexCounts[MaskIndex];
2800       if (!IsLHSOrUndefIndex)
2801         ++RHSIndexCounts[MaskIndex - NumElts];
2802     }
2803   }
2804 
2805   if (SwapOps) {
2806     std::swap(V1, V2);
2807     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2808   }
2809 
2810   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2811   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2812   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2813 
2814   if (IsSelect)
2815     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2816 
2817   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2818     // On such a large vector we're unable to use i8 as the index type.
2819     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2820     // may involve vector splitting if we're already at LMUL=8, or our
2821     // user-supplied maximum fixed-length LMUL.
2822     return SDValue();
2823   }
2824 
2825   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2826   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2827   MVT IndexVT = VT.changeTypeToInteger();
2828   // Since we can't introduce illegal index types at this stage, use i16 and
2829   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2830   // than XLenVT.
2831   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2832     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2833     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2834   }
2835 
2836   MVT IndexContainerVT =
2837       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2838 
2839   SDValue Gather;
2840   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2841   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2842   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2843     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2844                               Subtarget);
2845   } else {
2846     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2847     // If only one index is used, we can use a "splat" vrgather.
2848     // TODO: We can splat the most-common index and fix-up any stragglers, if
2849     // that's beneficial.
2850     if (LHSIndexCounts.size() == 1) {
2851       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2852       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2853                            DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask,
2854                            DAG.getUNDEF(ContainerVT), VL);
2855     } else {
2856       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2857       LHSIndices =
2858           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2859 
2860       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2861                            TrueMask, DAG.getUNDEF(ContainerVT), VL);
2862     }
2863   }
2864 
2865   // If a second vector operand is used by this shuffle, blend it in with an
2866   // additional vrgather.
2867   if (!V2.isUndef()) {
2868     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2869 
2870     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2871     SelectMask =
2872         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2873 
2874     // If only one index is used, we can use a "splat" vrgather.
2875     // TODO: We can splat the most-common index and fix-up any stragglers, if
2876     // that's beneficial.
2877     if (RHSIndexCounts.size() == 1) {
2878       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2879       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2880                            DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask,
2881                            Gather, VL);
2882     } else {
2883       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2884       RHSIndices =
2885           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2886       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices,
2887                            SelectMask, Gather, VL);
2888     }
2889   }
2890 
2891   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2892 }
2893 
2894 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2895   // Support splats for any type. These should type legalize well.
2896   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2897     return true;
2898 
2899   // Only support legal VTs for other shuffles for now.
2900   if (!isTypeLegal(VT))
2901     return false;
2902 
2903   MVT SVT = VT.getSimpleVT();
2904 
2905   bool SwapSources;
2906   int LoSrc, HiSrc;
2907   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2908          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2909 }
2910 
2911 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2912 // the exponent.
2913 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2914   MVT VT = Op.getSimpleValueType();
2915   unsigned EltSize = VT.getScalarSizeInBits();
2916   SDValue Src = Op.getOperand(0);
2917   SDLoc DL(Op);
2918 
2919   // We need a FP type that can represent the value.
2920   // TODO: Use f16 for i8 when possible?
2921   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2922   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2923 
2924   // Legal types should have been checked in the RISCVTargetLowering
2925   // constructor.
2926   // TODO: Splitting may make sense in some cases.
2927   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2928          "Expected legal float type!");
2929 
2930   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2931   // The trailing zero count is equal to log2 of this single bit value.
2932   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2933     SDValue Neg =
2934         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2935     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2936   }
2937 
2938   // We have a legal FP type, convert to it.
2939   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2940   // Bitcast to integer and shift the exponent to the LSB.
2941   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2942   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2943   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2944   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2945                               DAG.getConstant(ShiftAmt, DL, IntVT));
2946   // Truncate back to original type to allow vnsrl.
2947   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2948   // The exponent contains log2 of the value in biased form.
2949   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2950 
2951   // For trailing zeros, we just need to subtract the bias.
2952   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2953     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2954                        DAG.getConstant(ExponentBias, DL, VT));
2955 
2956   // For leading zeros, we need to remove the bias and convert from log2 to
2957   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2958   unsigned Adjust = ExponentBias + (EltSize - 1);
2959   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2960 }
2961 
2962 // While RVV has alignment restrictions, we should always be able to load as a
2963 // legal equivalently-sized byte-typed vector instead. This method is
2964 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2965 // the load is already correctly-aligned, it returns SDValue().
2966 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2967                                                     SelectionDAG &DAG) const {
2968   auto *Load = cast<LoadSDNode>(Op);
2969   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2970 
2971   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2972                                      Load->getMemoryVT(),
2973                                      *Load->getMemOperand()))
2974     return SDValue();
2975 
2976   SDLoc DL(Op);
2977   MVT VT = Op.getSimpleValueType();
2978   unsigned EltSizeBits = VT.getScalarSizeInBits();
2979   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2980          "Unexpected unaligned RVV load type");
2981   MVT NewVT =
2982       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2983   assert(NewVT.isValid() &&
2984          "Expecting equally-sized RVV vector types to be legal");
2985   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2986                           Load->getPointerInfo(), Load->getOriginalAlign(),
2987                           Load->getMemOperand()->getFlags());
2988   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2989 }
2990 
2991 // While RVV has alignment restrictions, we should always be able to store as a
2992 // legal equivalently-sized byte-typed vector instead. This method is
2993 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2994 // returns SDValue() if the store is already correctly aligned.
2995 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2996                                                      SelectionDAG &DAG) const {
2997   auto *Store = cast<StoreSDNode>(Op);
2998   assert(Store && Store->getValue().getValueType().isVector() &&
2999          "Expected vector store");
3000 
3001   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3002                                      Store->getMemoryVT(),
3003                                      *Store->getMemOperand()))
3004     return SDValue();
3005 
3006   SDLoc DL(Op);
3007   SDValue StoredVal = Store->getValue();
3008   MVT VT = StoredVal.getSimpleValueType();
3009   unsigned EltSizeBits = VT.getScalarSizeInBits();
3010   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3011          "Unexpected unaligned RVV store type");
3012   MVT NewVT =
3013       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3014   assert(NewVT.isValid() &&
3015          "Expecting equally-sized RVV vector types to be legal");
3016   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3017   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3018                       Store->getPointerInfo(), Store->getOriginalAlign(),
3019                       Store->getMemOperand()->getFlags());
3020 }
3021 
3022 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
3023                              const RISCVSubtarget &Subtarget) {
3024   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
3025 
3026   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
3027 
3028   // All simm32 constants should be handled by isel.
3029   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
3030   // this check redundant, but small immediates are common so this check
3031   // should have better compile time.
3032   if (isInt<32>(Imm))
3033     return Op;
3034 
3035   // We only need to cost the immediate, if constant pool lowering is enabled.
3036   if (!Subtarget.useConstantPoolForLargeInts())
3037     return Op;
3038 
3039   RISCVMatInt::InstSeq Seq =
3040       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
3041   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
3042     return Op;
3043 
3044   // Expand to a constant pool using the default expansion code.
3045   return SDValue();
3046 }
3047 
3048 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3049                                             SelectionDAG &DAG) const {
3050   switch (Op.getOpcode()) {
3051   default:
3052     report_fatal_error("unimplemented operand");
3053   case ISD::GlobalAddress:
3054     return lowerGlobalAddress(Op, DAG);
3055   case ISD::BlockAddress:
3056     return lowerBlockAddress(Op, DAG);
3057   case ISD::ConstantPool:
3058     return lowerConstantPool(Op, DAG);
3059   case ISD::JumpTable:
3060     return lowerJumpTable(Op, DAG);
3061   case ISD::GlobalTLSAddress:
3062     return lowerGlobalTLSAddress(Op, DAG);
3063   case ISD::Constant:
3064     return lowerConstant(Op, DAG, Subtarget);
3065   case ISD::SELECT:
3066     return lowerSELECT(Op, DAG);
3067   case ISD::BRCOND:
3068     return lowerBRCOND(Op, DAG);
3069   case ISD::VASTART:
3070     return lowerVASTART(Op, DAG);
3071   case ISD::FRAMEADDR:
3072     return lowerFRAMEADDR(Op, DAG);
3073   case ISD::RETURNADDR:
3074     return lowerRETURNADDR(Op, DAG);
3075   case ISD::SHL_PARTS:
3076     return lowerShiftLeftParts(Op, DAG);
3077   case ISD::SRA_PARTS:
3078     return lowerShiftRightParts(Op, DAG, true);
3079   case ISD::SRL_PARTS:
3080     return lowerShiftRightParts(Op, DAG, false);
3081   case ISD::BITCAST: {
3082     SDLoc DL(Op);
3083     EVT VT = Op.getValueType();
3084     SDValue Op0 = Op.getOperand(0);
3085     EVT Op0VT = Op0.getValueType();
3086     MVT XLenVT = Subtarget.getXLenVT();
3087     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3088       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3089       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3090       return FPConv;
3091     }
3092     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3093         Subtarget.hasStdExtF()) {
3094       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3095       SDValue FPConv =
3096           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3097       return FPConv;
3098     }
3099 
3100     // Consider other scalar<->scalar casts as legal if the types are legal.
3101     // Otherwise expand them.
3102     if (!VT.isVector() && !Op0VT.isVector()) {
3103       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3104         return Op;
3105       return SDValue();
3106     }
3107 
3108     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3109            "Unexpected types");
3110 
3111     if (VT.isFixedLengthVector()) {
3112       // We can handle fixed length vector bitcasts with a simple replacement
3113       // in isel.
3114       if (Op0VT.isFixedLengthVector())
3115         return Op;
3116       // When bitcasting from scalar to fixed-length vector, insert the scalar
3117       // into a one-element vector of the result type, and perform a vector
3118       // bitcast.
3119       if (!Op0VT.isVector()) {
3120         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3121         if (!isTypeLegal(BVT))
3122           return SDValue();
3123         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3124                                               DAG.getUNDEF(BVT), Op0,
3125                                               DAG.getConstant(0, DL, XLenVT)));
3126       }
3127       return SDValue();
3128     }
3129     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3130     // thus: bitcast the vector to a one-element vector type whose element type
3131     // is the same as the result type, and extract the first element.
3132     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3133       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3134       if (!isTypeLegal(BVT))
3135         return SDValue();
3136       SDValue BVec = DAG.getBitcast(BVT, Op0);
3137       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3138                          DAG.getConstant(0, DL, XLenVT));
3139     }
3140     return SDValue();
3141   }
3142   case ISD::INTRINSIC_WO_CHAIN:
3143     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3144   case ISD::INTRINSIC_W_CHAIN:
3145     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3146   case ISD::INTRINSIC_VOID:
3147     return LowerINTRINSIC_VOID(Op, DAG);
3148   case ISD::BSWAP:
3149   case ISD::BITREVERSE: {
3150     MVT VT = Op.getSimpleValueType();
3151     SDLoc DL(Op);
3152     if (Subtarget.hasStdExtZbp()) {
3153       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3154       // Start with the maximum immediate value which is the bitwidth - 1.
3155       unsigned Imm = VT.getSizeInBits() - 1;
3156       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3157       if (Op.getOpcode() == ISD::BSWAP)
3158         Imm &= ~0x7U;
3159       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3160                          DAG.getConstant(Imm, DL, VT));
3161     }
3162     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3163     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3164     // Expand bitreverse to a bswap(rev8) followed by brev8.
3165     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3166     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3167     // as brev8 by an isel pattern.
3168     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3169                        DAG.getConstant(7, DL, VT));
3170   }
3171   case ISD::FSHL:
3172   case ISD::FSHR: {
3173     MVT VT = Op.getSimpleValueType();
3174     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3175     SDLoc DL(Op);
3176     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3177     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3178     // accidentally setting the extra bit.
3179     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3180     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3181                                 DAG.getConstant(ShAmtWidth, DL, VT));
3182     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3183     // instruction use different orders. fshl will return its first operand for
3184     // shift of zero, fshr will return its second operand. fsl and fsr both
3185     // return rs1 so the ISD nodes need to have different operand orders.
3186     // Shift amount is in rs2.
3187     SDValue Op0 = Op.getOperand(0);
3188     SDValue Op1 = Op.getOperand(1);
3189     unsigned Opc = RISCVISD::FSL;
3190     if (Op.getOpcode() == ISD::FSHR) {
3191       std::swap(Op0, Op1);
3192       Opc = RISCVISD::FSR;
3193     }
3194     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3195   }
3196   case ISD::TRUNCATE:
3197     // Only custom-lower vector truncates
3198     if (!Op.getSimpleValueType().isVector())
3199       return Op;
3200     return lowerVectorTruncLike(Op, DAG);
3201   case ISD::ANY_EXTEND:
3202   case ISD::ZERO_EXTEND:
3203     if (Op.getOperand(0).getValueType().isVector() &&
3204         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3205       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3206     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3207   case ISD::SIGN_EXTEND:
3208     if (Op.getOperand(0).getValueType().isVector() &&
3209         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3210       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3211     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3212   case ISD::SPLAT_VECTOR_PARTS:
3213     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3214   case ISD::INSERT_VECTOR_ELT:
3215     return lowerINSERT_VECTOR_ELT(Op, DAG);
3216   case ISD::EXTRACT_VECTOR_ELT:
3217     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3218   case ISD::VSCALE: {
3219     MVT VT = Op.getSimpleValueType();
3220     SDLoc DL(Op);
3221     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3222     // We define our scalable vector types for lmul=1 to use a 64 bit known
3223     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3224     // vscale as VLENB / 8.
3225     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3226     if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
3227       report_fatal_error("Support for VLEN==32 is incomplete.");
3228     // We assume VLENB is a multiple of 8. We manually choose the best shift
3229     // here because SimplifyDemandedBits isn't always able to simplify it.
3230     uint64_t Val = Op.getConstantOperandVal(0);
3231     if (isPowerOf2_64(Val)) {
3232       uint64_t Log2 = Log2_64(Val);
3233       if (Log2 < 3)
3234         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3235                            DAG.getConstant(3 - Log2, DL, VT));
3236       if (Log2 > 3)
3237         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3238                            DAG.getConstant(Log2 - 3, DL, VT));
3239       return VLENB;
3240     }
3241     // If the multiplier is a multiple of 8, scale it down to avoid needing
3242     // to shift the VLENB value.
3243     if ((Val % 8) == 0)
3244       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3245                          DAG.getConstant(Val / 8, DL, VT));
3246 
3247     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3248                                  DAG.getConstant(3, DL, VT));
3249     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3250   }
3251   case ISD::FPOWI: {
3252     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3253     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3254     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3255         Op.getOperand(1).getValueType() == MVT::i32) {
3256       SDLoc DL(Op);
3257       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3258       SDValue Powi =
3259           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3260       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3261                          DAG.getIntPtrConstant(0, DL));
3262     }
3263     return SDValue();
3264   }
3265   case ISD::FP_EXTEND:
3266   case ISD::FP_ROUND:
3267     if (!Op.getValueType().isVector())
3268       return Op;
3269     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3270   case ISD::FP_TO_SINT:
3271   case ISD::FP_TO_UINT:
3272   case ISD::SINT_TO_FP:
3273   case ISD::UINT_TO_FP: {
3274     // RVV can only do fp<->int conversions to types half/double the size as
3275     // the source. We custom-lower any conversions that do two hops into
3276     // sequences.
3277     MVT VT = Op.getSimpleValueType();
3278     if (!VT.isVector())
3279       return Op;
3280     SDLoc DL(Op);
3281     SDValue Src = Op.getOperand(0);
3282     MVT EltVT = VT.getVectorElementType();
3283     MVT SrcVT = Src.getSimpleValueType();
3284     MVT SrcEltVT = SrcVT.getVectorElementType();
3285     unsigned EltSize = EltVT.getSizeInBits();
3286     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3287     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3288            "Unexpected vector element types");
3289 
3290     bool IsInt2FP = SrcEltVT.isInteger();
3291     // Widening conversions
3292     if (EltSize > (2 * SrcEltSize)) {
3293       if (IsInt2FP) {
3294         // Do a regular integer sign/zero extension then convert to float.
3295         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3296                                       VT.getVectorElementCount());
3297         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3298                                  ? ISD::ZERO_EXTEND
3299                                  : ISD::SIGN_EXTEND;
3300         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3301         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3302       }
3303       // FP2Int
3304       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3305       // Do one doubling fp_extend then complete the operation by converting
3306       // to int.
3307       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3308       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3309       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3310     }
3311 
3312     // Narrowing conversions
3313     if (SrcEltSize > (2 * EltSize)) {
3314       if (IsInt2FP) {
3315         // One narrowing int_to_fp, then an fp_round.
3316         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3317         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3318         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3319         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3320       }
3321       // FP2Int
3322       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3323       // representable by the integer, the result is poison.
3324       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3325                                     VT.getVectorElementCount());
3326       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3327       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3328     }
3329 
3330     // Scalable vectors can exit here. Patterns will handle equally-sized
3331     // conversions halving/doubling ones.
3332     if (!VT.isFixedLengthVector())
3333       return Op;
3334 
3335     // For fixed-length vectors we lower to a custom "VL" node.
3336     unsigned RVVOpc = 0;
3337     switch (Op.getOpcode()) {
3338     default:
3339       llvm_unreachable("Impossible opcode");
3340     case ISD::FP_TO_SINT:
3341       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3342       break;
3343     case ISD::FP_TO_UINT:
3344       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3345       break;
3346     case ISD::SINT_TO_FP:
3347       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3348       break;
3349     case ISD::UINT_TO_FP:
3350       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3351       break;
3352     }
3353 
3354     MVT ContainerVT, SrcContainerVT;
3355     // Derive the reference container type from the larger vector type.
3356     if (SrcEltSize > EltSize) {
3357       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3358       ContainerVT =
3359           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3360     } else {
3361       ContainerVT = getContainerForFixedLengthVector(VT);
3362       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3363     }
3364 
3365     SDValue Mask, VL;
3366     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3367 
3368     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3369     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3370     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3371   }
3372   case ISD::FP_TO_SINT_SAT:
3373   case ISD::FP_TO_UINT_SAT:
3374     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3375   case ISD::FTRUNC:
3376   case ISD::FCEIL:
3377   case ISD::FFLOOR:
3378     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3379   case ISD::FROUND:
3380     return lowerFROUND(Op, DAG);
3381   case ISD::VECREDUCE_ADD:
3382   case ISD::VECREDUCE_UMAX:
3383   case ISD::VECREDUCE_SMAX:
3384   case ISD::VECREDUCE_UMIN:
3385   case ISD::VECREDUCE_SMIN:
3386     return lowerVECREDUCE(Op, DAG);
3387   case ISD::VECREDUCE_AND:
3388   case ISD::VECREDUCE_OR:
3389   case ISD::VECREDUCE_XOR:
3390     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3391       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3392     return lowerVECREDUCE(Op, DAG);
3393   case ISD::VECREDUCE_FADD:
3394   case ISD::VECREDUCE_SEQ_FADD:
3395   case ISD::VECREDUCE_FMIN:
3396   case ISD::VECREDUCE_FMAX:
3397     return lowerFPVECREDUCE(Op, DAG);
3398   case ISD::VP_REDUCE_ADD:
3399   case ISD::VP_REDUCE_UMAX:
3400   case ISD::VP_REDUCE_SMAX:
3401   case ISD::VP_REDUCE_UMIN:
3402   case ISD::VP_REDUCE_SMIN:
3403   case ISD::VP_REDUCE_FADD:
3404   case ISD::VP_REDUCE_SEQ_FADD:
3405   case ISD::VP_REDUCE_FMIN:
3406   case ISD::VP_REDUCE_FMAX:
3407     return lowerVPREDUCE(Op, DAG);
3408   case ISD::VP_REDUCE_AND:
3409   case ISD::VP_REDUCE_OR:
3410   case ISD::VP_REDUCE_XOR:
3411     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3412       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3413     return lowerVPREDUCE(Op, DAG);
3414   case ISD::INSERT_SUBVECTOR:
3415     return lowerINSERT_SUBVECTOR(Op, DAG);
3416   case ISD::EXTRACT_SUBVECTOR:
3417     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3418   case ISD::STEP_VECTOR:
3419     return lowerSTEP_VECTOR(Op, DAG);
3420   case ISD::VECTOR_REVERSE:
3421     return lowerVECTOR_REVERSE(Op, DAG);
3422   case ISD::VECTOR_SPLICE:
3423     return lowerVECTOR_SPLICE(Op, DAG);
3424   case ISD::BUILD_VECTOR:
3425     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3426   case ISD::SPLAT_VECTOR:
3427     if (Op.getValueType().getVectorElementType() == MVT::i1)
3428       return lowerVectorMaskSplat(Op, DAG);
3429     return SDValue();
3430   case ISD::VECTOR_SHUFFLE:
3431     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3432   case ISD::CONCAT_VECTORS: {
3433     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3434     // better than going through the stack, as the default expansion does.
3435     SDLoc DL(Op);
3436     MVT VT = Op.getSimpleValueType();
3437     unsigned NumOpElts =
3438         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3439     SDValue Vec = DAG.getUNDEF(VT);
3440     for (const auto &OpIdx : enumerate(Op->ops())) {
3441       SDValue SubVec = OpIdx.value();
3442       // Don't insert undef subvectors.
3443       if (SubVec.isUndef())
3444         continue;
3445       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3446                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3447     }
3448     return Vec;
3449   }
3450   case ISD::LOAD:
3451     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3452       return V;
3453     if (Op.getValueType().isFixedLengthVector())
3454       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3455     return Op;
3456   case ISD::STORE:
3457     if (auto V = expandUnalignedRVVStore(Op, DAG))
3458       return V;
3459     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3460       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3461     return Op;
3462   case ISD::MLOAD:
3463   case ISD::VP_LOAD:
3464     return lowerMaskedLoad(Op, DAG);
3465   case ISD::MSTORE:
3466   case ISD::VP_STORE:
3467     return lowerMaskedStore(Op, DAG);
3468   case ISD::SETCC:
3469     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3470   case ISD::ADD:
3471     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3472   case ISD::SUB:
3473     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3474   case ISD::MUL:
3475     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3476   case ISD::MULHS:
3477     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3478   case ISD::MULHU:
3479     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3480   case ISD::AND:
3481     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3482                                               RISCVISD::AND_VL);
3483   case ISD::OR:
3484     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3485                                               RISCVISD::OR_VL);
3486   case ISD::XOR:
3487     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3488                                               RISCVISD::XOR_VL);
3489   case ISD::SDIV:
3490     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3491   case ISD::SREM:
3492     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3493   case ISD::UDIV:
3494     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3495   case ISD::UREM:
3496     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3497   case ISD::SHL:
3498   case ISD::SRA:
3499   case ISD::SRL:
3500     if (Op.getSimpleValueType().isFixedLengthVector())
3501       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3502     // This can be called for an i32 shift amount that needs to be promoted.
3503     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3504            "Unexpected custom legalisation");
3505     return SDValue();
3506   case ISD::SADDSAT:
3507     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3508   case ISD::UADDSAT:
3509     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3510   case ISD::SSUBSAT:
3511     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3512   case ISD::USUBSAT:
3513     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3514   case ISD::FADD:
3515     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3516   case ISD::FSUB:
3517     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3518   case ISD::FMUL:
3519     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3520   case ISD::FDIV:
3521     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3522   case ISD::FNEG:
3523     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3524   case ISD::FABS:
3525     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3526   case ISD::FSQRT:
3527     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3528   case ISD::FMA:
3529     return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL);
3530   case ISD::SMIN:
3531     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3532   case ISD::SMAX:
3533     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3534   case ISD::UMIN:
3535     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3536   case ISD::UMAX:
3537     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3538   case ISD::FMINNUM:
3539     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3540   case ISD::FMAXNUM:
3541     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3542   case ISD::ABS:
3543     return lowerABS(Op, DAG);
3544   case ISD::CTLZ_ZERO_UNDEF:
3545   case ISD::CTTZ_ZERO_UNDEF:
3546     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3547   case ISD::VSELECT:
3548     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3549   case ISD::FCOPYSIGN:
3550     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3551   case ISD::MGATHER:
3552   case ISD::VP_GATHER:
3553     return lowerMaskedGather(Op, DAG);
3554   case ISD::MSCATTER:
3555   case ISD::VP_SCATTER:
3556     return lowerMaskedScatter(Op, DAG);
3557   case ISD::FLT_ROUNDS_:
3558     return lowerGET_ROUNDING(Op, DAG);
3559   case ISD::SET_ROUNDING:
3560     return lowerSET_ROUNDING(Op, DAG);
3561   case ISD::EH_DWARF_CFA:
3562     return lowerEH_DWARF_CFA(Op, DAG);
3563   case ISD::VP_SELECT:
3564     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3565   case ISD::VP_MERGE:
3566     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3567   case ISD::VP_ADD:
3568     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3569   case ISD::VP_SUB:
3570     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3571   case ISD::VP_MUL:
3572     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3573   case ISD::VP_SDIV:
3574     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3575   case ISD::VP_UDIV:
3576     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3577   case ISD::VP_SREM:
3578     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3579   case ISD::VP_UREM:
3580     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3581   case ISD::VP_AND:
3582     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3583   case ISD::VP_OR:
3584     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3585   case ISD::VP_XOR:
3586     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3587   case ISD::VP_ASHR:
3588     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3589   case ISD::VP_LSHR:
3590     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3591   case ISD::VP_SHL:
3592     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3593   case ISD::VP_FADD:
3594     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3595   case ISD::VP_FSUB:
3596     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3597   case ISD::VP_FMUL:
3598     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3599   case ISD::VP_FDIV:
3600     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3601   case ISD::VP_FNEG:
3602     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3603   case ISD::VP_FMA:
3604     return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL);
3605   case ISD::VP_SIGN_EXTEND:
3606   case ISD::VP_ZERO_EXTEND:
3607     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3608       return lowerVPExtMaskOp(Op, DAG);
3609     return lowerVPOp(Op, DAG,
3610                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3611                          ? RISCVISD::VSEXT_VL
3612                          : RISCVISD::VZEXT_VL);
3613   case ISD::VP_TRUNCATE:
3614     return lowerVectorTruncLike(Op, DAG);
3615   case ISD::VP_FP_EXTEND:
3616   case ISD::VP_FP_ROUND:
3617     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3618   case ISD::VP_FPTOSI:
3619     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3620   case ISD::VP_FPTOUI:
3621     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3622   case ISD::VP_SITOFP:
3623     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3624   case ISD::VP_UITOFP:
3625     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3626   case ISD::VP_SETCC:
3627     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3628       return lowerVPSetCCMaskOp(Op, DAG);
3629     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3630   }
3631 }
3632 
3633 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3634                              SelectionDAG &DAG, unsigned Flags) {
3635   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3636 }
3637 
3638 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3639                              SelectionDAG &DAG, unsigned Flags) {
3640   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3641                                    Flags);
3642 }
3643 
3644 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3645                              SelectionDAG &DAG, unsigned Flags) {
3646   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3647                                    N->getOffset(), Flags);
3648 }
3649 
3650 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3651                              SelectionDAG &DAG, unsigned Flags) {
3652   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3653 }
3654 
3655 template <class NodeTy>
3656 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3657                                      bool IsLocal) const {
3658   SDLoc DL(N);
3659   EVT Ty = getPointerTy(DAG.getDataLayout());
3660 
3661   if (isPositionIndependent()) {
3662     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3663     if (IsLocal)
3664       // Use PC-relative addressing to access the symbol. This generates the
3665       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3666       // %pcrel_lo(auipc)).
3667       return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3668 
3669     // Use PC-relative addressing to access the GOT for this symbol, then load
3670     // the address from the GOT. This generates the pattern (PseudoLA sym),
3671     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3672     MachineFunction &MF = DAG.getMachineFunction();
3673     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3674         MachinePointerInfo::getGOT(MF),
3675         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3676             MachineMemOperand::MOInvariant,
3677         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3678     SDValue Load =
3679         DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other),
3680                                 {DAG.getEntryNode(), Addr}, Ty, MemOp);
3681     return Load;
3682   }
3683 
3684   switch (getTargetMachine().getCodeModel()) {
3685   default:
3686     report_fatal_error("Unsupported code model for lowering");
3687   case CodeModel::Small: {
3688     // Generate a sequence for accessing addresses within the first 2 GiB of
3689     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3690     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3691     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3692     SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3693     return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
3694   }
3695   case CodeModel::Medium: {
3696     // Generate a sequence for accessing addresses within any 2GiB range within
3697     // the address space. This generates the pattern (PseudoLLA sym), which
3698     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3699     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3700     return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3701   }
3702   }
3703 }
3704 
3705 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3706                                                 SelectionDAG &DAG) const {
3707   SDLoc DL(Op);
3708   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3709   assert(N->getOffset() == 0 && "unexpected offset in global node");
3710 
3711   const GlobalValue *GV = N->getGlobal();
3712   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3713   return getAddr(N, DAG, IsLocal);
3714 }
3715 
3716 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3717                                                SelectionDAG &DAG) const {
3718   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3719 
3720   return getAddr(N, DAG);
3721 }
3722 
3723 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3724                                                SelectionDAG &DAG) const {
3725   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3726 
3727   return getAddr(N, DAG);
3728 }
3729 
3730 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3731                                             SelectionDAG &DAG) const {
3732   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3733 
3734   return getAddr(N, DAG);
3735 }
3736 
3737 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3738                                               SelectionDAG &DAG,
3739                                               bool UseGOT) const {
3740   SDLoc DL(N);
3741   EVT Ty = getPointerTy(DAG.getDataLayout());
3742   const GlobalValue *GV = N->getGlobal();
3743   MVT XLenVT = Subtarget.getXLenVT();
3744 
3745   if (UseGOT) {
3746     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3747     // load the address from the GOT and add the thread pointer. This generates
3748     // the pattern (PseudoLA_TLS_IE sym), which expands to
3749     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3750     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3751     MachineFunction &MF = DAG.getMachineFunction();
3752     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3753         MachinePointerInfo::getGOT(MF),
3754         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3755             MachineMemOperand::MOInvariant,
3756         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3757     SDValue Load = DAG.getMemIntrinsicNode(
3758         RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other),
3759         {DAG.getEntryNode(), Addr}, Ty, MemOp);
3760 
3761     // Add the thread pointer.
3762     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3763     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3764   }
3765 
3766   // Generate a sequence for accessing the address relative to the thread
3767   // pointer, with the appropriate adjustment for the thread pointer offset.
3768   // This generates the pattern
3769   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3770   SDValue AddrHi =
3771       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3772   SDValue AddrAdd =
3773       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3774   SDValue AddrLo =
3775       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3776 
3777   SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3778   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3779   SDValue MNAdd =
3780       DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
3781   return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
3782 }
3783 
3784 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3785                                                SelectionDAG &DAG) const {
3786   SDLoc DL(N);
3787   EVT Ty = getPointerTy(DAG.getDataLayout());
3788   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3789   const GlobalValue *GV = N->getGlobal();
3790 
3791   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3792   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3793   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3794   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3795   SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr);
3796 
3797   // Prepare argument list to generate call.
3798   ArgListTy Args;
3799   ArgListEntry Entry;
3800   Entry.Node = Load;
3801   Entry.Ty = CallTy;
3802   Args.push_back(Entry);
3803 
3804   // Setup call to __tls_get_addr.
3805   TargetLowering::CallLoweringInfo CLI(DAG);
3806   CLI.setDebugLoc(DL)
3807       .setChain(DAG.getEntryNode())
3808       .setLibCallee(CallingConv::C, CallTy,
3809                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3810                     std::move(Args));
3811 
3812   return LowerCallTo(CLI).first;
3813 }
3814 
3815 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3816                                                    SelectionDAG &DAG) const {
3817   SDLoc DL(Op);
3818   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3819   assert(N->getOffset() == 0 && "unexpected offset in global node");
3820 
3821   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3822 
3823   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3824       CallingConv::GHC)
3825     report_fatal_error("In GHC calling convention TLS is not supported");
3826 
3827   SDValue Addr;
3828   switch (Model) {
3829   case TLSModel::LocalExec:
3830     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3831     break;
3832   case TLSModel::InitialExec:
3833     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3834     break;
3835   case TLSModel::LocalDynamic:
3836   case TLSModel::GeneralDynamic:
3837     Addr = getDynamicTLSAddr(N, DAG);
3838     break;
3839   }
3840 
3841   return Addr;
3842 }
3843 
3844 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3845   SDValue CondV = Op.getOperand(0);
3846   SDValue TrueV = Op.getOperand(1);
3847   SDValue FalseV = Op.getOperand(2);
3848   SDLoc DL(Op);
3849   MVT VT = Op.getSimpleValueType();
3850   MVT XLenVT = Subtarget.getXLenVT();
3851 
3852   // Lower vector SELECTs to VSELECTs by splatting the condition.
3853   if (VT.isVector()) {
3854     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3855     SDValue CondSplat = VT.isScalableVector()
3856                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3857                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3858     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3859   }
3860 
3861   // If the result type is XLenVT and CondV is the output of a SETCC node
3862   // which also operated on XLenVT inputs, then merge the SETCC node into the
3863   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3864   // compare+branch instructions. i.e.:
3865   // (select (setcc lhs, rhs, cc), truev, falsev)
3866   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3867   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3868       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3869     SDValue LHS = CondV.getOperand(0);
3870     SDValue RHS = CondV.getOperand(1);
3871     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3872     ISD::CondCode CCVal = CC->get();
3873 
3874     // Special case for a select of 2 constants that have a diffence of 1.
3875     // Normally this is done by DAGCombine, but if the select is introduced by
3876     // type legalization or op legalization, we miss it. Restricting to SETLT
3877     // case for now because that is what signed saturating add/sub need.
3878     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3879     // but we would probably want to swap the true/false values if the condition
3880     // is SETGE/SETLE to avoid an XORI.
3881     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3882         CCVal == ISD::SETLT) {
3883       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3884       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3885       if (TrueVal - 1 == FalseVal)
3886         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3887       if (TrueVal + 1 == FalseVal)
3888         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3889     }
3890 
3891     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3892 
3893     SDValue TargetCC = DAG.getCondCode(CCVal);
3894     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3895     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3896   }
3897 
3898   // Otherwise:
3899   // (select condv, truev, falsev)
3900   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3901   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3902   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3903 
3904   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3905 
3906   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3907 }
3908 
3909 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3910   SDValue CondV = Op.getOperand(1);
3911   SDLoc DL(Op);
3912   MVT XLenVT = Subtarget.getXLenVT();
3913 
3914   if (CondV.getOpcode() == ISD::SETCC &&
3915       CondV.getOperand(0).getValueType() == XLenVT) {
3916     SDValue LHS = CondV.getOperand(0);
3917     SDValue RHS = CondV.getOperand(1);
3918     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3919 
3920     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3921 
3922     SDValue TargetCC = DAG.getCondCode(CCVal);
3923     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3924                        LHS, RHS, TargetCC, Op.getOperand(2));
3925   }
3926 
3927   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3928                      CondV, DAG.getConstant(0, DL, XLenVT),
3929                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3930 }
3931 
3932 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3933   MachineFunction &MF = DAG.getMachineFunction();
3934   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3935 
3936   SDLoc DL(Op);
3937   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3938                                  getPointerTy(MF.getDataLayout()));
3939 
3940   // vastart just stores the address of the VarArgsFrameIndex slot into the
3941   // memory location argument.
3942   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3943   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3944                       MachinePointerInfo(SV));
3945 }
3946 
3947 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3948                                             SelectionDAG &DAG) const {
3949   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3950   MachineFunction &MF = DAG.getMachineFunction();
3951   MachineFrameInfo &MFI = MF.getFrameInfo();
3952   MFI.setFrameAddressIsTaken(true);
3953   Register FrameReg = RI.getFrameRegister(MF);
3954   int XLenInBytes = Subtarget.getXLen() / 8;
3955 
3956   EVT VT = Op.getValueType();
3957   SDLoc DL(Op);
3958   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3959   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3960   while (Depth--) {
3961     int Offset = -(XLenInBytes * 2);
3962     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3963                               DAG.getIntPtrConstant(Offset, DL));
3964     FrameAddr =
3965         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3966   }
3967   return FrameAddr;
3968 }
3969 
3970 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3971                                              SelectionDAG &DAG) const {
3972   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3973   MachineFunction &MF = DAG.getMachineFunction();
3974   MachineFrameInfo &MFI = MF.getFrameInfo();
3975   MFI.setReturnAddressIsTaken(true);
3976   MVT XLenVT = Subtarget.getXLenVT();
3977   int XLenInBytes = Subtarget.getXLen() / 8;
3978 
3979   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3980     return SDValue();
3981 
3982   EVT VT = Op.getValueType();
3983   SDLoc DL(Op);
3984   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3985   if (Depth) {
3986     int Off = -XLenInBytes;
3987     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3988     SDValue Offset = DAG.getConstant(Off, DL, VT);
3989     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3990                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3991                        MachinePointerInfo());
3992   }
3993 
3994   // Return the value of the return address register, marking it an implicit
3995   // live-in.
3996   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3997   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3998 }
3999 
4000 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4001                                                  SelectionDAG &DAG) const {
4002   SDLoc DL(Op);
4003   SDValue Lo = Op.getOperand(0);
4004   SDValue Hi = Op.getOperand(1);
4005   SDValue Shamt = Op.getOperand(2);
4006   EVT VT = Lo.getValueType();
4007 
4008   // if Shamt-XLEN < 0: // Shamt < XLEN
4009   //   Lo = Lo << Shamt
4010   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4011   // else:
4012   //   Lo = 0
4013   //   Hi = Lo << (Shamt-XLEN)
4014 
4015   SDValue Zero = DAG.getConstant(0, DL, VT);
4016   SDValue One = DAG.getConstant(1, DL, VT);
4017   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4018   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4019   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4020   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4021 
4022   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4023   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4024   SDValue ShiftRightLo =
4025       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4026   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4027   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4028   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4029 
4030   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4031 
4032   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4033   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4034 
4035   SDValue Parts[2] = {Lo, Hi};
4036   return DAG.getMergeValues(Parts, DL);
4037 }
4038 
4039 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4040                                                   bool IsSRA) const {
4041   SDLoc DL(Op);
4042   SDValue Lo = Op.getOperand(0);
4043   SDValue Hi = Op.getOperand(1);
4044   SDValue Shamt = Op.getOperand(2);
4045   EVT VT = Lo.getValueType();
4046 
4047   // SRA expansion:
4048   //   if Shamt-XLEN < 0: // Shamt < XLEN
4049   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4050   //     Hi = Hi >>s Shamt
4051   //   else:
4052   //     Lo = Hi >>s (Shamt-XLEN);
4053   //     Hi = Hi >>s (XLEN-1)
4054   //
4055   // SRL expansion:
4056   //   if Shamt-XLEN < 0: // Shamt < XLEN
4057   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4058   //     Hi = Hi >>u Shamt
4059   //   else:
4060   //     Lo = Hi >>u (Shamt-XLEN);
4061   //     Hi = 0;
4062 
4063   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4064 
4065   SDValue Zero = DAG.getConstant(0, DL, VT);
4066   SDValue One = DAG.getConstant(1, DL, VT);
4067   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4068   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4069   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4070   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4071 
4072   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4073   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4074   SDValue ShiftLeftHi =
4075       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4076   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4077   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4078   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4079   SDValue HiFalse =
4080       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4081 
4082   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4083 
4084   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4085   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4086 
4087   SDValue Parts[2] = {Lo, Hi};
4088   return DAG.getMergeValues(Parts, DL);
4089 }
4090 
4091 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4092 // legal equivalently-sized i8 type, so we can use that as a go-between.
4093 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4094                                                   SelectionDAG &DAG) const {
4095   SDLoc DL(Op);
4096   MVT VT = Op.getSimpleValueType();
4097   SDValue SplatVal = Op.getOperand(0);
4098   // All-zeros or all-ones splats are handled specially.
4099   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4100     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4101     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4102   }
4103   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4104     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4105     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4106   }
4107   MVT XLenVT = Subtarget.getXLenVT();
4108   assert(SplatVal.getValueType() == XLenVT &&
4109          "Unexpected type for i1 splat value");
4110   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4111   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4112                          DAG.getConstant(1, DL, XLenVT));
4113   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4114   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4115   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4116 }
4117 
4118 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4119 // illegal (currently only vXi64 RV32).
4120 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4121 // them to VMV_V_X_VL.
4122 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4123                                                      SelectionDAG &DAG) const {
4124   SDLoc DL(Op);
4125   MVT VecVT = Op.getSimpleValueType();
4126   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4127          "Unexpected SPLAT_VECTOR_PARTS lowering");
4128 
4129   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4130   SDValue Lo = Op.getOperand(0);
4131   SDValue Hi = Op.getOperand(1);
4132 
4133   if (VecVT.isFixedLengthVector()) {
4134     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4135     SDLoc DL(Op);
4136     SDValue Mask, VL;
4137     std::tie(Mask, VL) =
4138         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4139 
4140     SDValue Res =
4141         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4142     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4143   }
4144 
4145   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4146     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4147     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4148     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4149     // node in order to try and match RVV vector/scalar instructions.
4150     if ((LoC >> 31) == HiC)
4151       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4152                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4153   }
4154 
4155   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4156   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4157       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4158       Hi.getConstantOperandVal(1) == 31)
4159     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4160                        DAG.getRegister(RISCV::X0, MVT::i32));
4161 
4162   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4163   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4164                      DAG.getUNDEF(VecVT), Lo, Hi,
4165                      DAG.getRegister(RISCV::X0, MVT::i32));
4166 }
4167 
4168 // Custom-lower extensions from mask vectors by using a vselect either with 1
4169 // for zero/any-extension or -1 for sign-extension:
4170 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4171 // Note that any-extension is lowered identically to zero-extension.
4172 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4173                                                 int64_t ExtTrueVal) const {
4174   SDLoc DL(Op);
4175   MVT VecVT = Op.getSimpleValueType();
4176   SDValue Src = Op.getOperand(0);
4177   // Only custom-lower extensions from mask types
4178   assert(Src.getValueType().isVector() &&
4179          Src.getValueType().getVectorElementType() == MVT::i1);
4180 
4181   if (VecVT.isScalableVector()) {
4182     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4183     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4184     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4185   }
4186 
4187   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4188   MVT I1ContainerVT =
4189       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4190 
4191   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4192 
4193   SDValue Mask, VL;
4194   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4195 
4196   MVT XLenVT = Subtarget.getXLenVT();
4197   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4198   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4199 
4200   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4201                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4202   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4203                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4204   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4205                                SplatTrueVal, SplatZero, VL);
4206 
4207   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4208 }
4209 
4210 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4211     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4212   MVT ExtVT = Op.getSimpleValueType();
4213   // Only custom-lower extensions from fixed-length vector types.
4214   if (!ExtVT.isFixedLengthVector())
4215     return Op;
4216   MVT VT = Op.getOperand(0).getSimpleValueType();
4217   // Grab the canonical container type for the extended type. Infer the smaller
4218   // type from that to ensure the same number of vector elements, as we know
4219   // the LMUL will be sufficient to hold the smaller type.
4220   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4221   // Get the extended container type manually to ensure the same number of
4222   // vector elements between source and dest.
4223   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4224                                      ContainerExtVT.getVectorElementCount());
4225 
4226   SDValue Op1 =
4227       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4228 
4229   SDLoc DL(Op);
4230   SDValue Mask, VL;
4231   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4232 
4233   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4234 
4235   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4236 }
4237 
4238 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4239 // setcc operation:
4240 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4241 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4242                                                       SelectionDAG &DAG) const {
4243   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4244   SDLoc DL(Op);
4245   EVT MaskVT = Op.getValueType();
4246   // Only expect to custom-lower truncations to mask types
4247   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4248          "Unexpected type for vector mask lowering");
4249   SDValue Src = Op.getOperand(0);
4250   MVT VecVT = Src.getSimpleValueType();
4251   SDValue Mask, VL;
4252   if (IsVPTrunc) {
4253     Mask = Op.getOperand(1);
4254     VL = Op.getOperand(2);
4255   }
4256   // If this is a fixed vector, we need to convert it to a scalable vector.
4257   MVT ContainerVT = VecVT;
4258 
4259   if (VecVT.isFixedLengthVector()) {
4260     ContainerVT = getContainerForFixedLengthVector(VecVT);
4261     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4262     if (IsVPTrunc) {
4263       MVT MaskContainerVT =
4264           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4265       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4266     }
4267   }
4268 
4269   if (!IsVPTrunc) {
4270     std::tie(Mask, VL) =
4271         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4272   }
4273 
4274   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4275   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4276 
4277   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4278                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4279   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4280                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4281 
4282   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4283   SDValue Trunc =
4284       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4285   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4286                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4287   if (MaskVT.isFixedLengthVector())
4288     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4289   return Trunc;
4290 }
4291 
4292 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4293                                                   SelectionDAG &DAG) const {
4294   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4295   SDLoc DL(Op);
4296 
4297   MVT VT = Op.getSimpleValueType();
4298   // Only custom-lower vector truncates
4299   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4300 
4301   // Truncates to mask types are handled differently
4302   if (VT.getVectorElementType() == MVT::i1)
4303     return lowerVectorMaskTruncLike(Op, DAG);
4304 
4305   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4306   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4307   // truncate by one power of two at a time.
4308   MVT DstEltVT = VT.getVectorElementType();
4309 
4310   SDValue Src = Op.getOperand(0);
4311   MVT SrcVT = Src.getSimpleValueType();
4312   MVT SrcEltVT = SrcVT.getVectorElementType();
4313 
4314   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4315          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4316          "Unexpected vector truncate lowering");
4317 
4318   MVT ContainerVT = SrcVT;
4319   SDValue Mask, VL;
4320   if (IsVPTrunc) {
4321     Mask = Op.getOperand(1);
4322     VL = Op.getOperand(2);
4323   }
4324   if (SrcVT.isFixedLengthVector()) {
4325     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4326     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4327     if (IsVPTrunc) {
4328       MVT MaskVT = getMaskTypeFor(ContainerVT);
4329       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4330     }
4331   }
4332 
4333   SDValue Result = Src;
4334   if (!IsVPTrunc) {
4335     std::tie(Mask, VL) =
4336         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4337   }
4338 
4339   LLVMContext &Context = *DAG.getContext();
4340   const ElementCount Count = ContainerVT.getVectorElementCount();
4341   do {
4342     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4343     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4344     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4345                          Mask, VL);
4346   } while (SrcEltVT != DstEltVT);
4347 
4348   if (SrcVT.isFixedLengthVector())
4349     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4350 
4351   return Result;
4352 }
4353 
4354 SDValue
4355 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4356                                                     SelectionDAG &DAG) const {
4357   bool IsVP =
4358       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4359   bool IsExtend =
4360       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4361   // RVV can only do truncate fp to types half the size as the source. We
4362   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4363   // conversion instruction.
4364   SDLoc DL(Op);
4365   MVT VT = Op.getSimpleValueType();
4366 
4367   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4368 
4369   SDValue Src = Op.getOperand(0);
4370   MVT SrcVT = Src.getSimpleValueType();
4371 
4372   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4373                                      SrcVT.getVectorElementType() != MVT::f16);
4374   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4375                                      SrcVT.getVectorElementType() != MVT::f64);
4376 
4377   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4378 
4379   // Prepare any fixed-length vector operands.
4380   MVT ContainerVT = VT;
4381   SDValue Mask, VL;
4382   if (IsVP) {
4383     Mask = Op.getOperand(1);
4384     VL = Op.getOperand(2);
4385   }
4386   if (VT.isFixedLengthVector()) {
4387     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4388     ContainerVT =
4389         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4390     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4391     if (IsVP) {
4392       MVT MaskVT = getMaskTypeFor(ContainerVT);
4393       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4394     }
4395   }
4396 
4397   if (!IsVP)
4398     std::tie(Mask, VL) =
4399         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4400 
4401   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4402 
4403   if (IsDirectConv) {
4404     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4405     if (VT.isFixedLengthVector())
4406       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4407     return Src;
4408   }
4409 
4410   unsigned InterConvOpc =
4411       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4412 
4413   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4414   SDValue IntermediateConv =
4415       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4416   SDValue Result =
4417       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4418   if (VT.isFixedLengthVector())
4419     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4420   return Result;
4421 }
4422 
4423 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4424 // first position of a vector, and that vector is slid up to the insert index.
4425 // By limiting the active vector length to index+1 and merging with the
4426 // original vector (with an undisturbed tail policy for elements >= VL), we
4427 // achieve the desired result of leaving all elements untouched except the one
4428 // at VL-1, which is replaced with the desired value.
4429 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4430                                                     SelectionDAG &DAG) const {
4431   SDLoc DL(Op);
4432   MVT VecVT = Op.getSimpleValueType();
4433   SDValue Vec = Op.getOperand(0);
4434   SDValue Val = Op.getOperand(1);
4435   SDValue Idx = Op.getOperand(2);
4436 
4437   if (VecVT.getVectorElementType() == MVT::i1) {
4438     // FIXME: For now we just promote to an i8 vector and insert into that,
4439     // but this is probably not optimal.
4440     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4441     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4442     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4443     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4444   }
4445 
4446   MVT ContainerVT = VecVT;
4447   // If the operand is a fixed-length vector, convert to a scalable one.
4448   if (VecVT.isFixedLengthVector()) {
4449     ContainerVT = getContainerForFixedLengthVector(VecVT);
4450     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4451   }
4452 
4453   MVT XLenVT = Subtarget.getXLenVT();
4454 
4455   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4456   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4457   // Even i64-element vectors on RV32 can be lowered without scalar
4458   // legalization if the most-significant 32 bits of the value are not affected
4459   // by the sign-extension of the lower 32 bits.
4460   // TODO: We could also catch sign extensions of a 32-bit value.
4461   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4462     const auto *CVal = cast<ConstantSDNode>(Val);
4463     if (isInt<32>(CVal->getSExtValue())) {
4464       IsLegalInsert = true;
4465       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4466     }
4467   }
4468 
4469   SDValue Mask, VL;
4470   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4471 
4472   SDValue ValInVec;
4473 
4474   if (IsLegalInsert) {
4475     unsigned Opc =
4476         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4477     if (isNullConstant(Idx)) {
4478       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4479       if (!VecVT.isFixedLengthVector())
4480         return Vec;
4481       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4482     }
4483     ValInVec =
4484         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4485   } else {
4486     // On RV32, i64-element vectors must be specially handled to place the
4487     // value at element 0, by using two vslide1up instructions in sequence on
4488     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4489     // this.
4490     SDValue One = DAG.getConstant(1, DL, XLenVT);
4491     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4492     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4493     MVT I32ContainerVT =
4494         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4495     SDValue I32Mask =
4496         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4497     // Limit the active VL to two.
4498     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4499     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4500     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4501     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4502                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4503     // First slide in the hi value, then the lo in underneath it.
4504     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4505                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4506                            I32Mask, InsertI64VL);
4507     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4508                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4509                            I32Mask, InsertI64VL);
4510     // Bitcast back to the right container type.
4511     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4512   }
4513 
4514   // Now that the value is in a vector, slide it into position.
4515   SDValue InsertVL =
4516       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4517   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4518                                 ValInVec, Idx, Mask, InsertVL);
4519   if (!VecVT.isFixedLengthVector())
4520     return Slideup;
4521   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4522 }
4523 
4524 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4525 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4526 // types this is done using VMV_X_S to allow us to glean information about the
4527 // sign bits of the result.
4528 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4529                                                      SelectionDAG &DAG) const {
4530   SDLoc DL(Op);
4531   SDValue Idx = Op.getOperand(1);
4532   SDValue Vec = Op.getOperand(0);
4533   EVT EltVT = Op.getValueType();
4534   MVT VecVT = Vec.getSimpleValueType();
4535   MVT XLenVT = Subtarget.getXLenVT();
4536 
4537   if (VecVT.getVectorElementType() == MVT::i1) {
4538     if (VecVT.isFixedLengthVector()) {
4539       unsigned NumElts = VecVT.getVectorNumElements();
4540       if (NumElts >= 8) {
4541         MVT WideEltVT;
4542         unsigned WidenVecLen;
4543         SDValue ExtractElementIdx;
4544         SDValue ExtractBitIdx;
4545         unsigned MaxEEW = Subtarget.getELEN();
4546         MVT LargestEltVT = MVT::getIntegerVT(
4547             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4548         if (NumElts <= LargestEltVT.getSizeInBits()) {
4549           assert(isPowerOf2_32(NumElts) &&
4550                  "the number of elements should be power of 2");
4551           WideEltVT = MVT::getIntegerVT(NumElts);
4552           WidenVecLen = 1;
4553           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4554           ExtractBitIdx = Idx;
4555         } else {
4556           WideEltVT = LargestEltVT;
4557           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4558           // extract element index = index / element width
4559           ExtractElementIdx = DAG.getNode(
4560               ISD::SRL, DL, XLenVT, Idx,
4561               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4562           // mask bit index = index % element width
4563           ExtractBitIdx = DAG.getNode(
4564               ISD::AND, DL, XLenVT, Idx,
4565               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4566         }
4567         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4568         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4569         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4570                                          Vec, ExtractElementIdx);
4571         // Extract the bit from GPR.
4572         SDValue ShiftRight =
4573             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4574         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4575                            DAG.getConstant(1, DL, XLenVT));
4576       }
4577     }
4578     // Otherwise, promote to an i8 vector and extract from that.
4579     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4580     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4581     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4582   }
4583 
4584   // If this is a fixed vector, we need to convert it to a scalable vector.
4585   MVT ContainerVT = VecVT;
4586   if (VecVT.isFixedLengthVector()) {
4587     ContainerVT = getContainerForFixedLengthVector(VecVT);
4588     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4589   }
4590 
4591   // If the index is 0, the vector is already in the right position.
4592   if (!isNullConstant(Idx)) {
4593     // Use a VL of 1 to avoid processing more elements than we need.
4594     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4595     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4596     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4597                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4598   }
4599 
4600   if (!EltVT.isInteger()) {
4601     // Floating-point extracts are handled in TableGen.
4602     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4603                        DAG.getConstant(0, DL, XLenVT));
4604   }
4605 
4606   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4607   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4608 }
4609 
4610 // Some RVV intrinsics may claim that they want an integer operand to be
4611 // promoted or expanded.
4612 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4613                                            const RISCVSubtarget &Subtarget) {
4614   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4615           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4616          "Unexpected opcode");
4617 
4618   if (!Subtarget.hasVInstructions())
4619     return SDValue();
4620 
4621   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4622   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4623   SDLoc DL(Op);
4624 
4625   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4626       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4627   if (!II || !II->hasScalarOperand())
4628     return SDValue();
4629 
4630   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4631   assert(SplatOp < Op.getNumOperands());
4632 
4633   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4634   SDValue &ScalarOp = Operands[SplatOp];
4635   MVT OpVT = ScalarOp.getSimpleValueType();
4636   MVT XLenVT = Subtarget.getXLenVT();
4637 
4638   // If this isn't a scalar, or its type is XLenVT we're done.
4639   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4640     return SDValue();
4641 
4642   // Simplest case is that the operand needs to be promoted to XLenVT.
4643   if (OpVT.bitsLT(XLenVT)) {
4644     // If the operand is a constant, sign extend to increase our chances
4645     // of being able to use a .vi instruction. ANY_EXTEND would become a
4646     // a zero extend and the simm5 check in isel would fail.
4647     // FIXME: Should we ignore the upper bits in isel instead?
4648     unsigned ExtOpc =
4649         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4650     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4651     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4652   }
4653 
4654   // Use the previous operand to get the vXi64 VT. The result might be a mask
4655   // VT for compares. Using the previous operand assumes that the previous
4656   // operand will never have a smaller element size than a scalar operand and
4657   // that a widening operation never uses SEW=64.
4658   // NOTE: If this fails the below assert, we can probably just find the
4659   // element count from any operand or result and use it to construct the VT.
4660   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4661   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4662 
4663   // The more complex case is when the scalar is larger than XLenVT.
4664   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4665          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4666 
4667   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4668   // instruction to sign-extend since SEW>XLEN.
4669   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4670     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4671     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4672   }
4673 
4674   switch (IntNo) {
4675   case Intrinsic::riscv_vslide1up:
4676   case Intrinsic::riscv_vslide1down:
4677   case Intrinsic::riscv_vslide1up_mask:
4678   case Intrinsic::riscv_vslide1down_mask: {
4679     // We need to special case these when the scalar is larger than XLen.
4680     unsigned NumOps = Op.getNumOperands();
4681     bool IsMasked = NumOps == 7;
4682 
4683     // Convert the vector source to the equivalent nxvXi32 vector.
4684     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4685     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4686 
4687     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4688                                    DAG.getConstant(0, DL, XLenVT));
4689     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4690                                    DAG.getConstant(1, DL, XLenVT));
4691 
4692     // Double the VL since we halved SEW.
4693     SDValue AVL = getVLOperand(Op);
4694     SDValue I32VL;
4695 
4696     // Optimize for constant AVL
4697     if (isa<ConstantSDNode>(AVL)) {
4698       unsigned EltSize = VT.getScalarSizeInBits();
4699       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4700 
4701       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4702       unsigned MaxVLMAX =
4703           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4704 
4705       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4706       unsigned MinVLMAX =
4707           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4708 
4709       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4710       if (AVLInt <= MinVLMAX) {
4711         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4712       } else if (AVLInt >= 2 * MaxVLMAX) {
4713         // Just set vl to VLMAX in this situation
4714         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4715         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4716         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4717         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4718         SDValue SETVLMAX = DAG.getTargetConstant(
4719             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4720         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4721                             LMUL);
4722       } else {
4723         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4724         // is related to the hardware implementation.
4725         // So let the following code handle
4726       }
4727     }
4728     if (!I32VL) {
4729       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4730       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4731       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4732       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4733       SDValue SETVL =
4734           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4735       // Using vsetvli instruction to get actually used length which related to
4736       // the hardware implementation
4737       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4738                                SEW, LMUL);
4739       I32VL =
4740           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4741     }
4742 
4743     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4744 
4745     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4746     // instructions.
4747     SDValue Passthru;
4748     if (IsMasked)
4749       Passthru = DAG.getUNDEF(I32VT);
4750     else
4751       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4752 
4753     if (IntNo == Intrinsic::riscv_vslide1up ||
4754         IntNo == Intrinsic::riscv_vslide1up_mask) {
4755       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4756                         ScalarHi, I32Mask, I32VL);
4757       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4758                         ScalarLo, I32Mask, I32VL);
4759     } else {
4760       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4761                         ScalarLo, I32Mask, I32VL);
4762       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4763                         ScalarHi, I32Mask, I32VL);
4764     }
4765 
4766     // Convert back to nxvXi64.
4767     Vec = DAG.getBitcast(VT, Vec);
4768 
4769     if (!IsMasked)
4770       return Vec;
4771     // Apply mask after the operation.
4772     SDValue Mask = Operands[NumOps - 3];
4773     SDValue MaskedOff = Operands[1];
4774     // Assume Policy operand is the last operand.
4775     uint64_t Policy =
4776         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4777     // We don't need to select maskedoff if it's undef.
4778     if (MaskedOff.isUndef())
4779       return Vec;
4780     // TAMU
4781     if (Policy == RISCVII::TAIL_AGNOSTIC)
4782       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4783                          AVL);
4784     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4785     // It's fine because vmerge does not care mask policy.
4786     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4787                        AVL);
4788   }
4789   }
4790 
4791   // We need to convert the scalar to a splat vector.
4792   SDValue VL = getVLOperand(Op);
4793   assert(VL.getValueType() == XLenVT);
4794   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4795   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4796 }
4797 
4798 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4799                                                      SelectionDAG &DAG) const {
4800   unsigned IntNo = Op.getConstantOperandVal(0);
4801   SDLoc DL(Op);
4802   MVT XLenVT = Subtarget.getXLenVT();
4803 
4804   switch (IntNo) {
4805   default:
4806     break; // Don't custom lower most intrinsics.
4807   case Intrinsic::thread_pointer: {
4808     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4809     return DAG.getRegister(RISCV::X4, PtrVT);
4810   }
4811   case Intrinsic::riscv_orc_b:
4812   case Intrinsic::riscv_brev8: {
4813     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4814     unsigned Opc =
4815         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4816     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4817                        DAG.getConstant(7, DL, XLenVT));
4818   }
4819   case Intrinsic::riscv_grev:
4820   case Intrinsic::riscv_gorc: {
4821     unsigned Opc =
4822         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4823     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4824   }
4825   case Intrinsic::riscv_zip:
4826   case Intrinsic::riscv_unzip: {
4827     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4828     // For i32 the immediate is 15. For i64 the immediate is 31.
4829     unsigned Opc =
4830         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4831     unsigned BitWidth = Op.getValueSizeInBits();
4832     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4833     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4834                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4835   }
4836   case Intrinsic::riscv_shfl:
4837   case Intrinsic::riscv_unshfl: {
4838     unsigned Opc =
4839         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4840     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4841   }
4842   case Intrinsic::riscv_bcompress:
4843   case Intrinsic::riscv_bdecompress: {
4844     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4845                                                        : RISCVISD::BDECOMPRESS;
4846     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4847   }
4848   case Intrinsic::riscv_bfp:
4849     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4850                        Op.getOperand(2));
4851   case Intrinsic::riscv_fsl:
4852     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4853                        Op.getOperand(2), Op.getOperand(3));
4854   case Intrinsic::riscv_fsr:
4855     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4856                        Op.getOperand(2), Op.getOperand(3));
4857   case Intrinsic::riscv_vmv_x_s:
4858     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4859     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4860                        Op.getOperand(1));
4861   case Intrinsic::riscv_vmv_v_x:
4862     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4863                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4864                             Subtarget);
4865   case Intrinsic::riscv_vfmv_v_f:
4866     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4867                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4868   case Intrinsic::riscv_vmv_s_x: {
4869     SDValue Scalar = Op.getOperand(2);
4870 
4871     if (Scalar.getValueType().bitsLE(XLenVT)) {
4872       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4873       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4874                          Op.getOperand(1), Scalar, Op.getOperand(3));
4875     }
4876 
4877     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4878 
4879     // This is an i64 value that lives in two scalar registers. We have to
4880     // insert this in a convoluted way. First we build vXi64 splat containing
4881     // the two values that we assemble using some bit math. Next we'll use
4882     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4883     // to merge element 0 from our splat into the source vector.
4884     // FIXME: This is probably not the best way to do this, but it is
4885     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4886     // point.
4887     //   sw lo, (a0)
4888     //   sw hi, 4(a0)
4889     //   vlse vX, (a0)
4890     //
4891     //   vid.v      vVid
4892     //   vmseq.vx   mMask, vVid, 0
4893     //   vmerge.vvm vDest, vSrc, vVal, mMask
4894     MVT VT = Op.getSimpleValueType();
4895     SDValue Vec = Op.getOperand(1);
4896     SDValue VL = getVLOperand(Op);
4897 
4898     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4899     if (Op.getOperand(1).isUndef())
4900       return SplattedVal;
4901     SDValue SplattedIdx =
4902         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4903                     DAG.getConstant(0, DL, MVT::i32), VL);
4904 
4905     MVT MaskVT = getMaskTypeFor(VT);
4906     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4907     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4908     SDValue SelectCond =
4909         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4910                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4911     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4912                        Vec, VL);
4913   }
4914   }
4915 
4916   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4917 }
4918 
4919 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4920                                                     SelectionDAG &DAG) const {
4921   unsigned IntNo = Op.getConstantOperandVal(1);
4922   switch (IntNo) {
4923   default:
4924     break;
4925   case Intrinsic::riscv_masked_strided_load: {
4926     SDLoc DL(Op);
4927     MVT XLenVT = Subtarget.getXLenVT();
4928 
4929     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4930     // the selection of the masked intrinsics doesn't do this for us.
4931     SDValue Mask = Op.getOperand(5);
4932     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4933 
4934     MVT VT = Op->getSimpleValueType(0);
4935     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4936 
4937     SDValue PassThru = Op.getOperand(2);
4938     if (!IsUnmasked) {
4939       MVT MaskVT = getMaskTypeFor(ContainerVT);
4940       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4941       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4942     }
4943 
4944     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4945 
4946     SDValue IntID = DAG.getTargetConstant(
4947         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4948         XLenVT);
4949 
4950     auto *Load = cast<MemIntrinsicSDNode>(Op);
4951     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4952     if (IsUnmasked)
4953       Ops.push_back(DAG.getUNDEF(ContainerVT));
4954     else
4955       Ops.push_back(PassThru);
4956     Ops.push_back(Op.getOperand(3)); // Ptr
4957     Ops.push_back(Op.getOperand(4)); // Stride
4958     if (!IsUnmasked)
4959       Ops.push_back(Mask);
4960     Ops.push_back(VL);
4961     if (!IsUnmasked) {
4962       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4963       Ops.push_back(Policy);
4964     }
4965 
4966     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4967     SDValue Result =
4968         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4969                                 Load->getMemoryVT(), Load->getMemOperand());
4970     SDValue Chain = Result.getValue(1);
4971     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4972     return DAG.getMergeValues({Result, Chain}, DL);
4973   }
4974   case Intrinsic::riscv_seg2_load:
4975   case Intrinsic::riscv_seg3_load:
4976   case Intrinsic::riscv_seg4_load:
4977   case Intrinsic::riscv_seg5_load:
4978   case Intrinsic::riscv_seg6_load:
4979   case Intrinsic::riscv_seg7_load:
4980   case Intrinsic::riscv_seg8_load: {
4981     SDLoc DL(Op);
4982     static const Intrinsic::ID VlsegInts[7] = {
4983         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4984         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4985         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4986         Intrinsic::riscv_vlseg8};
4987     unsigned NF = Op->getNumValues() - 1;
4988     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4989     MVT XLenVT = Subtarget.getXLenVT();
4990     MVT VT = Op->getSimpleValueType(0);
4991     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4992 
4993     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4994     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4995     auto *Load = cast<MemIntrinsicSDNode>(Op);
4996     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4997     ContainerVTs.push_back(MVT::Other);
4998     SDVTList VTs = DAG.getVTList(ContainerVTs);
4999     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
5000     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
5001     Ops.push_back(Op.getOperand(2));
5002     Ops.push_back(VL);
5003     SDValue Result =
5004         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5005                                 Load->getMemoryVT(), Load->getMemOperand());
5006     SmallVector<SDValue, 9> Results;
5007     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
5008       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
5009                                                   DAG, Subtarget));
5010     Results.push_back(Result.getValue(NF));
5011     return DAG.getMergeValues(Results, DL);
5012   }
5013   }
5014 
5015   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
5016 }
5017 
5018 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5019                                                  SelectionDAG &DAG) const {
5020   unsigned IntNo = Op.getConstantOperandVal(1);
5021   switch (IntNo) {
5022   default:
5023     break;
5024   case Intrinsic::riscv_masked_strided_store: {
5025     SDLoc DL(Op);
5026     MVT XLenVT = Subtarget.getXLenVT();
5027 
5028     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5029     // the selection of the masked intrinsics doesn't do this for us.
5030     SDValue Mask = Op.getOperand(5);
5031     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5032 
5033     SDValue Val = Op.getOperand(2);
5034     MVT VT = Val.getSimpleValueType();
5035     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5036 
5037     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5038     if (!IsUnmasked) {
5039       MVT MaskVT = getMaskTypeFor(ContainerVT);
5040       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5041     }
5042 
5043     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5044 
5045     SDValue IntID = DAG.getTargetConstant(
5046         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5047         XLenVT);
5048 
5049     auto *Store = cast<MemIntrinsicSDNode>(Op);
5050     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5051     Ops.push_back(Val);
5052     Ops.push_back(Op.getOperand(3)); // Ptr
5053     Ops.push_back(Op.getOperand(4)); // Stride
5054     if (!IsUnmasked)
5055       Ops.push_back(Mask);
5056     Ops.push_back(VL);
5057 
5058     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5059                                    Ops, Store->getMemoryVT(),
5060                                    Store->getMemOperand());
5061   }
5062   }
5063 
5064   return SDValue();
5065 }
5066 
5067 static MVT getLMUL1VT(MVT VT) {
5068   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5069          "Unexpected vector MVT");
5070   return MVT::getScalableVectorVT(
5071       VT.getVectorElementType(),
5072       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5073 }
5074 
5075 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5076   switch (ISDOpcode) {
5077   default:
5078     llvm_unreachable("Unhandled reduction");
5079   case ISD::VECREDUCE_ADD:
5080     return RISCVISD::VECREDUCE_ADD_VL;
5081   case ISD::VECREDUCE_UMAX:
5082     return RISCVISD::VECREDUCE_UMAX_VL;
5083   case ISD::VECREDUCE_SMAX:
5084     return RISCVISD::VECREDUCE_SMAX_VL;
5085   case ISD::VECREDUCE_UMIN:
5086     return RISCVISD::VECREDUCE_UMIN_VL;
5087   case ISD::VECREDUCE_SMIN:
5088     return RISCVISD::VECREDUCE_SMIN_VL;
5089   case ISD::VECREDUCE_AND:
5090     return RISCVISD::VECREDUCE_AND_VL;
5091   case ISD::VECREDUCE_OR:
5092     return RISCVISD::VECREDUCE_OR_VL;
5093   case ISD::VECREDUCE_XOR:
5094     return RISCVISD::VECREDUCE_XOR_VL;
5095   }
5096 }
5097 
5098 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5099                                                          SelectionDAG &DAG,
5100                                                          bool IsVP) const {
5101   SDLoc DL(Op);
5102   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5103   MVT VecVT = Vec.getSimpleValueType();
5104   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5105           Op.getOpcode() == ISD::VECREDUCE_OR ||
5106           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5107           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5108           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5109           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5110          "Unexpected reduction lowering");
5111 
5112   MVT XLenVT = Subtarget.getXLenVT();
5113   assert(Op.getValueType() == XLenVT &&
5114          "Expected reduction output to be legalized to XLenVT");
5115 
5116   MVT ContainerVT = VecVT;
5117   if (VecVT.isFixedLengthVector()) {
5118     ContainerVT = getContainerForFixedLengthVector(VecVT);
5119     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5120   }
5121 
5122   SDValue Mask, VL;
5123   if (IsVP) {
5124     Mask = Op.getOperand(2);
5125     VL = Op.getOperand(3);
5126   } else {
5127     std::tie(Mask, VL) =
5128         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5129   }
5130 
5131   unsigned BaseOpc;
5132   ISD::CondCode CC;
5133   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5134 
5135   switch (Op.getOpcode()) {
5136   default:
5137     llvm_unreachable("Unhandled reduction");
5138   case ISD::VECREDUCE_AND:
5139   case ISD::VP_REDUCE_AND: {
5140     // vcpop ~x == 0
5141     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5142     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5143     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5144     CC = ISD::SETEQ;
5145     BaseOpc = ISD::AND;
5146     break;
5147   }
5148   case ISD::VECREDUCE_OR:
5149   case ISD::VP_REDUCE_OR:
5150     // vcpop x != 0
5151     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5152     CC = ISD::SETNE;
5153     BaseOpc = ISD::OR;
5154     break;
5155   case ISD::VECREDUCE_XOR:
5156   case ISD::VP_REDUCE_XOR: {
5157     // ((vcpop x) & 1) != 0
5158     SDValue One = DAG.getConstant(1, DL, XLenVT);
5159     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5160     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5161     CC = ISD::SETNE;
5162     BaseOpc = ISD::XOR;
5163     break;
5164   }
5165   }
5166 
5167   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5168 
5169   if (!IsVP)
5170     return SetCC;
5171 
5172   // Now include the start value in the operation.
5173   // Note that we must return the start value when no elements are operated
5174   // upon. The vcpop instructions we've emitted in each case above will return
5175   // 0 for an inactive vector, and so we've already received the neutral value:
5176   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5177   // can simply include the start value.
5178   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5179 }
5180 
5181 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5182                                             SelectionDAG &DAG) const {
5183   SDLoc DL(Op);
5184   SDValue Vec = Op.getOperand(0);
5185   EVT VecEVT = Vec.getValueType();
5186 
5187   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5188 
5189   // Due to ordering in legalize types we may have a vector type that needs to
5190   // be split. Do that manually so we can get down to a legal type.
5191   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5192          TargetLowering::TypeSplitVector) {
5193     SDValue Lo, Hi;
5194     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5195     VecEVT = Lo.getValueType();
5196     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5197   }
5198 
5199   // TODO: The type may need to be widened rather than split. Or widened before
5200   // it can be split.
5201   if (!isTypeLegal(VecEVT))
5202     return SDValue();
5203 
5204   MVT VecVT = VecEVT.getSimpleVT();
5205   MVT VecEltVT = VecVT.getVectorElementType();
5206   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5207 
5208   MVT ContainerVT = VecVT;
5209   if (VecVT.isFixedLengthVector()) {
5210     ContainerVT = getContainerForFixedLengthVector(VecVT);
5211     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5212   }
5213 
5214   MVT M1VT = getLMUL1VT(ContainerVT);
5215   MVT XLenVT = Subtarget.getXLenVT();
5216 
5217   SDValue Mask, VL;
5218   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5219 
5220   SDValue NeutralElem =
5221       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5222   SDValue IdentitySplat =
5223       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5224                        M1VT, DL, DAG, Subtarget);
5225   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5226                                   IdentitySplat, Mask, VL);
5227   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5228                              DAG.getConstant(0, DL, XLenVT));
5229   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5230 }
5231 
5232 // Given a reduction op, this function returns the matching reduction opcode,
5233 // the vector SDValue and the scalar SDValue required to lower this to a
5234 // RISCVISD node.
5235 static std::tuple<unsigned, SDValue, SDValue>
5236 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5237   SDLoc DL(Op);
5238   auto Flags = Op->getFlags();
5239   unsigned Opcode = Op.getOpcode();
5240   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5241   switch (Opcode) {
5242   default:
5243     llvm_unreachable("Unhandled reduction");
5244   case ISD::VECREDUCE_FADD: {
5245     // Use positive zero if we can. It is cheaper to materialize.
5246     SDValue Zero =
5247         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5248     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5249   }
5250   case ISD::VECREDUCE_SEQ_FADD:
5251     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5252                            Op.getOperand(0));
5253   case ISD::VECREDUCE_FMIN:
5254     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5255                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5256   case ISD::VECREDUCE_FMAX:
5257     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5258                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5259   }
5260 }
5261 
5262 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5263                                               SelectionDAG &DAG) const {
5264   SDLoc DL(Op);
5265   MVT VecEltVT = Op.getSimpleValueType();
5266 
5267   unsigned RVVOpcode;
5268   SDValue VectorVal, ScalarVal;
5269   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5270       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5271   MVT VecVT = VectorVal.getSimpleValueType();
5272 
5273   MVT ContainerVT = VecVT;
5274   if (VecVT.isFixedLengthVector()) {
5275     ContainerVT = getContainerForFixedLengthVector(VecVT);
5276     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5277   }
5278 
5279   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5280   MVT XLenVT = Subtarget.getXLenVT();
5281 
5282   SDValue Mask, VL;
5283   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5284 
5285   SDValue ScalarSplat =
5286       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5287                        M1VT, DL, DAG, Subtarget);
5288   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5289                                   VectorVal, ScalarSplat, Mask, VL);
5290   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5291                      DAG.getConstant(0, DL, XLenVT));
5292 }
5293 
5294 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5295   switch (ISDOpcode) {
5296   default:
5297     llvm_unreachable("Unhandled reduction");
5298   case ISD::VP_REDUCE_ADD:
5299     return RISCVISD::VECREDUCE_ADD_VL;
5300   case ISD::VP_REDUCE_UMAX:
5301     return RISCVISD::VECREDUCE_UMAX_VL;
5302   case ISD::VP_REDUCE_SMAX:
5303     return RISCVISD::VECREDUCE_SMAX_VL;
5304   case ISD::VP_REDUCE_UMIN:
5305     return RISCVISD::VECREDUCE_UMIN_VL;
5306   case ISD::VP_REDUCE_SMIN:
5307     return RISCVISD::VECREDUCE_SMIN_VL;
5308   case ISD::VP_REDUCE_AND:
5309     return RISCVISD::VECREDUCE_AND_VL;
5310   case ISD::VP_REDUCE_OR:
5311     return RISCVISD::VECREDUCE_OR_VL;
5312   case ISD::VP_REDUCE_XOR:
5313     return RISCVISD::VECREDUCE_XOR_VL;
5314   case ISD::VP_REDUCE_FADD:
5315     return RISCVISD::VECREDUCE_FADD_VL;
5316   case ISD::VP_REDUCE_SEQ_FADD:
5317     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5318   case ISD::VP_REDUCE_FMAX:
5319     return RISCVISD::VECREDUCE_FMAX_VL;
5320   case ISD::VP_REDUCE_FMIN:
5321     return RISCVISD::VECREDUCE_FMIN_VL;
5322   }
5323 }
5324 
5325 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5326                                            SelectionDAG &DAG) const {
5327   SDLoc DL(Op);
5328   SDValue Vec = Op.getOperand(1);
5329   EVT VecEVT = Vec.getValueType();
5330 
5331   // TODO: The type may need to be widened rather than split. Or widened before
5332   // it can be split.
5333   if (!isTypeLegal(VecEVT))
5334     return SDValue();
5335 
5336   MVT VecVT = VecEVT.getSimpleVT();
5337   MVT VecEltVT = VecVT.getVectorElementType();
5338   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5339 
5340   MVT ContainerVT = VecVT;
5341   if (VecVT.isFixedLengthVector()) {
5342     ContainerVT = getContainerForFixedLengthVector(VecVT);
5343     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5344   }
5345 
5346   SDValue VL = Op.getOperand(3);
5347   SDValue Mask = Op.getOperand(2);
5348 
5349   MVT M1VT = getLMUL1VT(ContainerVT);
5350   MVT XLenVT = Subtarget.getXLenVT();
5351   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5352 
5353   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5354                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5355                                         DL, DAG, Subtarget);
5356   SDValue Reduction =
5357       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5358   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5359                              DAG.getConstant(0, DL, XLenVT));
5360   if (!VecVT.isInteger())
5361     return Elt0;
5362   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5363 }
5364 
5365 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5366                                                    SelectionDAG &DAG) const {
5367   SDValue Vec = Op.getOperand(0);
5368   SDValue SubVec = Op.getOperand(1);
5369   MVT VecVT = Vec.getSimpleValueType();
5370   MVT SubVecVT = SubVec.getSimpleValueType();
5371 
5372   SDLoc DL(Op);
5373   MVT XLenVT = Subtarget.getXLenVT();
5374   unsigned OrigIdx = Op.getConstantOperandVal(2);
5375   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5376 
5377   // We don't have the ability to slide mask vectors up indexed by their i1
5378   // elements; the smallest we can do is i8. Often we are able to bitcast to
5379   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5380   // into a scalable one, we might not necessarily have enough scalable
5381   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5382   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5383       (OrigIdx != 0 || !Vec.isUndef())) {
5384     if (VecVT.getVectorMinNumElements() >= 8 &&
5385         SubVecVT.getVectorMinNumElements() >= 8) {
5386       assert(OrigIdx % 8 == 0 && "Invalid index");
5387       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5388              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5389              "Unexpected mask vector lowering");
5390       OrigIdx /= 8;
5391       SubVecVT =
5392           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5393                            SubVecVT.isScalableVector());
5394       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5395                                VecVT.isScalableVector());
5396       Vec = DAG.getBitcast(VecVT, Vec);
5397       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5398     } else {
5399       // We can't slide this mask vector up indexed by its i1 elements.
5400       // This poses a problem when we wish to insert a scalable vector which
5401       // can't be re-expressed as a larger type. Just choose the slow path and
5402       // extend to a larger type, then truncate back down.
5403       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5404       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5405       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5406       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5407       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5408                         Op.getOperand(2));
5409       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5410       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5411     }
5412   }
5413 
5414   // If the subvector vector is a fixed-length type, we cannot use subregister
5415   // manipulation to simplify the codegen; we don't know which register of a
5416   // LMUL group contains the specific subvector as we only know the minimum
5417   // register size. Therefore we must slide the vector group up the full
5418   // amount.
5419   if (SubVecVT.isFixedLengthVector()) {
5420     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5421       return Op;
5422     MVT ContainerVT = VecVT;
5423     if (VecVT.isFixedLengthVector()) {
5424       ContainerVT = getContainerForFixedLengthVector(VecVT);
5425       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5426     }
5427     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5428                          DAG.getUNDEF(ContainerVT), SubVec,
5429                          DAG.getConstant(0, DL, XLenVT));
5430     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5431       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5432       return DAG.getBitcast(Op.getValueType(), SubVec);
5433     }
5434     SDValue Mask =
5435         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5436     // Set the vector length to only the number of elements we care about. Note
5437     // that for slideup this includes the offset.
5438     SDValue VL =
5439         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5440     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5441     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5442                                   SubVec, SlideupAmt, Mask, VL);
5443     if (VecVT.isFixedLengthVector())
5444       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5445     return DAG.getBitcast(Op.getValueType(), Slideup);
5446   }
5447 
5448   unsigned SubRegIdx, RemIdx;
5449   std::tie(SubRegIdx, RemIdx) =
5450       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5451           VecVT, SubVecVT, OrigIdx, TRI);
5452 
5453   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5454   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5455                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5456                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5457 
5458   // 1. If the Idx has been completely eliminated and this subvector's size is
5459   // a vector register or a multiple thereof, or the surrounding elements are
5460   // undef, then this is a subvector insert which naturally aligns to a vector
5461   // register. These can easily be handled using subregister manipulation.
5462   // 2. If the subvector is smaller than a vector register, then the insertion
5463   // must preserve the undisturbed elements of the register. We do this by
5464   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5465   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5466   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5467   // LMUL=1 type back into the larger vector (resolving to another subregister
5468   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5469   // to avoid allocating a large register group to hold our subvector.
5470   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5471     return Op;
5472 
5473   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5474   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5475   // (in our case undisturbed). This means we can set up a subvector insertion
5476   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5477   // size of the subvector.
5478   MVT InterSubVT = VecVT;
5479   SDValue AlignedExtract = Vec;
5480   unsigned AlignedIdx = OrigIdx - RemIdx;
5481   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5482     InterSubVT = getLMUL1VT(VecVT);
5483     // Extract a subvector equal to the nearest full vector register type. This
5484     // should resolve to a EXTRACT_SUBREG instruction.
5485     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5486                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5487   }
5488 
5489   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5490   // For scalable vectors this must be further multiplied by vscale.
5491   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5492 
5493   SDValue Mask, VL;
5494   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5495 
5496   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5497   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5498   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5499   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5500 
5501   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5502                        DAG.getUNDEF(InterSubVT), SubVec,
5503                        DAG.getConstant(0, DL, XLenVT));
5504 
5505   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5506                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5507 
5508   // If required, insert this subvector back into the correct vector register.
5509   // This should resolve to an INSERT_SUBREG instruction.
5510   if (VecVT.bitsGT(InterSubVT))
5511     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5512                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5513 
5514   // We might have bitcast from a mask type: cast back to the original type if
5515   // required.
5516   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5517 }
5518 
5519 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5520                                                     SelectionDAG &DAG) const {
5521   SDValue Vec = Op.getOperand(0);
5522   MVT SubVecVT = Op.getSimpleValueType();
5523   MVT VecVT = Vec.getSimpleValueType();
5524 
5525   SDLoc DL(Op);
5526   MVT XLenVT = Subtarget.getXLenVT();
5527   unsigned OrigIdx = Op.getConstantOperandVal(1);
5528   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5529 
5530   // We don't have the ability to slide mask vectors down indexed by their i1
5531   // elements; the smallest we can do is i8. Often we are able to bitcast to
5532   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5533   // from a scalable one, we might not necessarily have enough scalable
5534   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5535   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5536     if (VecVT.getVectorMinNumElements() >= 8 &&
5537         SubVecVT.getVectorMinNumElements() >= 8) {
5538       assert(OrigIdx % 8 == 0 && "Invalid index");
5539       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5540              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5541              "Unexpected mask vector lowering");
5542       OrigIdx /= 8;
5543       SubVecVT =
5544           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5545                            SubVecVT.isScalableVector());
5546       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5547                                VecVT.isScalableVector());
5548       Vec = DAG.getBitcast(VecVT, Vec);
5549     } else {
5550       // We can't slide this mask vector down, indexed by its i1 elements.
5551       // This poses a problem when we wish to extract a scalable vector which
5552       // can't be re-expressed as a larger type. Just choose the slow path and
5553       // extend to a larger type, then truncate back down.
5554       // TODO: We could probably improve this when extracting certain fixed
5555       // from fixed, where we can extract as i8 and shift the correct element
5556       // right to reach the desired subvector?
5557       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5558       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5559       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5560       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5561                         Op.getOperand(1));
5562       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5563       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5564     }
5565   }
5566 
5567   // If the subvector vector is a fixed-length type, we cannot use subregister
5568   // manipulation to simplify the codegen; we don't know which register of a
5569   // LMUL group contains the specific subvector as we only know the minimum
5570   // register size. Therefore we must slide the vector group down the full
5571   // amount.
5572   if (SubVecVT.isFixedLengthVector()) {
5573     // With an index of 0 this is a cast-like subvector, which can be performed
5574     // with subregister operations.
5575     if (OrigIdx == 0)
5576       return Op;
5577     MVT ContainerVT = VecVT;
5578     if (VecVT.isFixedLengthVector()) {
5579       ContainerVT = getContainerForFixedLengthVector(VecVT);
5580       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5581     }
5582     SDValue Mask =
5583         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5584     // Set the vector length to only the number of elements we care about. This
5585     // avoids sliding down elements we're going to discard straight away.
5586     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5587     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5588     SDValue Slidedown =
5589         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5590                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5591     // Now we can use a cast-like subvector extract to get the result.
5592     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5593                             DAG.getConstant(0, DL, XLenVT));
5594     return DAG.getBitcast(Op.getValueType(), Slidedown);
5595   }
5596 
5597   unsigned SubRegIdx, RemIdx;
5598   std::tie(SubRegIdx, RemIdx) =
5599       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5600           VecVT, SubVecVT, OrigIdx, TRI);
5601 
5602   // If the Idx has been completely eliminated then this is a subvector extract
5603   // which naturally aligns to a vector register. These can easily be handled
5604   // using subregister manipulation.
5605   if (RemIdx == 0)
5606     return Op;
5607 
5608   // Else we must shift our vector register directly to extract the subvector.
5609   // Do this using VSLIDEDOWN.
5610 
5611   // If the vector type is an LMUL-group type, extract a subvector equal to the
5612   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5613   // instruction.
5614   MVT InterSubVT = VecVT;
5615   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5616     InterSubVT = getLMUL1VT(VecVT);
5617     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5618                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5619   }
5620 
5621   // Slide this vector register down by the desired number of elements in order
5622   // to place the desired subvector starting at element 0.
5623   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5624   // For scalable vectors this must be further multiplied by vscale.
5625   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5626 
5627   SDValue Mask, VL;
5628   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5629   SDValue Slidedown =
5630       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5631                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5632 
5633   // Now the vector is in the right position, extract our final subvector. This
5634   // should resolve to a COPY.
5635   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5636                           DAG.getConstant(0, DL, XLenVT));
5637 
5638   // We might have bitcast from a mask type: cast back to the original type if
5639   // required.
5640   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5641 }
5642 
5643 // Lower step_vector to the vid instruction. Any non-identity step value must
5644 // be accounted for my manual expansion.
5645 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5646                                               SelectionDAG &DAG) const {
5647   SDLoc DL(Op);
5648   MVT VT = Op.getSimpleValueType();
5649   MVT XLenVT = Subtarget.getXLenVT();
5650   SDValue Mask, VL;
5651   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5652   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5653   uint64_t StepValImm = Op.getConstantOperandVal(0);
5654   if (StepValImm != 1) {
5655     if (isPowerOf2_64(StepValImm)) {
5656       SDValue StepVal =
5657           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5658                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5659       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5660     } else {
5661       SDValue StepVal = lowerScalarSplat(
5662           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5663           VL, VT, DL, DAG, Subtarget);
5664       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5665     }
5666   }
5667   return StepVec;
5668 }
5669 
5670 // Implement vector_reverse using vrgather.vv with indices determined by
5671 // subtracting the id of each element from (VLMAX-1). This will convert
5672 // the indices like so:
5673 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5674 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5675 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5676                                                  SelectionDAG &DAG) const {
5677   SDLoc DL(Op);
5678   MVT VecVT = Op.getSimpleValueType();
5679   if (VecVT.getVectorElementType() == MVT::i1) {
5680     MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
5681     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0));
5682     SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1);
5683     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2);
5684   }
5685   unsigned EltSize = VecVT.getScalarSizeInBits();
5686   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5687   unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
5688   unsigned MaxVLMAX =
5689     RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5690 
5691   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5692   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5693 
5694   // If this is SEW=8 and VLMAX is potentially more than 256, we need
5695   // to use vrgatherei16.vv.
5696   // TODO: It's also possible to use vrgatherei16.vv for other types to
5697   // decrease register width for the index calculation.
5698   if (MaxVLMAX > 256 && EltSize == 8) {
5699     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5700     // Reverse each half, then reassemble them in reverse order.
5701     // NOTE: It's also possible that after splitting that VLMAX no longer
5702     // requires vrgatherei16.vv.
5703     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5704       SDValue Lo, Hi;
5705       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5706       EVT LoVT, HiVT;
5707       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5708       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5709       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5710       // Reassemble the low and high pieces reversed.
5711       // FIXME: This is a CONCAT_VECTORS.
5712       SDValue Res =
5713           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5714                       DAG.getIntPtrConstant(0, DL));
5715       return DAG.getNode(
5716           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5717           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5718     }
5719 
5720     // Just promote the int type to i16 which will double the LMUL.
5721     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5722     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5723   }
5724 
5725   MVT XLenVT = Subtarget.getXLenVT();
5726   SDValue Mask, VL;
5727   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5728 
5729   // Calculate VLMAX-1 for the desired SEW.
5730   unsigned MinElts = VecVT.getVectorMinNumElements();
5731   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5732                               DAG.getConstant(MinElts, DL, XLenVT));
5733   SDValue VLMinus1 =
5734       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5735 
5736   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5737   bool IsRV32E64 =
5738       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5739   SDValue SplatVL;
5740   if (!IsRV32E64)
5741     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5742   else
5743     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5744                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5745 
5746   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5747   SDValue Indices =
5748       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5749 
5750   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask,
5751                      DAG.getUNDEF(VecVT), VL);
5752 }
5753 
5754 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5755                                                 SelectionDAG &DAG) const {
5756   SDLoc DL(Op);
5757   SDValue V1 = Op.getOperand(0);
5758   SDValue V2 = Op.getOperand(1);
5759   MVT XLenVT = Subtarget.getXLenVT();
5760   MVT VecVT = Op.getSimpleValueType();
5761 
5762   unsigned MinElts = VecVT.getVectorMinNumElements();
5763   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5764                               DAG.getConstant(MinElts, DL, XLenVT));
5765 
5766   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5767   SDValue DownOffset, UpOffset;
5768   if (ImmValue >= 0) {
5769     // The operand is a TargetConstant, we need to rebuild it as a regular
5770     // constant.
5771     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5772     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5773   } else {
5774     // The operand is a TargetConstant, we need to rebuild it as a regular
5775     // constant rather than negating the original operand.
5776     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5777     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5778   }
5779 
5780   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5781 
5782   SDValue SlideDown =
5783       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5784                   DownOffset, TrueMask, UpOffset);
5785   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5786                      TrueMask, DAG.getRegister(RISCV::X0, XLenVT));
5787 }
5788 
5789 SDValue
5790 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5791                                                      SelectionDAG &DAG) const {
5792   SDLoc DL(Op);
5793   auto *Load = cast<LoadSDNode>(Op);
5794 
5795   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5796                                         Load->getMemoryVT(),
5797                                         *Load->getMemOperand()) &&
5798          "Expecting a correctly-aligned load");
5799 
5800   MVT VT = Op.getSimpleValueType();
5801   MVT XLenVT = Subtarget.getXLenVT();
5802   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5803 
5804   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5805 
5806   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5807   SDValue IntID = DAG.getTargetConstant(
5808       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5809   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5810   if (!IsMaskOp)
5811     Ops.push_back(DAG.getUNDEF(ContainerVT));
5812   Ops.push_back(Load->getBasePtr());
5813   Ops.push_back(VL);
5814   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5815   SDValue NewLoad =
5816       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5817                               Load->getMemoryVT(), Load->getMemOperand());
5818 
5819   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5820   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5821 }
5822 
5823 SDValue
5824 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5825                                                       SelectionDAG &DAG) const {
5826   SDLoc DL(Op);
5827   auto *Store = cast<StoreSDNode>(Op);
5828 
5829   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5830                                         Store->getMemoryVT(),
5831                                         *Store->getMemOperand()) &&
5832          "Expecting a correctly-aligned store");
5833 
5834   SDValue StoreVal = Store->getValue();
5835   MVT VT = StoreVal.getSimpleValueType();
5836   MVT XLenVT = Subtarget.getXLenVT();
5837 
5838   // If the size less than a byte, we need to pad with zeros to make a byte.
5839   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5840     VT = MVT::v8i1;
5841     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5842                            DAG.getConstant(0, DL, VT), StoreVal,
5843                            DAG.getIntPtrConstant(0, DL));
5844   }
5845 
5846   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5847 
5848   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5849 
5850   SDValue NewValue =
5851       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5852 
5853   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5854   SDValue IntID = DAG.getTargetConstant(
5855       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5856   return DAG.getMemIntrinsicNode(
5857       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5858       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5859       Store->getMemoryVT(), Store->getMemOperand());
5860 }
5861 
5862 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5863                                              SelectionDAG &DAG) const {
5864   SDLoc DL(Op);
5865   MVT VT = Op.getSimpleValueType();
5866 
5867   const auto *MemSD = cast<MemSDNode>(Op);
5868   EVT MemVT = MemSD->getMemoryVT();
5869   MachineMemOperand *MMO = MemSD->getMemOperand();
5870   SDValue Chain = MemSD->getChain();
5871   SDValue BasePtr = MemSD->getBasePtr();
5872 
5873   SDValue Mask, PassThru, VL;
5874   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5875     Mask = VPLoad->getMask();
5876     PassThru = DAG.getUNDEF(VT);
5877     VL = VPLoad->getVectorLength();
5878   } else {
5879     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5880     Mask = MLoad->getMask();
5881     PassThru = MLoad->getPassThru();
5882   }
5883 
5884   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5885 
5886   MVT XLenVT = Subtarget.getXLenVT();
5887 
5888   MVT ContainerVT = VT;
5889   if (VT.isFixedLengthVector()) {
5890     ContainerVT = getContainerForFixedLengthVector(VT);
5891     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5892     if (!IsUnmasked) {
5893       MVT MaskVT = getMaskTypeFor(ContainerVT);
5894       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5895     }
5896   }
5897 
5898   if (!VL)
5899     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5900 
5901   unsigned IntID =
5902       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5903   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5904   if (IsUnmasked)
5905     Ops.push_back(DAG.getUNDEF(ContainerVT));
5906   else
5907     Ops.push_back(PassThru);
5908   Ops.push_back(BasePtr);
5909   if (!IsUnmasked)
5910     Ops.push_back(Mask);
5911   Ops.push_back(VL);
5912   if (!IsUnmasked)
5913     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5914 
5915   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5916 
5917   SDValue Result =
5918       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5919   Chain = Result.getValue(1);
5920 
5921   if (VT.isFixedLengthVector())
5922     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5923 
5924   return DAG.getMergeValues({Result, Chain}, DL);
5925 }
5926 
5927 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5928                                               SelectionDAG &DAG) const {
5929   SDLoc DL(Op);
5930 
5931   const auto *MemSD = cast<MemSDNode>(Op);
5932   EVT MemVT = MemSD->getMemoryVT();
5933   MachineMemOperand *MMO = MemSD->getMemOperand();
5934   SDValue Chain = MemSD->getChain();
5935   SDValue BasePtr = MemSD->getBasePtr();
5936   SDValue Val, Mask, VL;
5937 
5938   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5939     Val = VPStore->getValue();
5940     Mask = VPStore->getMask();
5941     VL = VPStore->getVectorLength();
5942   } else {
5943     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5944     Val = MStore->getValue();
5945     Mask = MStore->getMask();
5946   }
5947 
5948   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5949 
5950   MVT VT = Val.getSimpleValueType();
5951   MVT XLenVT = Subtarget.getXLenVT();
5952 
5953   MVT ContainerVT = VT;
5954   if (VT.isFixedLengthVector()) {
5955     ContainerVT = getContainerForFixedLengthVector(VT);
5956 
5957     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5958     if (!IsUnmasked) {
5959       MVT MaskVT = getMaskTypeFor(ContainerVT);
5960       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5961     }
5962   }
5963 
5964   if (!VL)
5965     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5966 
5967   unsigned IntID =
5968       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5969   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5970   Ops.push_back(Val);
5971   Ops.push_back(BasePtr);
5972   if (!IsUnmasked)
5973     Ops.push_back(Mask);
5974   Ops.push_back(VL);
5975 
5976   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5977                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5978 }
5979 
5980 SDValue
5981 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5982                                                       SelectionDAG &DAG) const {
5983   MVT InVT = Op.getOperand(0).getSimpleValueType();
5984   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5985 
5986   MVT VT = Op.getSimpleValueType();
5987 
5988   SDValue Op1 =
5989       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5990   SDValue Op2 =
5991       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5992 
5993   SDLoc DL(Op);
5994   SDValue VL =
5995       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5996 
5997   MVT MaskVT = getMaskTypeFor(ContainerVT);
5998   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
5999 
6000   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
6001                             Op.getOperand(2), Mask, VL);
6002 
6003   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
6004 }
6005 
6006 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
6007     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
6008   MVT VT = Op.getSimpleValueType();
6009 
6010   if (VT.getVectorElementType() == MVT::i1)
6011     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
6012 
6013   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
6014 }
6015 
6016 SDValue
6017 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
6018                                                       SelectionDAG &DAG) const {
6019   unsigned Opc;
6020   switch (Op.getOpcode()) {
6021   default: llvm_unreachable("Unexpected opcode!");
6022   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
6023   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
6024   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
6025   }
6026 
6027   return lowerToScalableOp(Op, DAG, Opc);
6028 }
6029 
6030 // Lower vector ABS to smax(X, sub(0, X)).
6031 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6032   SDLoc DL(Op);
6033   MVT VT = Op.getSimpleValueType();
6034   SDValue X = Op.getOperand(0);
6035 
6036   assert(VT.isFixedLengthVector() && "Unexpected type");
6037 
6038   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6039   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6040 
6041   SDValue Mask, VL;
6042   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6043 
6044   SDValue SplatZero = DAG.getNode(
6045       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6046       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6047   SDValue NegX =
6048       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6049   SDValue Max =
6050       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6051 
6052   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6053 }
6054 
6055 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6056     SDValue Op, SelectionDAG &DAG) const {
6057   SDLoc DL(Op);
6058   MVT VT = Op.getSimpleValueType();
6059   SDValue Mag = Op.getOperand(0);
6060   SDValue Sign = Op.getOperand(1);
6061   assert(Mag.getValueType() == Sign.getValueType() &&
6062          "Can only handle COPYSIGN with matching types.");
6063 
6064   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6065   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6066   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6067 
6068   SDValue Mask, VL;
6069   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6070 
6071   SDValue CopySign =
6072       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6073 
6074   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6075 }
6076 
6077 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6078     SDValue Op, SelectionDAG &DAG) const {
6079   MVT VT = Op.getSimpleValueType();
6080   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6081 
6082   MVT I1ContainerVT =
6083       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6084 
6085   SDValue CC =
6086       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6087   SDValue Op1 =
6088       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6089   SDValue Op2 =
6090       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6091 
6092   SDLoc DL(Op);
6093   SDValue Mask, VL;
6094   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6095 
6096   SDValue Select =
6097       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6098 
6099   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6100 }
6101 
6102 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6103                                                unsigned NewOpc,
6104                                                bool HasMask) const {
6105   MVT VT = Op.getSimpleValueType();
6106   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6107 
6108   // Create list of operands by converting existing ones to scalable types.
6109   SmallVector<SDValue, 6> Ops;
6110   for (const SDValue &V : Op->op_values()) {
6111     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6112 
6113     // Pass through non-vector operands.
6114     if (!V.getValueType().isVector()) {
6115       Ops.push_back(V);
6116       continue;
6117     }
6118 
6119     // "cast" fixed length vector to a scalable vector.
6120     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6121            "Only fixed length vectors are supported!");
6122     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6123   }
6124 
6125   SDLoc DL(Op);
6126   SDValue Mask, VL;
6127   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6128   if (HasMask)
6129     Ops.push_back(Mask);
6130   Ops.push_back(VL);
6131 
6132   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6133   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6134 }
6135 
6136 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6137 // * Operands of each node are assumed to be in the same order.
6138 // * The EVL operand is promoted from i32 to i64 on RV64.
6139 // * Fixed-length vectors are converted to their scalable-vector container
6140 //   types.
6141 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6142                                        unsigned RISCVISDOpc) const {
6143   SDLoc DL(Op);
6144   MVT VT = Op.getSimpleValueType();
6145   SmallVector<SDValue, 4> Ops;
6146 
6147   for (const auto &OpIdx : enumerate(Op->ops())) {
6148     SDValue V = OpIdx.value();
6149     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6150     // Pass through operands which aren't fixed-length vectors.
6151     if (!V.getValueType().isFixedLengthVector()) {
6152       Ops.push_back(V);
6153       continue;
6154     }
6155     // "cast" fixed length vector to a scalable vector.
6156     MVT OpVT = V.getSimpleValueType();
6157     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6158     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6159            "Only fixed length vectors are supported!");
6160     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6161   }
6162 
6163   if (!VT.isFixedLengthVector())
6164     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6165 
6166   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6167 
6168   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6169 
6170   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6171 }
6172 
6173 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6174                                               SelectionDAG &DAG) const {
6175   SDLoc DL(Op);
6176   MVT VT = Op.getSimpleValueType();
6177 
6178   SDValue Src = Op.getOperand(0);
6179   // NOTE: Mask is dropped.
6180   SDValue VL = Op.getOperand(2);
6181 
6182   MVT ContainerVT = VT;
6183   if (VT.isFixedLengthVector()) {
6184     ContainerVT = getContainerForFixedLengthVector(VT);
6185     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6186     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6187   }
6188 
6189   MVT XLenVT = Subtarget.getXLenVT();
6190   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6191   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6192                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6193 
6194   SDValue SplatValue = DAG.getConstant(
6195       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6196   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6197                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6198 
6199   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6200                                Splat, ZeroSplat, VL);
6201   if (!VT.isFixedLengthVector())
6202     return Result;
6203   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6204 }
6205 
6206 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6207                                                 SelectionDAG &DAG) const {
6208   SDLoc DL(Op);
6209   MVT VT = Op.getSimpleValueType();
6210 
6211   SDValue Op1 = Op.getOperand(0);
6212   SDValue Op2 = Op.getOperand(1);
6213   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6214   // NOTE: Mask is dropped.
6215   SDValue VL = Op.getOperand(4);
6216 
6217   MVT ContainerVT = VT;
6218   if (VT.isFixedLengthVector()) {
6219     ContainerVT = getContainerForFixedLengthVector(VT);
6220     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6221     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6222   }
6223 
6224   SDValue Result;
6225   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6226 
6227   switch (Condition) {
6228   default:
6229     break;
6230   // X != Y  --> (X^Y)
6231   case ISD::SETNE:
6232     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6233     break;
6234   // X == Y  --> ~(X^Y)
6235   case ISD::SETEQ: {
6236     SDValue Temp =
6237         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6238     Result =
6239         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6240     break;
6241   }
6242   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6243   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6244   case ISD::SETGT:
6245   case ISD::SETULT: {
6246     SDValue Temp =
6247         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6248     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6249     break;
6250   }
6251   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6252   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6253   case ISD::SETLT:
6254   case ISD::SETUGT: {
6255     SDValue Temp =
6256         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6257     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6258     break;
6259   }
6260   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6261   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6262   case ISD::SETGE:
6263   case ISD::SETULE: {
6264     SDValue Temp =
6265         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6266     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6267     break;
6268   }
6269   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6270   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6271   case ISD::SETLE:
6272   case ISD::SETUGE: {
6273     SDValue Temp =
6274         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6275     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6276     break;
6277   }
6278   }
6279 
6280   if (!VT.isFixedLengthVector())
6281     return Result;
6282   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6283 }
6284 
6285 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6286 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6287                                                 unsigned RISCVISDOpc) const {
6288   SDLoc DL(Op);
6289 
6290   SDValue Src = Op.getOperand(0);
6291   SDValue Mask = Op.getOperand(1);
6292   SDValue VL = Op.getOperand(2);
6293 
6294   MVT DstVT = Op.getSimpleValueType();
6295   MVT SrcVT = Src.getSimpleValueType();
6296   if (DstVT.isFixedLengthVector()) {
6297     DstVT = getContainerForFixedLengthVector(DstVT);
6298     SrcVT = getContainerForFixedLengthVector(SrcVT);
6299     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6300     MVT MaskVT = getMaskTypeFor(DstVT);
6301     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6302   }
6303 
6304   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6305                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6306                                 ? RISCVISD::VSEXT_VL
6307                                 : RISCVISD::VZEXT_VL;
6308 
6309   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6310   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6311 
6312   SDValue Result;
6313   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6314     if (SrcVT.isInteger()) {
6315       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6316 
6317       // Do we need to do any pre-widening before converting?
6318       if (SrcEltSize == 1) {
6319         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6320         MVT XLenVT = Subtarget.getXLenVT();
6321         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6322         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6323                                         DAG.getUNDEF(IntVT), Zero, VL);
6324         SDValue One = DAG.getConstant(
6325             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6326         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6327                                        DAG.getUNDEF(IntVT), One, VL);
6328         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6329                           ZeroSplat, VL);
6330       } else if (DstEltSize > (2 * SrcEltSize)) {
6331         // Widen before converting.
6332         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6333                                      DstVT.getVectorElementCount());
6334         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6335       }
6336 
6337       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6338     } else {
6339       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6340              "Wrong input/output vector types");
6341 
6342       // Convert f16 to f32 then convert f32 to i64.
6343       if (DstEltSize > (2 * SrcEltSize)) {
6344         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6345         MVT InterimFVT =
6346             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6347         Src =
6348             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6349       }
6350 
6351       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6352     }
6353   } else { // Narrowing + Conversion
6354     if (SrcVT.isInteger()) {
6355       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6356       // First do a narrowing convert to an FP type half the size, then round
6357       // the FP type to a small FP type if needed.
6358 
6359       MVT InterimFVT = DstVT;
6360       if (SrcEltSize > (2 * DstEltSize)) {
6361         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6362         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6363         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6364       }
6365 
6366       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6367 
6368       if (InterimFVT != DstVT) {
6369         Src = Result;
6370         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6371       }
6372     } else {
6373       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6374              "Wrong input/output vector types");
6375       // First do a narrowing conversion to an integer half the size, then
6376       // truncate if needed.
6377 
6378       if (DstEltSize == 1) {
6379         // First convert to the same size integer, then convert to mask using
6380         // setcc.
6381         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6382         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6383                                           DstVT.getVectorElementCount());
6384         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6385 
6386         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6387         // otherwise the conversion was undefined.
6388         MVT XLenVT = Subtarget.getXLenVT();
6389         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6390         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6391                                 DAG.getUNDEF(InterimIVT), SplatZero);
6392         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6393                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6394       } else {
6395         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6396                                           DstVT.getVectorElementCount());
6397 
6398         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6399 
6400         while (InterimIVT != DstVT) {
6401           SrcEltSize /= 2;
6402           Src = Result;
6403           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6404                                         DstVT.getVectorElementCount());
6405           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6406                                Src, Mask, VL);
6407         }
6408       }
6409     }
6410   }
6411 
6412   MVT VT = Op.getSimpleValueType();
6413   if (!VT.isFixedLengthVector())
6414     return Result;
6415   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6416 }
6417 
6418 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6419                                             unsigned MaskOpc,
6420                                             unsigned VecOpc) const {
6421   MVT VT = Op.getSimpleValueType();
6422   if (VT.getVectorElementType() != MVT::i1)
6423     return lowerVPOp(Op, DAG, VecOpc);
6424 
6425   // It is safe to drop mask parameter as masked-off elements are undef.
6426   SDValue Op1 = Op->getOperand(0);
6427   SDValue Op2 = Op->getOperand(1);
6428   SDValue VL = Op->getOperand(3);
6429 
6430   MVT ContainerVT = VT;
6431   const bool IsFixed = VT.isFixedLengthVector();
6432   if (IsFixed) {
6433     ContainerVT = getContainerForFixedLengthVector(VT);
6434     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6435     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6436   }
6437 
6438   SDLoc DL(Op);
6439   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6440   if (!IsFixed)
6441     return Val;
6442   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6443 }
6444 
6445 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6446 // matched to a RVV indexed load. The RVV indexed load instructions only
6447 // support the "unsigned unscaled" addressing mode; indices are implicitly
6448 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6449 // signed or scaled indexing is extended to the XLEN value type and scaled
6450 // accordingly.
6451 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6452                                                SelectionDAG &DAG) const {
6453   SDLoc DL(Op);
6454   MVT VT = Op.getSimpleValueType();
6455 
6456   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6457   EVT MemVT = MemSD->getMemoryVT();
6458   MachineMemOperand *MMO = MemSD->getMemOperand();
6459   SDValue Chain = MemSD->getChain();
6460   SDValue BasePtr = MemSD->getBasePtr();
6461 
6462   ISD::LoadExtType LoadExtType;
6463   SDValue Index, Mask, PassThru, VL;
6464 
6465   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6466     Index = VPGN->getIndex();
6467     Mask = VPGN->getMask();
6468     PassThru = DAG.getUNDEF(VT);
6469     VL = VPGN->getVectorLength();
6470     // VP doesn't support extending loads.
6471     LoadExtType = ISD::NON_EXTLOAD;
6472   } else {
6473     // Else it must be a MGATHER.
6474     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6475     Index = MGN->getIndex();
6476     Mask = MGN->getMask();
6477     PassThru = MGN->getPassThru();
6478     LoadExtType = MGN->getExtensionType();
6479   }
6480 
6481   MVT IndexVT = Index.getSimpleValueType();
6482   MVT XLenVT = Subtarget.getXLenVT();
6483 
6484   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6485          "Unexpected VTs!");
6486   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6487   // Targets have to explicitly opt-in for extending vector loads.
6488   assert(LoadExtType == ISD::NON_EXTLOAD &&
6489          "Unexpected extending MGATHER/VP_GATHER");
6490   (void)LoadExtType;
6491 
6492   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6493   // the selection of the masked intrinsics doesn't do this for us.
6494   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6495 
6496   MVT ContainerVT = VT;
6497   if (VT.isFixedLengthVector()) {
6498     ContainerVT = getContainerForFixedLengthVector(VT);
6499     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6500                                ContainerVT.getVectorElementCount());
6501 
6502     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6503 
6504     if (!IsUnmasked) {
6505       MVT MaskVT = getMaskTypeFor(ContainerVT);
6506       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6507       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6508     }
6509   }
6510 
6511   if (!VL)
6512     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6513 
6514   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6515     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6516     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6517                                    VL);
6518     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6519                         TrueMask, VL);
6520   }
6521 
6522   unsigned IntID =
6523       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6524   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6525   if (IsUnmasked)
6526     Ops.push_back(DAG.getUNDEF(ContainerVT));
6527   else
6528     Ops.push_back(PassThru);
6529   Ops.push_back(BasePtr);
6530   Ops.push_back(Index);
6531   if (!IsUnmasked)
6532     Ops.push_back(Mask);
6533   Ops.push_back(VL);
6534   if (!IsUnmasked)
6535     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6536 
6537   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6538   SDValue Result =
6539       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6540   Chain = Result.getValue(1);
6541 
6542   if (VT.isFixedLengthVector())
6543     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6544 
6545   return DAG.getMergeValues({Result, Chain}, DL);
6546 }
6547 
6548 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6549 // matched to a RVV indexed store. The RVV indexed store instructions only
6550 // support the "unsigned unscaled" addressing mode; indices are implicitly
6551 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6552 // signed or scaled indexing is extended to the XLEN value type and scaled
6553 // accordingly.
6554 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6555                                                 SelectionDAG &DAG) const {
6556   SDLoc DL(Op);
6557   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6558   EVT MemVT = MemSD->getMemoryVT();
6559   MachineMemOperand *MMO = MemSD->getMemOperand();
6560   SDValue Chain = MemSD->getChain();
6561   SDValue BasePtr = MemSD->getBasePtr();
6562 
6563   bool IsTruncatingStore = false;
6564   SDValue Index, Mask, Val, VL;
6565 
6566   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6567     Index = VPSN->getIndex();
6568     Mask = VPSN->getMask();
6569     Val = VPSN->getValue();
6570     VL = VPSN->getVectorLength();
6571     // VP doesn't support truncating stores.
6572     IsTruncatingStore = false;
6573   } else {
6574     // Else it must be a MSCATTER.
6575     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6576     Index = MSN->getIndex();
6577     Mask = MSN->getMask();
6578     Val = MSN->getValue();
6579     IsTruncatingStore = MSN->isTruncatingStore();
6580   }
6581 
6582   MVT VT = Val.getSimpleValueType();
6583   MVT IndexVT = Index.getSimpleValueType();
6584   MVT XLenVT = Subtarget.getXLenVT();
6585 
6586   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6587          "Unexpected VTs!");
6588   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6589   // Targets have to explicitly opt-in for extending vector loads and
6590   // truncating vector stores.
6591   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6592   (void)IsTruncatingStore;
6593 
6594   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6595   // the selection of the masked intrinsics doesn't do this for us.
6596   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6597 
6598   MVT ContainerVT = VT;
6599   if (VT.isFixedLengthVector()) {
6600     ContainerVT = getContainerForFixedLengthVector(VT);
6601     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6602                                ContainerVT.getVectorElementCount());
6603 
6604     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6605     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6606 
6607     if (!IsUnmasked) {
6608       MVT MaskVT = getMaskTypeFor(ContainerVT);
6609       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6610     }
6611   }
6612 
6613   if (!VL)
6614     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6615 
6616   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6617     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6618     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6619                                    VL);
6620     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6621                         TrueMask, VL);
6622   }
6623 
6624   unsigned IntID =
6625       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6626   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6627   Ops.push_back(Val);
6628   Ops.push_back(BasePtr);
6629   Ops.push_back(Index);
6630   if (!IsUnmasked)
6631     Ops.push_back(Mask);
6632   Ops.push_back(VL);
6633 
6634   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6635                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6636 }
6637 
6638 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6639                                                SelectionDAG &DAG) const {
6640   const MVT XLenVT = Subtarget.getXLenVT();
6641   SDLoc DL(Op);
6642   SDValue Chain = Op->getOperand(0);
6643   SDValue SysRegNo = DAG.getTargetConstant(
6644       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6645   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6646   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6647 
6648   // Encoding used for rounding mode in RISCV differs from that used in
6649   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6650   // table, which consists of a sequence of 4-bit fields, each representing
6651   // corresponding FLT_ROUNDS mode.
6652   static const int Table =
6653       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6654       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6655       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6656       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6657       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6658 
6659   SDValue Shift =
6660       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6661   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6662                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6663   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6664                                DAG.getConstant(7, DL, XLenVT));
6665 
6666   return DAG.getMergeValues({Masked, Chain}, DL);
6667 }
6668 
6669 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6670                                                SelectionDAG &DAG) const {
6671   const MVT XLenVT = Subtarget.getXLenVT();
6672   SDLoc DL(Op);
6673   SDValue Chain = Op->getOperand(0);
6674   SDValue RMValue = Op->getOperand(1);
6675   SDValue SysRegNo = DAG.getTargetConstant(
6676       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6677 
6678   // Encoding used for rounding mode in RISCV differs from that used in
6679   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6680   // a table, which consists of a sequence of 4-bit fields, each representing
6681   // corresponding RISCV mode.
6682   static const unsigned Table =
6683       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6684       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6685       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6686       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6687       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6688 
6689   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6690                               DAG.getConstant(2, DL, XLenVT));
6691   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6692                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6693   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6694                         DAG.getConstant(0x7, DL, XLenVT));
6695   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6696                      RMValue);
6697 }
6698 
6699 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6700                                                SelectionDAG &DAG) const {
6701   MachineFunction &MF = DAG.getMachineFunction();
6702 
6703   bool isRISCV64 = Subtarget.is64Bit();
6704   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6705 
6706   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6707   return DAG.getFrameIndex(FI, PtrVT);
6708 }
6709 
6710 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6711   switch (IntNo) {
6712   default:
6713     llvm_unreachable("Unexpected Intrinsic");
6714   case Intrinsic::riscv_bcompress:
6715     return RISCVISD::BCOMPRESSW;
6716   case Intrinsic::riscv_bdecompress:
6717     return RISCVISD::BDECOMPRESSW;
6718   case Intrinsic::riscv_bfp:
6719     return RISCVISD::BFPW;
6720   case Intrinsic::riscv_fsl:
6721     return RISCVISD::FSLW;
6722   case Intrinsic::riscv_fsr:
6723     return RISCVISD::FSRW;
6724   }
6725 }
6726 
6727 // Converts the given intrinsic to a i64 operation with any extension.
6728 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6729                                          unsigned IntNo) {
6730   SDLoc DL(N);
6731   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6732   // Deal with the Instruction Operands
6733   SmallVector<SDValue, 3> NewOps;
6734   for (SDValue Op : drop_begin(N->ops()))
6735     // Promote the operand to i64 type
6736     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6737   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6738   // ReplaceNodeResults requires we maintain the same type for the return value.
6739   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6740 }
6741 
6742 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6743 // form of the given Opcode.
6744 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6745   switch (Opcode) {
6746   default:
6747     llvm_unreachable("Unexpected opcode");
6748   case ISD::SHL:
6749     return RISCVISD::SLLW;
6750   case ISD::SRA:
6751     return RISCVISD::SRAW;
6752   case ISD::SRL:
6753     return RISCVISD::SRLW;
6754   case ISD::SDIV:
6755     return RISCVISD::DIVW;
6756   case ISD::UDIV:
6757     return RISCVISD::DIVUW;
6758   case ISD::UREM:
6759     return RISCVISD::REMUW;
6760   case ISD::ROTL:
6761     return RISCVISD::ROLW;
6762   case ISD::ROTR:
6763     return RISCVISD::RORW;
6764   }
6765 }
6766 
6767 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6768 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6769 // otherwise be promoted to i64, making it difficult to select the
6770 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6771 // type i8/i16/i32 is lost.
6772 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6773                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6774   SDLoc DL(N);
6775   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6776   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6777   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6778   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6779   // ReplaceNodeResults requires we maintain the same type for the return value.
6780   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6781 }
6782 
6783 // Converts the given 32-bit operation to a i64 operation with signed extension
6784 // semantic to reduce the signed extension instructions.
6785 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6786   SDLoc DL(N);
6787   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6788   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6789   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6790   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6791                                DAG.getValueType(MVT::i32));
6792   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6793 }
6794 
6795 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6796                                              SmallVectorImpl<SDValue> &Results,
6797                                              SelectionDAG &DAG) const {
6798   SDLoc DL(N);
6799   switch (N->getOpcode()) {
6800   default:
6801     llvm_unreachable("Don't know how to custom type legalize this operation!");
6802   case ISD::STRICT_FP_TO_SINT:
6803   case ISD::STRICT_FP_TO_UINT:
6804   case ISD::FP_TO_SINT:
6805   case ISD::FP_TO_UINT: {
6806     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6807            "Unexpected custom legalisation");
6808     bool IsStrict = N->isStrictFPOpcode();
6809     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6810                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6811     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6812     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6813         TargetLowering::TypeSoftenFloat) {
6814       if (!isTypeLegal(Op0.getValueType()))
6815         return;
6816       if (IsStrict) {
6817         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6818                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6819         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6820         SDValue Res = DAG.getNode(
6821             Opc, DL, VTs, N->getOperand(0), Op0,
6822             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6823         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6824         Results.push_back(Res.getValue(1));
6825         return;
6826       }
6827       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6828       SDValue Res =
6829           DAG.getNode(Opc, DL, MVT::i64, Op0,
6830                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6831       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6832       return;
6833     }
6834     // If the FP type needs to be softened, emit a library call using the 'si'
6835     // version. If we left it to default legalization we'd end up with 'di'. If
6836     // the FP type doesn't need to be softened just let generic type
6837     // legalization promote the result type.
6838     RTLIB::Libcall LC;
6839     if (IsSigned)
6840       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6841     else
6842       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6843     MakeLibCallOptions CallOptions;
6844     EVT OpVT = Op0.getValueType();
6845     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6846     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6847     SDValue Result;
6848     std::tie(Result, Chain) =
6849         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6850     Results.push_back(Result);
6851     if (IsStrict)
6852       Results.push_back(Chain);
6853     break;
6854   }
6855   case ISD::READCYCLECOUNTER: {
6856     assert(!Subtarget.is64Bit() &&
6857            "READCYCLECOUNTER only has custom type legalization on riscv32");
6858 
6859     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6860     SDValue RCW =
6861         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6862 
6863     Results.push_back(
6864         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6865     Results.push_back(RCW.getValue(2));
6866     break;
6867   }
6868   case ISD::MUL: {
6869     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6870     unsigned XLen = Subtarget.getXLen();
6871     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6872     if (Size > XLen) {
6873       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6874       SDValue LHS = N->getOperand(0);
6875       SDValue RHS = N->getOperand(1);
6876       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6877 
6878       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6879       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6880       // We need exactly one side to be unsigned.
6881       if (LHSIsU == RHSIsU)
6882         return;
6883 
6884       auto MakeMULPair = [&](SDValue S, SDValue U) {
6885         MVT XLenVT = Subtarget.getXLenVT();
6886         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6887         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6888         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6889         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6890         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6891       };
6892 
6893       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6894       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6895 
6896       // The other operand should be signed, but still prefer MULH when
6897       // possible.
6898       if (RHSIsU && LHSIsS && !RHSIsS)
6899         Results.push_back(MakeMULPair(LHS, RHS));
6900       else if (LHSIsU && RHSIsS && !LHSIsS)
6901         Results.push_back(MakeMULPair(RHS, LHS));
6902 
6903       return;
6904     }
6905     LLVM_FALLTHROUGH;
6906   }
6907   case ISD::ADD:
6908   case ISD::SUB:
6909     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6910            "Unexpected custom legalisation");
6911     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6912     break;
6913   case ISD::SHL:
6914   case ISD::SRA:
6915   case ISD::SRL:
6916     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6917            "Unexpected custom legalisation");
6918     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6919       // If we can use a BSET instruction, allow default promotion to apply.
6920       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6921           isOneConstant(N->getOperand(0)))
6922         break;
6923       Results.push_back(customLegalizeToWOp(N, DAG));
6924       break;
6925     }
6926 
6927     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6928     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6929     // shift amount.
6930     if (N->getOpcode() == ISD::SHL) {
6931       SDLoc DL(N);
6932       SDValue NewOp0 =
6933           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6934       SDValue NewOp1 =
6935           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6936       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6937       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6938                                    DAG.getValueType(MVT::i32));
6939       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6940     }
6941 
6942     break;
6943   case ISD::ROTL:
6944   case ISD::ROTR:
6945     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6946            "Unexpected custom legalisation");
6947     Results.push_back(customLegalizeToWOp(N, DAG));
6948     break;
6949   case ISD::CTTZ:
6950   case ISD::CTTZ_ZERO_UNDEF:
6951   case ISD::CTLZ:
6952   case ISD::CTLZ_ZERO_UNDEF: {
6953     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6954            "Unexpected custom legalisation");
6955 
6956     SDValue NewOp0 =
6957         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6958     bool IsCTZ =
6959         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6960     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6961     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6962     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6963     return;
6964   }
6965   case ISD::SDIV:
6966   case ISD::UDIV:
6967   case ISD::UREM: {
6968     MVT VT = N->getSimpleValueType(0);
6969     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6970            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6971            "Unexpected custom legalisation");
6972     // Don't promote division/remainder by constant since we should expand those
6973     // to multiply by magic constant.
6974     // FIXME: What if the expansion is disabled for minsize.
6975     if (N->getOperand(1).getOpcode() == ISD::Constant)
6976       return;
6977 
6978     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6979     // the upper 32 bits. For other types we need to sign or zero extend
6980     // based on the opcode.
6981     unsigned ExtOpc = ISD::ANY_EXTEND;
6982     if (VT != MVT::i32)
6983       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6984                                            : ISD::ZERO_EXTEND;
6985 
6986     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6987     break;
6988   }
6989   case ISD::UADDO:
6990   case ISD::USUBO: {
6991     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6992            "Unexpected custom legalisation");
6993     bool IsAdd = N->getOpcode() == ISD::UADDO;
6994     // Create an ADDW or SUBW.
6995     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6996     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6997     SDValue Res =
6998         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6999     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
7000                       DAG.getValueType(MVT::i32));
7001 
7002     SDValue Overflow;
7003     if (IsAdd && isOneConstant(RHS)) {
7004       // Special case uaddo X, 1 overflowed if the addition result is 0.
7005       // The general case (X + C) < C is not necessarily beneficial. Although we
7006       // reduce the live range of X, we may introduce the materialization of
7007       // constant C, especially when the setcc result is used by branch. We have
7008       // no compare with constant and branch instructions.
7009       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
7010                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
7011     } else {
7012       // Sign extend the LHS and perform an unsigned compare with the ADDW
7013       // result. Since the inputs are sign extended from i32, this is equivalent
7014       // to comparing the lower 32 bits.
7015       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7016       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
7017                               IsAdd ? ISD::SETULT : ISD::SETUGT);
7018     }
7019 
7020     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7021     Results.push_back(Overflow);
7022     return;
7023   }
7024   case ISD::UADDSAT:
7025   case ISD::USUBSAT: {
7026     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7027            "Unexpected custom legalisation");
7028     if (Subtarget.hasStdExtZbb()) {
7029       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
7030       // sign extend allows overflow of the lower 32 bits to be detected on
7031       // the promoted size.
7032       SDValue LHS =
7033           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7034       SDValue RHS =
7035           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
7036       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
7037       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7038       return;
7039     }
7040 
7041     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
7042     // promotion for UADDO/USUBO.
7043     Results.push_back(expandAddSubSat(N, DAG));
7044     return;
7045   }
7046   case ISD::ABS: {
7047     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7048            "Unexpected custom legalisation");
7049 
7050     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
7051 
7052     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7053 
7054     // Freeze the source so we can increase it's use count.
7055     Src = DAG.getFreeze(Src);
7056 
7057     // Copy sign bit to all bits using the sraiw pattern.
7058     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7059                                    DAG.getValueType(MVT::i32));
7060     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7061                            DAG.getConstant(31, DL, MVT::i64));
7062 
7063     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7064     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7065 
7066     // NOTE: The result is only required to be anyextended, but sext is
7067     // consistent with type legalization of sub.
7068     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7069                          DAG.getValueType(MVT::i32));
7070     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7071     return;
7072   }
7073   case ISD::BITCAST: {
7074     EVT VT = N->getValueType(0);
7075     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7076     SDValue Op0 = N->getOperand(0);
7077     EVT Op0VT = Op0.getValueType();
7078     MVT XLenVT = Subtarget.getXLenVT();
7079     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7080       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7081       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7082     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7083                Subtarget.hasStdExtF()) {
7084       SDValue FPConv =
7085           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7086       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7087     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7088                isTypeLegal(Op0VT)) {
7089       // Custom-legalize bitcasts from fixed-length vector types to illegal
7090       // scalar types in order to improve codegen. Bitcast the vector to a
7091       // one-element vector type whose element type is the same as the result
7092       // type, and extract the first element.
7093       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7094       if (isTypeLegal(BVT)) {
7095         SDValue BVec = DAG.getBitcast(BVT, Op0);
7096         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7097                                       DAG.getConstant(0, DL, XLenVT)));
7098       }
7099     }
7100     break;
7101   }
7102   case RISCVISD::GREV:
7103   case RISCVISD::GORC:
7104   case RISCVISD::SHFL: {
7105     MVT VT = N->getSimpleValueType(0);
7106     MVT XLenVT = Subtarget.getXLenVT();
7107     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7108            "Unexpected custom legalisation");
7109     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7110     assert((Subtarget.hasStdExtZbp() ||
7111             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7112              N->getConstantOperandVal(1) == 7)) &&
7113            "Unexpected extension");
7114     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7115     SDValue NewOp1 =
7116         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7117     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7118     // ReplaceNodeResults requires we maintain the same type for the return
7119     // value.
7120     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7121     break;
7122   }
7123   case ISD::BSWAP:
7124   case ISD::BITREVERSE: {
7125     MVT VT = N->getSimpleValueType(0);
7126     MVT XLenVT = Subtarget.getXLenVT();
7127     assert((VT == MVT::i8 || VT == MVT::i16 ||
7128             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7129            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7130     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7131     unsigned Imm = VT.getSizeInBits() - 1;
7132     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7133     if (N->getOpcode() == ISD::BSWAP)
7134       Imm &= ~0x7U;
7135     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7136                                 DAG.getConstant(Imm, DL, XLenVT));
7137     // ReplaceNodeResults requires we maintain the same type for the return
7138     // value.
7139     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7140     break;
7141   }
7142   case ISD::FSHL:
7143   case ISD::FSHR: {
7144     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7145            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7146     SDValue NewOp0 =
7147         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7148     SDValue NewOp1 =
7149         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7150     SDValue NewShAmt =
7151         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7152     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7153     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7154     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7155                            DAG.getConstant(0x1f, DL, MVT::i64));
7156     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7157     // instruction use different orders. fshl will return its first operand for
7158     // shift of zero, fshr will return its second operand. fsl and fsr both
7159     // return rs1 so the ISD nodes need to have different operand orders.
7160     // Shift amount is in rs2.
7161     unsigned Opc = RISCVISD::FSLW;
7162     if (N->getOpcode() == ISD::FSHR) {
7163       std::swap(NewOp0, NewOp1);
7164       Opc = RISCVISD::FSRW;
7165     }
7166     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7167     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7168     break;
7169   }
7170   case ISD::EXTRACT_VECTOR_ELT: {
7171     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7172     // type is illegal (currently only vXi64 RV32).
7173     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7174     // transferred to the destination register. We issue two of these from the
7175     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7176     // first element.
7177     SDValue Vec = N->getOperand(0);
7178     SDValue Idx = N->getOperand(1);
7179 
7180     // The vector type hasn't been legalized yet so we can't issue target
7181     // specific nodes if it needs legalization.
7182     // FIXME: We would manually legalize if it's important.
7183     if (!isTypeLegal(Vec.getValueType()))
7184       return;
7185 
7186     MVT VecVT = Vec.getSimpleValueType();
7187 
7188     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7189            VecVT.getVectorElementType() == MVT::i64 &&
7190            "Unexpected EXTRACT_VECTOR_ELT legalization");
7191 
7192     // If this is a fixed vector, we need to convert it to a scalable vector.
7193     MVT ContainerVT = VecVT;
7194     if (VecVT.isFixedLengthVector()) {
7195       ContainerVT = getContainerForFixedLengthVector(VecVT);
7196       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7197     }
7198 
7199     MVT XLenVT = Subtarget.getXLenVT();
7200 
7201     // Use a VL of 1 to avoid processing more elements than we need.
7202     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7203     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7204 
7205     // Unless the index is known to be 0, we must slide the vector down to get
7206     // the desired element into index 0.
7207     if (!isNullConstant(Idx)) {
7208       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7209                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7210     }
7211 
7212     // Extract the lower XLEN bits of the correct vector element.
7213     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7214 
7215     // To extract the upper XLEN bits of the vector element, shift the first
7216     // element right by 32 bits and re-extract the lower XLEN bits.
7217     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7218                                      DAG.getUNDEF(ContainerVT),
7219                                      DAG.getConstant(32, DL, XLenVT), VL);
7220     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7221                                  ThirtyTwoV, Mask, VL);
7222 
7223     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7224 
7225     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7226     break;
7227   }
7228   case ISD::INTRINSIC_WO_CHAIN: {
7229     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7230     switch (IntNo) {
7231     default:
7232       llvm_unreachable(
7233           "Don't know how to custom type legalize this intrinsic!");
7234     case Intrinsic::riscv_grev:
7235     case Intrinsic::riscv_gorc: {
7236       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7237              "Unexpected custom legalisation");
7238       SDValue NewOp1 =
7239           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7240       SDValue NewOp2 =
7241           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7242       unsigned Opc =
7243           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7244       // If the control is a constant, promote the node by clearing any extra
7245       // bits bits in the control. isel will form greviw/gorciw if the result is
7246       // sign extended.
7247       if (isa<ConstantSDNode>(NewOp2)) {
7248         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7249                              DAG.getConstant(0x1f, DL, MVT::i64));
7250         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7251       }
7252       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7253       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7254       break;
7255     }
7256     case Intrinsic::riscv_bcompress:
7257     case Intrinsic::riscv_bdecompress:
7258     case Intrinsic::riscv_bfp:
7259     case Intrinsic::riscv_fsl:
7260     case Intrinsic::riscv_fsr: {
7261       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7262              "Unexpected custom legalisation");
7263       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7264       break;
7265     }
7266     case Intrinsic::riscv_orc_b: {
7267       // Lower to the GORCI encoding for orc.b with the operand extended.
7268       SDValue NewOp =
7269           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7270       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7271                                 DAG.getConstant(7, DL, MVT::i64));
7272       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7273       return;
7274     }
7275     case Intrinsic::riscv_shfl:
7276     case Intrinsic::riscv_unshfl: {
7277       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7278              "Unexpected custom legalisation");
7279       SDValue NewOp1 =
7280           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7281       SDValue NewOp2 =
7282           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7283       unsigned Opc =
7284           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7285       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7286       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7287       // will be shuffled the same way as the lower 32 bit half, but the two
7288       // halves won't cross.
7289       if (isa<ConstantSDNode>(NewOp2)) {
7290         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7291                              DAG.getConstant(0xf, DL, MVT::i64));
7292         Opc =
7293             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7294       }
7295       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7296       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7297       break;
7298     }
7299     case Intrinsic::riscv_vmv_x_s: {
7300       EVT VT = N->getValueType(0);
7301       MVT XLenVT = Subtarget.getXLenVT();
7302       if (VT.bitsLT(XLenVT)) {
7303         // Simple case just extract using vmv.x.s and truncate.
7304         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7305                                       Subtarget.getXLenVT(), N->getOperand(1));
7306         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7307         return;
7308       }
7309 
7310       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7311              "Unexpected custom legalization");
7312 
7313       // We need to do the move in two steps.
7314       SDValue Vec = N->getOperand(1);
7315       MVT VecVT = Vec.getSimpleValueType();
7316 
7317       // First extract the lower XLEN bits of the element.
7318       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7319 
7320       // To extract the upper XLEN bits of the vector element, shift the first
7321       // element right by 32 bits and re-extract the lower XLEN bits.
7322       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7323       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7324 
7325       SDValue ThirtyTwoV =
7326           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7327                       DAG.getConstant(32, DL, XLenVT), VL);
7328       SDValue LShr32 =
7329           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7330       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7331 
7332       Results.push_back(
7333           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7334       break;
7335     }
7336     }
7337     break;
7338   }
7339   case ISD::VECREDUCE_ADD:
7340   case ISD::VECREDUCE_AND:
7341   case ISD::VECREDUCE_OR:
7342   case ISD::VECREDUCE_XOR:
7343   case ISD::VECREDUCE_SMAX:
7344   case ISD::VECREDUCE_UMAX:
7345   case ISD::VECREDUCE_SMIN:
7346   case ISD::VECREDUCE_UMIN:
7347     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7348       Results.push_back(V);
7349     break;
7350   case ISD::VP_REDUCE_ADD:
7351   case ISD::VP_REDUCE_AND:
7352   case ISD::VP_REDUCE_OR:
7353   case ISD::VP_REDUCE_XOR:
7354   case ISD::VP_REDUCE_SMAX:
7355   case ISD::VP_REDUCE_UMAX:
7356   case ISD::VP_REDUCE_SMIN:
7357   case ISD::VP_REDUCE_UMIN:
7358     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7359       Results.push_back(V);
7360     break;
7361   case ISD::FLT_ROUNDS_: {
7362     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7363     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7364     Results.push_back(Res.getValue(0));
7365     Results.push_back(Res.getValue(1));
7366     break;
7367   }
7368   }
7369 }
7370 
7371 // A structure to hold one of the bit-manipulation patterns below. Together, a
7372 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7373 //   (or (and (shl x, 1), 0xAAAAAAAA),
7374 //       (and (srl x, 1), 0x55555555))
7375 struct RISCVBitmanipPat {
7376   SDValue Op;
7377   unsigned ShAmt;
7378   bool IsSHL;
7379 
7380   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7381     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7382   }
7383 };
7384 
7385 // Matches patterns of the form
7386 //   (and (shl x, C2), (C1 << C2))
7387 //   (and (srl x, C2), C1)
7388 //   (shl (and x, C1), C2)
7389 //   (srl (and x, (C1 << C2)), C2)
7390 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7391 // The expected masks for each shift amount are specified in BitmanipMasks where
7392 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7393 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7394 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7395 // XLen is 64.
7396 static Optional<RISCVBitmanipPat>
7397 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7398   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7399          "Unexpected number of masks");
7400   Optional<uint64_t> Mask;
7401   // Optionally consume a mask around the shift operation.
7402   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7403     Mask = Op.getConstantOperandVal(1);
7404     Op = Op.getOperand(0);
7405   }
7406   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7407     return None;
7408   bool IsSHL = Op.getOpcode() == ISD::SHL;
7409 
7410   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7411     return None;
7412   uint64_t ShAmt = Op.getConstantOperandVal(1);
7413 
7414   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7415   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7416     return None;
7417   // If we don't have enough masks for 64 bit, then we must be trying to
7418   // match SHFL so we're only allowed to shift 1/4 of the width.
7419   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7420     return None;
7421 
7422   SDValue Src = Op.getOperand(0);
7423 
7424   // The expected mask is shifted left when the AND is found around SHL
7425   // patterns.
7426   //   ((x >> 1) & 0x55555555)
7427   //   ((x << 1) & 0xAAAAAAAA)
7428   bool SHLExpMask = IsSHL;
7429 
7430   if (!Mask) {
7431     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7432     // the mask is all ones: consume that now.
7433     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7434       Mask = Src.getConstantOperandVal(1);
7435       Src = Src.getOperand(0);
7436       // The expected mask is now in fact shifted left for SRL, so reverse the
7437       // decision.
7438       //   ((x & 0xAAAAAAAA) >> 1)
7439       //   ((x & 0x55555555) << 1)
7440       SHLExpMask = !SHLExpMask;
7441     } else {
7442       // Use a default shifted mask of all-ones if there's no AND, truncated
7443       // down to the expected width. This simplifies the logic later on.
7444       Mask = maskTrailingOnes<uint64_t>(Width);
7445       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7446     }
7447   }
7448 
7449   unsigned MaskIdx = Log2_32(ShAmt);
7450   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7451 
7452   if (SHLExpMask)
7453     ExpMask <<= ShAmt;
7454 
7455   if (Mask != ExpMask)
7456     return None;
7457 
7458   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7459 }
7460 
7461 // Matches any of the following bit-manipulation patterns:
7462 //   (and (shl x, 1), (0x55555555 << 1))
7463 //   (and (srl x, 1), 0x55555555)
7464 //   (shl (and x, 0x55555555), 1)
7465 //   (srl (and x, (0x55555555 << 1)), 1)
7466 // where the shift amount and mask may vary thus:
7467 //   [1]  = 0x55555555 / 0xAAAAAAAA
7468 //   [2]  = 0x33333333 / 0xCCCCCCCC
7469 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7470 //   [8]  = 0x00FF00FF / 0xFF00FF00
7471 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7472 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7473 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7474   // These are the unshifted masks which we use to match bit-manipulation
7475   // patterns. They may be shifted left in certain circumstances.
7476   static const uint64_t BitmanipMasks[] = {
7477       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7478       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7479 
7480   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7481 }
7482 
7483 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7484 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7485   auto BinOpToRVVReduce = [](unsigned Opc) {
7486     switch (Opc) {
7487     default:
7488       llvm_unreachable("Unhandled binary to transfrom reduction");
7489     case ISD::ADD:
7490       return RISCVISD::VECREDUCE_ADD_VL;
7491     case ISD::UMAX:
7492       return RISCVISD::VECREDUCE_UMAX_VL;
7493     case ISD::SMAX:
7494       return RISCVISD::VECREDUCE_SMAX_VL;
7495     case ISD::UMIN:
7496       return RISCVISD::VECREDUCE_UMIN_VL;
7497     case ISD::SMIN:
7498       return RISCVISD::VECREDUCE_SMIN_VL;
7499     case ISD::AND:
7500       return RISCVISD::VECREDUCE_AND_VL;
7501     case ISD::OR:
7502       return RISCVISD::VECREDUCE_OR_VL;
7503     case ISD::XOR:
7504       return RISCVISD::VECREDUCE_XOR_VL;
7505     case ISD::FADD:
7506       return RISCVISD::VECREDUCE_FADD_VL;
7507     case ISD::FMAXNUM:
7508       return RISCVISD::VECREDUCE_FMAX_VL;
7509     case ISD::FMINNUM:
7510       return RISCVISD::VECREDUCE_FMIN_VL;
7511     }
7512   };
7513 
7514   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7515     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7516            isNullConstant(V.getOperand(1)) &&
7517            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7518   };
7519 
7520   unsigned Opc = N->getOpcode();
7521   unsigned ReduceIdx;
7522   if (IsReduction(N->getOperand(0), Opc))
7523     ReduceIdx = 0;
7524   else if (IsReduction(N->getOperand(1), Opc))
7525     ReduceIdx = 1;
7526   else
7527     return SDValue();
7528 
7529   // Skip if FADD disallows reassociation but the combiner needs.
7530   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7531     return SDValue();
7532 
7533   SDValue Extract = N->getOperand(ReduceIdx);
7534   SDValue Reduce = Extract.getOperand(0);
7535   if (!Reduce.hasOneUse())
7536     return SDValue();
7537 
7538   SDValue ScalarV = Reduce.getOperand(2);
7539 
7540   // Make sure that ScalarV is a splat with VL=1.
7541   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7542       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7543       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7544     return SDValue();
7545 
7546   if (!isOneConstant(ScalarV.getOperand(2)))
7547     return SDValue();
7548 
7549   // TODO: Deal with value other than neutral element.
7550   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7551     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7552         isNullFPConstant(V))
7553       return true;
7554     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7555                                  N->getFlags()) == V;
7556   };
7557 
7558   // Check the scalar of ScalarV is neutral element
7559   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7560     return SDValue();
7561 
7562   if (!ScalarV.hasOneUse())
7563     return SDValue();
7564 
7565   EVT SplatVT = ScalarV.getValueType();
7566   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7567   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7568   if (SplatVT.isInteger()) {
7569     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7570     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7571       SplatOpc = RISCVISD::VMV_S_X_VL;
7572     else
7573       SplatOpc = RISCVISD::VMV_V_X_VL;
7574   }
7575 
7576   SDValue NewScalarV =
7577       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7578                   ScalarV.getOperand(2));
7579   SDValue NewReduce =
7580       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7581                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7582                   Reduce.getOperand(3), Reduce.getOperand(4));
7583   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7584                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7585 }
7586 
7587 // Match the following pattern as a GREVI(W) operation
7588 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7589 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7590                                const RISCVSubtarget &Subtarget) {
7591   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7592   EVT VT = Op.getValueType();
7593 
7594   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7595     auto LHS = matchGREVIPat(Op.getOperand(0));
7596     auto RHS = matchGREVIPat(Op.getOperand(1));
7597     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7598       SDLoc DL(Op);
7599       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7600                          DAG.getConstant(LHS->ShAmt, DL, VT));
7601     }
7602   }
7603   return SDValue();
7604 }
7605 
7606 // Matches any the following pattern as a GORCI(W) operation
7607 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7608 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7609 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7610 // Note that with the variant of 3.,
7611 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7612 // the inner pattern will first be matched as GREVI and then the outer
7613 // pattern will be matched to GORC via the first rule above.
7614 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7615 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7616                                const RISCVSubtarget &Subtarget) {
7617   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7618   EVT VT = Op.getValueType();
7619 
7620   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7621     SDLoc DL(Op);
7622     SDValue Op0 = Op.getOperand(0);
7623     SDValue Op1 = Op.getOperand(1);
7624 
7625     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7626       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7627           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7628           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7629         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7630       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7631       if ((Reverse.getOpcode() == ISD::ROTL ||
7632            Reverse.getOpcode() == ISD::ROTR) &&
7633           Reverse.getOperand(0) == X &&
7634           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7635         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7636         if (RotAmt == (VT.getSizeInBits() / 2))
7637           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7638                              DAG.getConstant(RotAmt, DL, VT));
7639       }
7640       return SDValue();
7641     };
7642 
7643     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7644     if (SDValue V = MatchOROfReverse(Op0, Op1))
7645       return V;
7646     if (SDValue V = MatchOROfReverse(Op1, Op0))
7647       return V;
7648 
7649     // OR is commutable so canonicalize its OR operand to the left
7650     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7651       std::swap(Op0, Op1);
7652     if (Op0.getOpcode() != ISD::OR)
7653       return SDValue();
7654     SDValue OrOp0 = Op0.getOperand(0);
7655     SDValue OrOp1 = Op0.getOperand(1);
7656     auto LHS = matchGREVIPat(OrOp0);
7657     // OR is commutable so swap the operands and try again: x might have been
7658     // on the left
7659     if (!LHS) {
7660       std::swap(OrOp0, OrOp1);
7661       LHS = matchGREVIPat(OrOp0);
7662     }
7663     auto RHS = matchGREVIPat(Op1);
7664     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7665       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7666                          DAG.getConstant(LHS->ShAmt, DL, VT));
7667     }
7668   }
7669   return SDValue();
7670 }
7671 
7672 // Matches any of the following bit-manipulation patterns:
7673 //   (and (shl x, 1), (0x22222222 << 1))
7674 //   (and (srl x, 1), 0x22222222)
7675 //   (shl (and x, 0x22222222), 1)
7676 //   (srl (and x, (0x22222222 << 1)), 1)
7677 // where the shift amount and mask may vary thus:
7678 //   [1]  = 0x22222222 / 0x44444444
7679 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7680 //   [4]  = 0x00F000F0 / 0x0F000F00
7681 //   [8]  = 0x0000FF00 / 0x00FF0000
7682 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7683 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7684   // These are the unshifted masks which we use to match bit-manipulation
7685   // patterns. They may be shifted left in certain circumstances.
7686   static const uint64_t BitmanipMasks[] = {
7687       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7688       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7689 
7690   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7691 }
7692 
7693 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7694 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7695                                const RISCVSubtarget &Subtarget) {
7696   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7697   EVT VT = Op.getValueType();
7698 
7699   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7700     return SDValue();
7701 
7702   SDValue Op0 = Op.getOperand(0);
7703   SDValue Op1 = Op.getOperand(1);
7704 
7705   // Or is commutable so canonicalize the second OR to the LHS.
7706   if (Op0.getOpcode() != ISD::OR)
7707     std::swap(Op0, Op1);
7708   if (Op0.getOpcode() != ISD::OR)
7709     return SDValue();
7710 
7711   // We found an inner OR, so our operands are the operands of the inner OR
7712   // and the other operand of the outer OR.
7713   SDValue A = Op0.getOperand(0);
7714   SDValue B = Op0.getOperand(1);
7715   SDValue C = Op1;
7716 
7717   auto Match1 = matchSHFLPat(A);
7718   auto Match2 = matchSHFLPat(B);
7719 
7720   // If neither matched, we failed.
7721   if (!Match1 && !Match2)
7722     return SDValue();
7723 
7724   // We had at least one match. if one failed, try the remaining C operand.
7725   if (!Match1) {
7726     std::swap(A, C);
7727     Match1 = matchSHFLPat(A);
7728     if (!Match1)
7729       return SDValue();
7730   } else if (!Match2) {
7731     std::swap(B, C);
7732     Match2 = matchSHFLPat(B);
7733     if (!Match2)
7734       return SDValue();
7735   }
7736   assert(Match1 && Match2);
7737 
7738   // Make sure our matches pair up.
7739   if (!Match1->formsPairWith(*Match2))
7740     return SDValue();
7741 
7742   // All the remains is to make sure C is an AND with the same input, that masks
7743   // out the bits that are being shuffled.
7744   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7745       C.getOperand(0) != Match1->Op)
7746     return SDValue();
7747 
7748   uint64_t Mask = C.getConstantOperandVal(1);
7749 
7750   static const uint64_t BitmanipMasks[] = {
7751       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7752       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7753   };
7754 
7755   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7756   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7757   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7758 
7759   if (Mask != ExpMask)
7760     return SDValue();
7761 
7762   SDLoc DL(Op);
7763   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7764                      DAG.getConstant(Match1->ShAmt, DL, VT));
7765 }
7766 
7767 // Optimize (add (shl x, c0), (shl y, c1)) ->
7768 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7769 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7770                                   const RISCVSubtarget &Subtarget) {
7771   // Perform this optimization only in the zba extension.
7772   if (!Subtarget.hasStdExtZba())
7773     return SDValue();
7774 
7775   // Skip for vector types and larger types.
7776   EVT VT = N->getValueType(0);
7777   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7778     return SDValue();
7779 
7780   // The two operand nodes must be SHL and have no other use.
7781   SDValue N0 = N->getOperand(0);
7782   SDValue N1 = N->getOperand(1);
7783   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7784       !N0->hasOneUse() || !N1->hasOneUse())
7785     return SDValue();
7786 
7787   // Check c0 and c1.
7788   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7789   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7790   if (!N0C || !N1C)
7791     return SDValue();
7792   int64_t C0 = N0C->getSExtValue();
7793   int64_t C1 = N1C->getSExtValue();
7794   if (C0 <= 0 || C1 <= 0)
7795     return SDValue();
7796 
7797   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7798   int64_t Bits = std::min(C0, C1);
7799   int64_t Diff = std::abs(C0 - C1);
7800   if (Diff != 1 && Diff != 2 && Diff != 3)
7801     return SDValue();
7802 
7803   // Build nodes.
7804   SDLoc DL(N);
7805   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7806   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7807   SDValue NA0 =
7808       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7809   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7810   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7811 }
7812 
7813 // Combine
7814 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7815 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7816 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7817 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7818 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7819 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7820 // The grev patterns represents BSWAP.
7821 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7822 // off the grev.
7823 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7824                                           const RISCVSubtarget &Subtarget) {
7825   bool IsWInstruction =
7826       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7827   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7828           IsWInstruction) &&
7829          "Unexpected opcode!");
7830   SDValue Src = N->getOperand(0);
7831   EVT VT = N->getValueType(0);
7832   SDLoc DL(N);
7833 
7834   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7835     return SDValue();
7836 
7837   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7838       !isa<ConstantSDNode>(Src.getOperand(1)))
7839     return SDValue();
7840 
7841   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7842   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7843 
7844   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7845   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7846   unsigned ShAmt1 = N->getConstantOperandVal(1);
7847   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7848   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7849     return SDValue();
7850 
7851   Src = Src.getOperand(0);
7852 
7853   // Toggle bit the MSB of the shift.
7854   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7855   if (CombinedShAmt == 0)
7856     return Src;
7857 
7858   SDValue Res = DAG.getNode(
7859       RISCVISD::GREV, DL, VT, Src,
7860       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7861   if (!IsWInstruction)
7862     return Res;
7863 
7864   // Sign extend the result to match the behavior of the rotate. This will be
7865   // selected to GREVIW in isel.
7866   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7867                      DAG.getValueType(MVT::i32));
7868 }
7869 
7870 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7871 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7872 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7873 // not undo itself, but they are redundant.
7874 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7875   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7876   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7877   SDValue Src = N->getOperand(0);
7878 
7879   if (Src.getOpcode() != N->getOpcode())
7880     return SDValue();
7881 
7882   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7883       !isa<ConstantSDNode>(Src.getOperand(1)))
7884     return SDValue();
7885 
7886   unsigned ShAmt1 = N->getConstantOperandVal(1);
7887   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7888   Src = Src.getOperand(0);
7889 
7890   unsigned CombinedShAmt;
7891   if (IsGORC)
7892     CombinedShAmt = ShAmt1 | ShAmt2;
7893   else
7894     CombinedShAmt = ShAmt1 ^ ShAmt2;
7895 
7896   if (CombinedShAmt == 0)
7897     return Src;
7898 
7899   SDLoc DL(N);
7900   return DAG.getNode(
7901       N->getOpcode(), DL, N->getValueType(0), Src,
7902       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7903 }
7904 
7905 // Combine a constant select operand into its use:
7906 //
7907 // (and (select cond, -1, c), x)
7908 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7909 // (or  (select cond, 0, c), x)
7910 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7911 // (xor (select cond, 0, c), x)
7912 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7913 // (add (select cond, 0, c), x)
7914 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7915 // (sub x, (select cond, 0, c))
7916 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7917 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7918                                    SelectionDAG &DAG, bool AllOnes) {
7919   EVT VT = N->getValueType(0);
7920 
7921   // Skip vectors.
7922   if (VT.isVector())
7923     return SDValue();
7924 
7925   if ((Slct.getOpcode() != ISD::SELECT &&
7926        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7927       !Slct.hasOneUse())
7928     return SDValue();
7929 
7930   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7931     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7932   };
7933 
7934   bool SwapSelectOps;
7935   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7936   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7937   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7938   SDValue NonConstantVal;
7939   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7940     SwapSelectOps = false;
7941     NonConstantVal = FalseVal;
7942   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7943     SwapSelectOps = true;
7944     NonConstantVal = TrueVal;
7945   } else
7946     return SDValue();
7947 
7948   // Slct is now know to be the desired identity constant when CC is true.
7949   TrueVal = OtherOp;
7950   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7951   // Unless SwapSelectOps says the condition should be false.
7952   if (SwapSelectOps)
7953     std::swap(TrueVal, FalseVal);
7954 
7955   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7956     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7957                        {Slct.getOperand(0), Slct.getOperand(1),
7958                         Slct.getOperand(2), TrueVal, FalseVal});
7959 
7960   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7961                      {Slct.getOperand(0), TrueVal, FalseVal});
7962 }
7963 
7964 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7965 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7966                                               bool AllOnes) {
7967   SDValue N0 = N->getOperand(0);
7968   SDValue N1 = N->getOperand(1);
7969   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7970     return Result;
7971   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7972     return Result;
7973   return SDValue();
7974 }
7975 
7976 // Transform (add (mul x, c0), c1) ->
7977 //           (add (mul (add x, c1/c0), c0), c1%c0).
7978 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7979 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7980 // to an infinite loop in DAGCombine if transformed.
7981 // Or transform (add (mul x, c0), c1) ->
7982 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7983 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7984 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7985 // lead to an infinite loop in DAGCombine if transformed.
7986 // Or transform (add (mul x, c0), c1) ->
7987 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7988 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7989 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7990 // lead to an infinite loop in DAGCombine if transformed.
7991 // Or transform (add (mul x, c0), c1) ->
7992 //              (mul (add x, c1/c0), c0).
7993 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7994 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7995                                      const RISCVSubtarget &Subtarget) {
7996   // Skip for vector types and larger types.
7997   EVT VT = N->getValueType(0);
7998   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7999     return SDValue();
8000   // The first operand node must be a MUL and has no other use.
8001   SDValue N0 = N->getOperand(0);
8002   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
8003     return SDValue();
8004   // Check if c0 and c1 match above conditions.
8005   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8006   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8007   if (!N0C || !N1C)
8008     return SDValue();
8009   // If N0C has multiple uses it's possible one of the cases in
8010   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
8011   // in an infinite loop.
8012   if (!N0C->hasOneUse())
8013     return SDValue();
8014   int64_t C0 = N0C->getSExtValue();
8015   int64_t C1 = N1C->getSExtValue();
8016   int64_t CA, CB;
8017   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
8018     return SDValue();
8019   // Search for proper CA (non-zero) and CB that both are simm12.
8020   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
8021       !isInt<12>(C0 * (C1 / C0))) {
8022     CA = C1 / C0;
8023     CB = C1 % C0;
8024   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
8025              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
8026     CA = C1 / C0 + 1;
8027     CB = C1 % C0 - C0;
8028   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
8029              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
8030     CA = C1 / C0 - 1;
8031     CB = C1 % C0 + C0;
8032   } else
8033     return SDValue();
8034   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
8035   SDLoc DL(N);
8036   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
8037                              DAG.getConstant(CA, DL, VT));
8038   SDValue New1 =
8039       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
8040   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
8041 }
8042 
8043 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
8044                                  const RISCVSubtarget &Subtarget) {
8045   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
8046     return V;
8047   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
8048     return V;
8049   if (SDValue V = combineBinOpToReduce(N, DAG))
8050     return V;
8051   // fold (add (select lhs, rhs, cc, 0, y), x) ->
8052   //      (select lhs, rhs, cc, x, (add x, y))
8053   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8054 }
8055 
8056 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8057   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8058   //      (select lhs, rhs, cc, x, (sub x, y))
8059   SDValue N0 = N->getOperand(0);
8060   SDValue N1 = N->getOperand(1);
8061   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8062 }
8063 
8064 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8065                                  const RISCVSubtarget &Subtarget) {
8066   SDValue N0 = N->getOperand(0);
8067   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8068   // extending X. This is safe since we only need the LSB after the shift and
8069   // shift amounts larger than 31 would produce poison. If we wait until
8070   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8071   // to use a BEXT instruction.
8072   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8073       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8074       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8075       N0.hasOneUse()) {
8076     SDLoc DL(N);
8077     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8078     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8079     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8080     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8081                               DAG.getConstant(1, DL, MVT::i64));
8082     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8083   }
8084 
8085   if (SDValue V = combineBinOpToReduce(N, DAG))
8086     return V;
8087 
8088   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8089   //      (select lhs, rhs, cc, x, (and x, y))
8090   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8091 }
8092 
8093 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8094                                 const RISCVSubtarget &Subtarget) {
8095   if (Subtarget.hasStdExtZbp()) {
8096     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8097       return GREV;
8098     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8099       return GORC;
8100     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8101       return SHFL;
8102   }
8103 
8104   if (SDValue V = combineBinOpToReduce(N, DAG))
8105     return V;
8106   // fold (or (select cond, 0, y), x) ->
8107   //      (select cond, x, (or x, y))
8108   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8109 }
8110 
8111 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8112   SDValue N0 = N->getOperand(0);
8113   SDValue N1 = N->getOperand(1);
8114 
8115   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8116   // NOTE: Assumes ROL being legal means ROLW is legal.
8117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8118   if (N0.getOpcode() == RISCVISD::SLLW &&
8119       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8120       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8121     SDLoc DL(N);
8122     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8123                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8124   }
8125 
8126   if (SDValue V = combineBinOpToReduce(N, DAG))
8127     return V;
8128   // fold (xor (select cond, 0, y), x) ->
8129   //      (select cond, x, (xor x, y))
8130   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8131 }
8132 
8133 static SDValue
8134 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8135                                 const RISCVSubtarget &Subtarget) {
8136   SDValue Src = N->getOperand(0);
8137   EVT VT = N->getValueType(0);
8138 
8139   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8140   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8141       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8142     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8143                        Src.getOperand(0));
8144 
8145   // Fold (i64 (sext_inreg (abs X), i32)) ->
8146   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8147   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8148   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8149   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8150   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8151   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8152   // may get combined into an earlier operation so we need to use
8153   // ComputeNumSignBits.
8154   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8155   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8156   // we can't assume that X has 33 sign bits. We must check.
8157   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8158       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8159       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8160       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8161     SDLoc DL(N);
8162     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8163     SDValue Neg =
8164         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8165     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8166                       DAG.getValueType(MVT::i32));
8167     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8168   }
8169 
8170   return SDValue();
8171 }
8172 
8173 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8174 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8175 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8176                                              bool Commute = false) {
8177   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8178           N->getOpcode() == RISCVISD::SUB_VL) &&
8179          "Unexpected opcode");
8180   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8181   SDValue Op0 = N->getOperand(0);
8182   SDValue Op1 = N->getOperand(1);
8183   if (Commute)
8184     std::swap(Op0, Op1);
8185 
8186   MVT VT = N->getSimpleValueType(0);
8187 
8188   // Determine the narrow size for a widening add/sub.
8189   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8190   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8191                                   VT.getVectorElementCount());
8192 
8193   SDValue Mask = N->getOperand(2);
8194   SDValue VL = N->getOperand(3);
8195 
8196   SDLoc DL(N);
8197 
8198   // If the RHS is a sext or zext, we can form a widening op.
8199   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8200        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8201       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8202     unsigned ExtOpc = Op1.getOpcode();
8203     Op1 = Op1.getOperand(0);
8204     // Re-introduce narrower extends if needed.
8205     if (Op1.getValueType() != NarrowVT)
8206       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8207 
8208     unsigned WOpc;
8209     if (ExtOpc == RISCVISD::VSEXT_VL)
8210       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8211     else
8212       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8213 
8214     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8215   }
8216 
8217   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8218   // sext/zext?
8219 
8220   return SDValue();
8221 }
8222 
8223 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8224 // vwsub(u).vv/vx.
8225 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8226   SDValue Op0 = N->getOperand(0);
8227   SDValue Op1 = N->getOperand(1);
8228   SDValue Mask = N->getOperand(2);
8229   SDValue VL = N->getOperand(3);
8230 
8231   MVT VT = N->getSimpleValueType(0);
8232   MVT NarrowVT = Op1.getSimpleValueType();
8233   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8234 
8235   unsigned VOpc;
8236   switch (N->getOpcode()) {
8237   default: llvm_unreachable("Unexpected opcode");
8238   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8239   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8240   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8241   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8242   }
8243 
8244   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8245                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8246 
8247   SDLoc DL(N);
8248 
8249   // If the LHS is a sext or zext, we can narrow this op to the same size as
8250   // the RHS.
8251   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8252        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8253       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8254     unsigned ExtOpc = Op0.getOpcode();
8255     Op0 = Op0.getOperand(0);
8256     // Re-introduce narrower extends if needed.
8257     if (Op0.getValueType() != NarrowVT)
8258       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8259     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8260   }
8261 
8262   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8263                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8264 
8265   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8266   // to commute and use a vwadd(u).vx instead.
8267   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8268       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8269     Op0 = Op0.getOperand(1);
8270 
8271     // See if have enough sign bits or zero bits in the scalar to use a
8272     // widening add/sub by splatting to smaller element size.
8273     unsigned EltBits = VT.getScalarSizeInBits();
8274     unsigned ScalarBits = Op0.getValueSizeInBits();
8275     // Make sure we're getting all element bits from the scalar register.
8276     // FIXME: Support implicit sign extension of vmv.v.x?
8277     if (ScalarBits < EltBits)
8278       return SDValue();
8279 
8280     if (IsSigned) {
8281       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8282         return SDValue();
8283     } else {
8284       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8285       if (!DAG.MaskedValueIsZero(Op0, Mask))
8286         return SDValue();
8287     }
8288 
8289     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8290                       DAG.getUNDEF(NarrowVT), Op0, VL);
8291     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8292   }
8293 
8294   return SDValue();
8295 }
8296 
8297 // Try to form VWMUL, VWMULU or VWMULSU.
8298 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8299 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8300                                        bool Commute) {
8301   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8302   SDValue Op0 = N->getOperand(0);
8303   SDValue Op1 = N->getOperand(1);
8304   if (Commute)
8305     std::swap(Op0, Op1);
8306 
8307   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8308   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8309   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8310   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8311     return SDValue();
8312 
8313   SDValue Mask = N->getOperand(2);
8314   SDValue VL = N->getOperand(3);
8315 
8316   // Make sure the mask and VL match.
8317   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8318     return SDValue();
8319 
8320   MVT VT = N->getSimpleValueType(0);
8321 
8322   // Determine the narrow size for a widening multiply.
8323   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8324   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8325                                   VT.getVectorElementCount());
8326 
8327   SDLoc DL(N);
8328 
8329   // See if the other operand is the same opcode.
8330   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8331     if (!Op1.hasOneUse())
8332       return SDValue();
8333 
8334     // Make sure the mask and VL match.
8335     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8336       return SDValue();
8337 
8338     Op1 = Op1.getOperand(0);
8339   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8340     // The operand is a splat of a scalar.
8341 
8342     // The pasthru must be undef for tail agnostic
8343     if (!Op1.getOperand(0).isUndef())
8344       return SDValue();
8345     // The VL must be the same.
8346     if (Op1.getOperand(2) != VL)
8347       return SDValue();
8348 
8349     // Get the scalar value.
8350     Op1 = Op1.getOperand(1);
8351 
8352     // See if have enough sign bits or zero bits in the scalar to use a
8353     // widening multiply by splatting to smaller element size.
8354     unsigned EltBits = VT.getScalarSizeInBits();
8355     unsigned ScalarBits = Op1.getValueSizeInBits();
8356     // Make sure we're getting all element bits from the scalar register.
8357     // FIXME: Support implicit sign extension of vmv.v.x?
8358     if (ScalarBits < EltBits)
8359       return SDValue();
8360 
8361     // If the LHS is a sign extend, try to use vwmul.
8362     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8363       // Can use vwmul.
8364     } else {
8365       // Otherwise try to use vwmulu or vwmulsu.
8366       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8367       if (DAG.MaskedValueIsZero(Op1, Mask))
8368         IsVWMULSU = IsSignExt;
8369       else
8370         return SDValue();
8371     }
8372 
8373     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8374                       DAG.getUNDEF(NarrowVT), Op1, VL);
8375   } else
8376     return SDValue();
8377 
8378   Op0 = Op0.getOperand(0);
8379 
8380   // Re-introduce narrower extends if needed.
8381   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8382   if (Op0.getValueType() != NarrowVT)
8383     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8384   // vwmulsu requires second operand to be zero extended.
8385   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8386   if (Op1.getValueType() != NarrowVT)
8387     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8388 
8389   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8390   if (!IsVWMULSU)
8391     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8392   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8393 }
8394 
8395 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8396   switch (Op.getOpcode()) {
8397   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8398   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8399   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8400   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8401   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8402   }
8403 
8404   return RISCVFPRndMode::Invalid;
8405 }
8406 
8407 // Fold
8408 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8409 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8410 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8411 //   (fp_to_int (fceil X))      -> fcvt X, rup
8412 //   (fp_to_int (fround X))     -> fcvt X, rmm
8413 static SDValue performFP_TO_INTCombine(SDNode *N,
8414                                        TargetLowering::DAGCombinerInfo &DCI,
8415                                        const RISCVSubtarget &Subtarget) {
8416   SelectionDAG &DAG = DCI.DAG;
8417   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8418   MVT XLenVT = Subtarget.getXLenVT();
8419 
8420   // Only handle XLen or i32 types. Other types narrower than XLen will
8421   // eventually be legalized to XLenVT.
8422   EVT VT = N->getValueType(0);
8423   if (VT != MVT::i32 && VT != XLenVT)
8424     return SDValue();
8425 
8426   SDValue Src = N->getOperand(0);
8427 
8428   // Ensure the FP type is also legal.
8429   if (!TLI.isTypeLegal(Src.getValueType()))
8430     return SDValue();
8431 
8432   // Don't do this for f16 with Zfhmin and not Zfh.
8433   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8434     return SDValue();
8435 
8436   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8437   if (FRM == RISCVFPRndMode::Invalid)
8438     return SDValue();
8439 
8440   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8441 
8442   unsigned Opc;
8443   if (VT == XLenVT)
8444     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8445   else
8446     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8447 
8448   SDLoc DL(N);
8449   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8450                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8451   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8452 }
8453 
8454 // Fold
8455 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8456 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8457 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8458 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8459 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8460 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8461                                        TargetLowering::DAGCombinerInfo &DCI,
8462                                        const RISCVSubtarget &Subtarget) {
8463   SelectionDAG &DAG = DCI.DAG;
8464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8465   MVT XLenVT = Subtarget.getXLenVT();
8466 
8467   // Only handle XLen types. Other types narrower than XLen will eventually be
8468   // legalized to XLenVT.
8469   EVT DstVT = N->getValueType(0);
8470   if (DstVT != XLenVT)
8471     return SDValue();
8472 
8473   SDValue Src = N->getOperand(0);
8474 
8475   // Ensure the FP type is also legal.
8476   if (!TLI.isTypeLegal(Src.getValueType()))
8477     return SDValue();
8478 
8479   // Don't do this for f16 with Zfhmin and not Zfh.
8480   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8481     return SDValue();
8482 
8483   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8484 
8485   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8486   if (FRM == RISCVFPRndMode::Invalid)
8487     return SDValue();
8488 
8489   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8490 
8491   unsigned Opc;
8492   if (SatVT == DstVT)
8493     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8494   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8495     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8496   else
8497     return SDValue();
8498   // FIXME: Support other SatVTs by clamping before or after the conversion.
8499 
8500   Src = Src.getOperand(0);
8501 
8502   SDLoc DL(N);
8503   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8504                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8505 
8506   // RISCV FP-to-int conversions saturate to the destination register size, but
8507   // don't produce 0 for nan.
8508   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8509   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8510 }
8511 
8512 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8513 // smaller than XLenVT.
8514 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8515                                         const RISCVSubtarget &Subtarget) {
8516   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8517 
8518   SDValue Src = N->getOperand(0);
8519   if (Src.getOpcode() != ISD::BSWAP)
8520     return SDValue();
8521 
8522   EVT VT = N->getValueType(0);
8523   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8524       !isPowerOf2_32(VT.getSizeInBits()))
8525     return SDValue();
8526 
8527   SDLoc DL(N);
8528   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8529                      DAG.getConstant(7, DL, VT));
8530 }
8531 
8532 // Convert from one FMA opcode to another based on whether we are negating the
8533 // multiply result and/or the accumulator.
8534 // NOTE: Only supports RVV operations with VL.
8535 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
8536   assert((NegMul || NegAcc) && "Not negating anything?");
8537 
8538   // Negating the multiply result changes ADD<->SUB and toggles 'N'.
8539   if (NegMul) {
8540     // clang-format off
8541     switch (Opcode) {
8542     default: llvm_unreachable("Unexpected opcode");
8543     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFNMSUB_VL; break;
8544     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL;  break;
8545     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL;  break;
8546     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFNMADD_VL; break;
8547     }
8548     // clang-format on
8549   }
8550 
8551   // Negating the accumulator changes ADD<->SUB.
8552   if (NegAcc) {
8553     // clang-format off
8554     switch (Opcode) {
8555     default: llvm_unreachable("Unexpected opcode");
8556     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFMSUB_VL;  break;
8557     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFMADD_VL;  break;
8558     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
8559     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
8560     }
8561     // clang-format on
8562   }
8563 
8564   return Opcode;
8565 }
8566 
8567 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG,
8568                                  const RISCVSubtarget &Subtarget) {
8569   assert(N->getOpcode() == ISD::SRA && "Unexpected opcode");
8570 
8571   if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit())
8572     return SDValue();
8573 
8574   if (!isa<ConstantSDNode>(N->getOperand(1)))
8575     return SDValue();
8576   uint64_t ShAmt = N->getConstantOperandVal(1);
8577   if (ShAmt > 32)
8578     return SDValue();
8579 
8580   SDValue N0 = N->getOperand(0);
8581 
8582   // Combine (sra (sext_inreg (shl X, C1), i32), C2) ->
8583   // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of
8584   // SLLIW+SRAIW. SLLI+SRAI have compressed forms.
8585   if (ShAmt < 32 &&
8586       N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() &&
8587       cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 &&
8588       N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() &&
8589       isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
8590     uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1);
8591     if (LShAmt < 32) {
8592       SDLoc ShlDL(N0.getOperand(0));
8593       SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64,
8594                                 N0.getOperand(0).getOperand(0),
8595                                 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64));
8596       SDLoc DL(N);
8597       return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl,
8598                          DAG.getConstant(ShAmt + 32, DL, MVT::i64));
8599     }
8600   }
8601 
8602   // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C)
8603   // FIXME: Should this be a generic combine? There's a similar combine on X86.
8604   //
8605   // Also try these folds where an add or sub is in the middle.
8606   // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C)
8607   // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C)
8608   SDValue Shl;
8609   ConstantSDNode *AddC = nullptr;
8610 
8611   // We might have an ADD or SUB between the SRA and SHL.
8612   bool IsAdd = N0.getOpcode() == ISD::ADD;
8613   if ((IsAdd || N0.getOpcode() == ISD::SUB)) {
8614     if (!N0.hasOneUse())
8615       return SDValue();
8616     // Other operand needs to be a constant we can modify.
8617     AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0));
8618     if (!AddC)
8619       return SDValue();
8620 
8621     // AddC needs to have at least 32 trailing zeros.
8622     if (AddC->getAPIntValue().countTrailingZeros() < 32)
8623       return SDValue();
8624 
8625     Shl = N0.getOperand(IsAdd ? 0 : 1);
8626   } else {
8627     // Not an ADD or SUB.
8628     Shl = N0;
8629   }
8630 
8631   // Look for a shift left by 32.
8632   if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() ||
8633       !isa<ConstantSDNode>(Shl.getOperand(1)) ||
8634       Shl.getConstantOperandVal(1) != 32)
8635     return SDValue();
8636 
8637   SDLoc DL(N);
8638   SDValue In = Shl.getOperand(0);
8639 
8640   // If we looked through an ADD or SUB, we need to rebuild it with the shifted
8641   // constant.
8642   if (AddC) {
8643     SDValue ShiftedAddC =
8644         DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64);
8645     if (IsAdd)
8646       In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC);
8647     else
8648       In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In);
8649   }
8650 
8651   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In,
8652                              DAG.getValueType(MVT::i32));
8653   if (ShAmt == 32)
8654     return SExt;
8655 
8656   return DAG.getNode(
8657       ISD::SHL, DL, MVT::i64, SExt,
8658       DAG.getConstant(32 - ShAmt, DL, MVT::i64));
8659 }
8660 
8661 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8662                                                DAGCombinerInfo &DCI) const {
8663   SelectionDAG &DAG = DCI.DAG;
8664 
8665   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8666   // bits are demanded. N will be added to the Worklist if it was not deleted.
8667   // Caller should return SDValue(N, 0) if this returns true.
8668   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8669     SDValue Op = N->getOperand(OpNo);
8670     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8671     if (!SimplifyDemandedBits(Op, Mask, DCI))
8672       return false;
8673 
8674     if (N->getOpcode() != ISD::DELETED_NODE)
8675       DCI.AddToWorklist(N);
8676     return true;
8677   };
8678 
8679   switch (N->getOpcode()) {
8680   default:
8681     break;
8682   case RISCVISD::SplitF64: {
8683     SDValue Op0 = N->getOperand(0);
8684     // If the input to SplitF64 is just BuildPairF64 then the operation is
8685     // redundant. Instead, use BuildPairF64's operands directly.
8686     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8687       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8688 
8689     if (Op0->isUndef()) {
8690       SDValue Lo = DAG.getUNDEF(MVT::i32);
8691       SDValue Hi = DAG.getUNDEF(MVT::i32);
8692       return DCI.CombineTo(N, Lo, Hi);
8693     }
8694 
8695     SDLoc DL(N);
8696 
8697     // It's cheaper to materialise two 32-bit integers than to load a double
8698     // from the constant pool and transfer it to integer registers through the
8699     // stack.
8700     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8701       APInt V = C->getValueAPF().bitcastToAPInt();
8702       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8703       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8704       return DCI.CombineTo(N, Lo, Hi);
8705     }
8706 
8707     // This is a target-specific version of a DAGCombine performed in
8708     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8709     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8710     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8711     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8712         !Op0.getNode()->hasOneUse())
8713       break;
8714     SDValue NewSplitF64 =
8715         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8716                     Op0.getOperand(0));
8717     SDValue Lo = NewSplitF64.getValue(0);
8718     SDValue Hi = NewSplitF64.getValue(1);
8719     APInt SignBit = APInt::getSignMask(32);
8720     if (Op0.getOpcode() == ISD::FNEG) {
8721       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8722                                   DAG.getConstant(SignBit, DL, MVT::i32));
8723       return DCI.CombineTo(N, Lo, NewHi);
8724     }
8725     assert(Op0.getOpcode() == ISD::FABS);
8726     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8727                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8728     return DCI.CombineTo(N, Lo, NewHi);
8729   }
8730   case RISCVISD::SLLW:
8731   case RISCVISD::SRAW:
8732   case RISCVISD::SRLW: {
8733     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8734     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8735         SimplifyDemandedLowBitsHelper(1, 5))
8736       return SDValue(N, 0);
8737 
8738     break;
8739   }
8740   case ISD::ROTR:
8741   case ISD::ROTL:
8742   case RISCVISD::RORW:
8743   case RISCVISD::ROLW: {
8744     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8745       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8746       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8747           SimplifyDemandedLowBitsHelper(1, 5))
8748         return SDValue(N, 0);
8749     }
8750 
8751     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8752   }
8753   case RISCVISD::CLZW:
8754   case RISCVISD::CTZW: {
8755     // Only the lower 32 bits of the first operand are read
8756     if (SimplifyDemandedLowBitsHelper(0, 32))
8757       return SDValue(N, 0);
8758     break;
8759   }
8760   case RISCVISD::GREV:
8761   case RISCVISD::GORC: {
8762     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8763     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8764     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8765     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8766       return SDValue(N, 0);
8767 
8768     return combineGREVI_GORCI(N, DAG);
8769   }
8770   case RISCVISD::GREVW:
8771   case RISCVISD::GORCW: {
8772     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8773     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8774         SimplifyDemandedLowBitsHelper(1, 5))
8775       return SDValue(N, 0);
8776 
8777     break;
8778   }
8779   case RISCVISD::SHFL:
8780   case RISCVISD::UNSHFL: {
8781     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8782     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8783     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8784     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8785       return SDValue(N, 0);
8786 
8787     break;
8788   }
8789   case RISCVISD::SHFLW:
8790   case RISCVISD::UNSHFLW: {
8791     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8792     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8793         SimplifyDemandedLowBitsHelper(1, 4))
8794       return SDValue(N, 0);
8795 
8796     break;
8797   }
8798   case RISCVISD::BCOMPRESSW:
8799   case RISCVISD::BDECOMPRESSW: {
8800     // Only the lower 32 bits of LHS and RHS are read.
8801     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8802         SimplifyDemandedLowBitsHelper(1, 32))
8803       return SDValue(N, 0);
8804 
8805     break;
8806   }
8807   case RISCVISD::FSR:
8808   case RISCVISD::FSL:
8809   case RISCVISD::FSRW:
8810   case RISCVISD::FSLW: {
8811     bool IsWInstruction =
8812         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8813     unsigned BitWidth =
8814         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8815     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8816     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8817     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8818       return SDValue(N, 0);
8819 
8820     break;
8821   }
8822   case RISCVISD::FMV_X_ANYEXTH:
8823   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8824     SDLoc DL(N);
8825     SDValue Op0 = N->getOperand(0);
8826     MVT VT = N->getSimpleValueType(0);
8827     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8828     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8829     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8830     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8831          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8832         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8833          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8834       assert(Op0.getOperand(0).getValueType() == VT &&
8835              "Unexpected value type!");
8836       return Op0.getOperand(0);
8837     }
8838 
8839     // This is a target-specific version of a DAGCombine performed in
8840     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8841     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8842     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8843     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8844         !Op0.getNode()->hasOneUse())
8845       break;
8846     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8847     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8848     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8849     if (Op0.getOpcode() == ISD::FNEG)
8850       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8851                          DAG.getConstant(SignBit, DL, VT));
8852 
8853     assert(Op0.getOpcode() == ISD::FABS);
8854     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8855                        DAG.getConstant(~SignBit, DL, VT));
8856   }
8857   case ISD::ADD:
8858     return performADDCombine(N, DAG, Subtarget);
8859   case ISD::SUB:
8860     return performSUBCombine(N, DAG);
8861   case ISD::AND:
8862     return performANDCombine(N, DAG, Subtarget);
8863   case ISD::OR:
8864     return performORCombine(N, DAG, Subtarget);
8865   case ISD::XOR:
8866     return performXORCombine(N, DAG);
8867   case ISD::FADD:
8868   case ISD::UMAX:
8869   case ISD::UMIN:
8870   case ISD::SMAX:
8871   case ISD::SMIN:
8872   case ISD::FMAXNUM:
8873   case ISD::FMINNUM:
8874     return combineBinOpToReduce(N, DAG);
8875   case ISD::SIGN_EXTEND_INREG:
8876     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8877   case ISD::ZERO_EXTEND:
8878     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8879     // type legalization. This is safe because fp_to_uint produces poison if
8880     // it overflows.
8881     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8882       SDValue Src = N->getOperand(0);
8883       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8884           isTypeLegal(Src.getOperand(0).getValueType()))
8885         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8886                            Src.getOperand(0));
8887       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8888           isTypeLegal(Src.getOperand(1).getValueType())) {
8889         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8890         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8891                                   Src.getOperand(0), Src.getOperand(1));
8892         DCI.CombineTo(N, Res);
8893         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8894         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8895         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8896       }
8897     }
8898     return SDValue();
8899   case RISCVISD::SELECT_CC: {
8900     // Transform
8901     SDValue LHS = N->getOperand(0);
8902     SDValue RHS = N->getOperand(1);
8903     SDValue TrueV = N->getOperand(3);
8904     SDValue FalseV = N->getOperand(4);
8905 
8906     // If the True and False values are the same, we don't need a select_cc.
8907     if (TrueV == FalseV)
8908       return TrueV;
8909 
8910     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8911     if (!ISD::isIntEqualitySetCC(CCVal))
8912       break;
8913 
8914     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8915     //      (select_cc X, Y, lt, trueV, falseV)
8916     // Sometimes the setcc is introduced after select_cc has been formed.
8917     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8918         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8919       // If we're looking for eq 0 instead of ne 0, we need to invert the
8920       // condition.
8921       bool Invert = CCVal == ISD::SETEQ;
8922       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8923       if (Invert)
8924         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8925 
8926       SDLoc DL(N);
8927       RHS = LHS.getOperand(1);
8928       LHS = LHS.getOperand(0);
8929       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8930 
8931       SDValue TargetCC = DAG.getCondCode(CCVal);
8932       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8933                          {LHS, RHS, TargetCC, TrueV, FalseV});
8934     }
8935 
8936     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8937     //      (select_cc X, Y, eq/ne, trueV, falseV)
8938     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8939       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8940                          {LHS.getOperand(0), LHS.getOperand(1),
8941                           N->getOperand(2), TrueV, FalseV});
8942     // (select_cc X, 1, setne, trueV, falseV) ->
8943     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8944     // This can occur when legalizing some floating point comparisons.
8945     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8946     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8947       SDLoc DL(N);
8948       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8949       SDValue TargetCC = DAG.getCondCode(CCVal);
8950       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8951       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8952                          {LHS, RHS, TargetCC, TrueV, FalseV});
8953     }
8954 
8955     break;
8956   }
8957   case RISCVISD::BR_CC: {
8958     SDValue LHS = N->getOperand(1);
8959     SDValue RHS = N->getOperand(2);
8960     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8961     if (!ISD::isIntEqualitySetCC(CCVal))
8962       break;
8963 
8964     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8965     //      (br_cc X, Y, lt, dest)
8966     // Sometimes the setcc is introduced after br_cc has been formed.
8967     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8968         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8969       // If we're looking for eq 0 instead of ne 0, we need to invert the
8970       // condition.
8971       bool Invert = CCVal == ISD::SETEQ;
8972       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8973       if (Invert)
8974         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8975 
8976       SDLoc DL(N);
8977       RHS = LHS.getOperand(1);
8978       LHS = LHS.getOperand(0);
8979       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8980 
8981       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8982                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8983                          N->getOperand(4));
8984     }
8985 
8986     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8987     //      (br_cc X, Y, eq/ne, trueV, falseV)
8988     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8989       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8990                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8991                          N->getOperand(3), N->getOperand(4));
8992 
8993     // (br_cc X, 1, setne, br_cc) ->
8994     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8995     // This can occur when legalizing some floating point comparisons.
8996     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8997     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8998       SDLoc DL(N);
8999       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
9000       SDValue TargetCC = DAG.getCondCode(CCVal);
9001       RHS = DAG.getConstant(0, DL, LHS.getValueType());
9002       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
9003                          N->getOperand(0), LHS, RHS, TargetCC,
9004                          N->getOperand(4));
9005     }
9006     break;
9007   }
9008   case ISD::BITREVERSE:
9009     return performBITREVERSECombine(N, DAG, Subtarget);
9010   case ISD::FP_TO_SINT:
9011   case ISD::FP_TO_UINT:
9012     return performFP_TO_INTCombine(N, DCI, Subtarget);
9013   case ISD::FP_TO_SINT_SAT:
9014   case ISD::FP_TO_UINT_SAT:
9015     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
9016   case ISD::FCOPYSIGN: {
9017     EVT VT = N->getValueType(0);
9018     if (!VT.isVector())
9019       break;
9020     // There is a form of VFSGNJ which injects the negated sign of its second
9021     // operand. Try and bubble any FNEG up after the extend/round to produce
9022     // this optimized pattern. Avoid modifying cases where FP_ROUND and
9023     // TRUNC=1.
9024     SDValue In2 = N->getOperand(1);
9025     // Avoid cases where the extend/round has multiple uses, as duplicating
9026     // those is typically more expensive than removing a fneg.
9027     if (!In2.hasOneUse())
9028       break;
9029     if (In2.getOpcode() != ISD::FP_EXTEND &&
9030         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
9031       break;
9032     In2 = In2.getOperand(0);
9033     if (In2.getOpcode() != ISD::FNEG)
9034       break;
9035     SDLoc DL(N);
9036     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
9037     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
9038                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
9039   }
9040   case ISD::MGATHER:
9041   case ISD::MSCATTER:
9042   case ISD::VP_GATHER:
9043   case ISD::VP_SCATTER: {
9044     if (!DCI.isBeforeLegalize())
9045       break;
9046     SDValue Index, ScaleOp;
9047     bool IsIndexScaled = false;
9048     bool IsIndexSigned = false;
9049     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
9050       Index = VPGSN->getIndex();
9051       ScaleOp = VPGSN->getScale();
9052       IsIndexScaled = VPGSN->isIndexScaled();
9053       IsIndexSigned = VPGSN->isIndexSigned();
9054     } else {
9055       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
9056       Index = MGSN->getIndex();
9057       ScaleOp = MGSN->getScale();
9058       IsIndexScaled = MGSN->isIndexScaled();
9059       IsIndexSigned = MGSN->isIndexSigned();
9060     }
9061     EVT IndexVT = Index.getValueType();
9062     MVT XLenVT = Subtarget.getXLenVT();
9063     // RISCV indexed loads only support the "unsigned unscaled" addressing
9064     // mode, so anything else must be manually legalized.
9065     bool NeedsIdxLegalization =
9066         IsIndexScaled ||
9067         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
9068     if (!NeedsIdxLegalization)
9069       break;
9070 
9071     SDLoc DL(N);
9072 
9073     // Any index legalization should first promote to XLenVT, so we don't lose
9074     // bits when scaling. This may create an illegal index type so we let
9075     // LLVM's legalization take care of the splitting.
9076     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
9077     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
9078       IndexVT = IndexVT.changeVectorElementType(XLenVT);
9079       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9080                           DL, IndexVT, Index);
9081     }
9082 
9083     if (IsIndexScaled) {
9084       // Manually scale the indices.
9085       // TODO: Sanitize the scale operand here?
9086       // TODO: For VP nodes, should we use VP_SHL here?
9087       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
9088       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
9089       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
9090       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
9091       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
9092     }
9093 
9094     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
9095     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
9096       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
9097                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
9098                               ScaleOp, VPGN->getMask(),
9099                               VPGN->getVectorLength()},
9100                              VPGN->getMemOperand(), NewIndexTy);
9101     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
9102       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
9103                               {VPSN->getChain(), VPSN->getValue(),
9104                                VPSN->getBasePtr(), Index, ScaleOp,
9105                                VPSN->getMask(), VPSN->getVectorLength()},
9106                               VPSN->getMemOperand(), NewIndexTy);
9107     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
9108       return DAG.getMaskedGather(
9109           N->getVTList(), MGN->getMemoryVT(), DL,
9110           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
9111            MGN->getBasePtr(), Index, ScaleOp},
9112           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
9113     const auto *MSN = cast<MaskedScatterSDNode>(N);
9114     return DAG.getMaskedScatter(
9115         N->getVTList(), MSN->getMemoryVT(), DL,
9116         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
9117          Index, ScaleOp},
9118         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
9119   }
9120   case RISCVISD::SRA_VL:
9121   case RISCVISD::SRL_VL:
9122   case RISCVISD::SHL_VL: {
9123     SDValue ShAmt = N->getOperand(1);
9124     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9125       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9126       SDLoc DL(N);
9127       SDValue VL = N->getOperand(3);
9128       EVT VT = N->getValueType(0);
9129       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9130                           ShAmt.getOperand(1), VL);
9131       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
9132                          N->getOperand(2), N->getOperand(3));
9133     }
9134     break;
9135   }
9136   case ISD::SRA:
9137     if (SDValue V = performSRACombine(N, DAG, Subtarget))
9138       return V;
9139     LLVM_FALLTHROUGH;
9140   case ISD::SRL:
9141   case ISD::SHL: {
9142     SDValue ShAmt = N->getOperand(1);
9143     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9144       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9145       SDLoc DL(N);
9146       EVT VT = N->getValueType(0);
9147       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9148                           ShAmt.getOperand(1),
9149                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
9150       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
9151     }
9152     break;
9153   }
9154   case RISCVISD::ADD_VL:
9155     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
9156       return V;
9157     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
9158   case RISCVISD::SUB_VL:
9159     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
9160   case RISCVISD::VWADD_W_VL:
9161   case RISCVISD::VWADDU_W_VL:
9162   case RISCVISD::VWSUB_W_VL:
9163   case RISCVISD::VWSUBU_W_VL:
9164     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
9165   case RISCVISD::MUL_VL:
9166     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
9167       return V;
9168     // Mul is commutative.
9169     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
9170   case RISCVISD::VFMADD_VL:
9171   case RISCVISD::VFNMADD_VL:
9172   case RISCVISD::VFMSUB_VL:
9173   case RISCVISD::VFNMSUB_VL: {
9174     // Fold FNEG_VL into FMA opcodes.
9175     SDValue A = N->getOperand(0);
9176     SDValue B = N->getOperand(1);
9177     SDValue C = N->getOperand(2);
9178     SDValue Mask = N->getOperand(3);
9179     SDValue VL = N->getOperand(4);
9180 
9181     auto invertIfNegative = [&Mask, &VL](SDValue &V) {
9182       if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask &&
9183           V.getOperand(2) == VL) {
9184         // Return the negated input.
9185         V = V.getOperand(0);
9186         return true;
9187       }
9188 
9189       return false;
9190     };
9191 
9192     bool NegA = invertIfNegative(A);
9193     bool NegB = invertIfNegative(B);
9194     bool NegC = invertIfNegative(C);
9195 
9196     // If no operands are negated, we're done.
9197     if (!NegA && !NegB && !NegC)
9198       return SDValue();
9199 
9200     unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
9201     return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask,
9202                        VL);
9203   }
9204   case ISD::STORE: {
9205     auto *Store = cast<StoreSDNode>(N);
9206     SDValue Val = Store->getValue();
9207     // Combine store of vmv.x.s to vse with VL of 1.
9208     // FIXME: Support FP.
9209     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
9210       SDValue Src = Val.getOperand(0);
9211       MVT VecVT = Src.getSimpleValueType();
9212       EVT MemVT = Store->getMemoryVT();
9213       // The memory VT and the element type must match.
9214       if (MemVT == VecVT.getVectorElementType()) {
9215         SDLoc DL(N);
9216         MVT MaskVT = getMaskTypeFor(VecVT);
9217         return DAG.getStoreVP(
9218             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
9219             DAG.getConstant(1, DL, MaskVT),
9220             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
9221             Store->getMemOperand(), Store->getAddressingMode(),
9222             Store->isTruncatingStore(), /*IsCompress*/ false);
9223       }
9224     }
9225 
9226     break;
9227   }
9228   case ISD::SPLAT_VECTOR: {
9229     EVT VT = N->getValueType(0);
9230     // Only perform this combine on legal MVT types.
9231     if (!isTypeLegal(VT))
9232       break;
9233     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9234                                          DAG, Subtarget))
9235       return Gather;
9236     break;
9237   }
9238   case RISCVISD::VMV_V_X_VL: {
9239     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9240     // scalar input.
9241     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9242     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9243     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9244       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9245         return SDValue(N, 0);
9246 
9247     break;
9248   }
9249   case ISD::INTRINSIC_WO_CHAIN: {
9250     unsigned IntNo = N->getConstantOperandVal(0);
9251     switch (IntNo) {
9252       // By default we do not combine any intrinsic.
9253     default:
9254       return SDValue();
9255     case Intrinsic::riscv_vcpop:
9256     case Intrinsic::riscv_vcpop_mask:
9257     case Intrinsic::riscv_vfirst:
9258     case Intrinsic::riscv_vfirst_mask: {
9259       SDValue VL = N->getOperand(2);
9260       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9261           IntNo == Intrinsic::riscv_vfirst_mask)
9262         VL = N->getOperand(3);
9263       if (!isNullConstant(VL))
9264         return SDValue();
9265       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9266       SDLoc DL(N);
9267       EVT VT = N->getValueType(0);
9268       if (IntNo == Intrinsic::riscv_vfirst ||
9269           IntNo == Intrinsic::riscv_vfirst_mask)
9270         return DAG.getConstant(-1, DL, VT);
9271       return DAG.getConstant(0, DL, VT);
9272     }
9273     }
9274   }
9275   case ISD::BITCAST: {
9276     assert(Subtarget.useRVVForFixedLengthVectors());
9277     SDValue N0 = N->getOperand(0);
9278     EVT VT = N->getValueType(0);
9279     EVT SrcVT = N0.getValueType();
9280     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9281     // type, widen both sides to avoid a trip through memory.
9282     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9283         VT.isScalarInteger()) {
9284       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9285       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9286       Ops[0] = N0;
9287       SDLoc DL(N);
9288       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9289       N0 = DAG.getBitcast(MVT::i8, N0);
9290       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9291     }
9292 
9293     return SDValue();
9294   }
9295   }
9296 
9297   return SDValue();
9298 }
9299 
9300 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9301     const SDNode *N, CombineLevel Level) const {
9302   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9303   // materialised in fewer instructions than `(OP _, c1)`:
9304   //
9305   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9306   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9307   SDValue N0 = N->getOperand(0);
9308   EVT Ty = N0.getValueType();
9309   if (Ty.isScalarInteger() &&
9310       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9311     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9312     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9313     if (C1 && C2) {
9314       const APInt &C1Int = C1->getAPIntValue();
9315       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9316 
9317       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9318       // and the combine should happen, to potentially allow further combines
9319       // later.
9320       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9321           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9322         return true;
9323 
9324       // We can materialise `c1` in an add immediate, so it's "free", and the
9325       // combine should be prevented.
9326       if (C1Int.getMinSignedBits() <= 64 &&
9327           isLegalAddImmediate(C1Int.getSExtValue()))
9328         return false;
9329 
9330       // Neither constant will fit into an immediate, so find materialisation
9331       // costs.
9332       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9333                                               Subtarget.getFeatureBits(),
9334                                               /*CompressionCost*/true);
9335       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9336           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9337           /*CompressionCost*/true);
9338 
9339       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9340       // combine should be prevented.
9341       if (C1Cost < ShiftedC1Cost)
9342         return false;
9343     }
9344   }
9345   return true;
9346 }
9347 
9348 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9349     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9350     TargetLoweringOpt &TLO) const {
9351   // Delay this optimization as late as possible.
9352   if (!TLO.LegalOps)
9353     return false;
9354 
9355   EVT VT = Op.getValueType();
9356   if (VT.isVector())
9357     return false;
9358 
9359   // Only handle AND for now.
9360   unsigned Opcode = Op.getOpcode();
9361   if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR)
9362     return false;
9363 
9364   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9365   if (!C)
9366     return false;
9367 
9368   const APInt &Mask = C->getAPIntValue();
9369 
9370   // Clear all non-demanded bits initially.
9371   APInt ShrunkMask = Mask & DemandedBits;
9372 
9373   // Try to make a smaller immediate by setting undemanded bits.
9374 
9375   APInt ExpandedMask = Mask | ~DemandedBits;
9376 
9377   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9378     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9379   };
9380   auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool {
9381     if (NewMask == Mask)
9382       return true;
9383     SDLoc DL(Op);
9384     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType());
9385     SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
9386                                     Op.getOperand(0), NewC);
9387     return TLO.CombineTo(Op, NewOp);
9388   };
9389 
9390   // If the shrunk mask fits in sign extended 12 bits, let the target
9391   // independent code apply it.
9392   if (ShrunkMask.isSignedIntN(12))
9393     return false;
9394 
9395   // And has a few special cases for zext.
9396   if (Opcode == ISD::AND) {
9397     // Preserve (and X, 0xffff) when zext.h is supported.
9398     if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9399       APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9400       if (IsLegalMask(NewMask))
9401         return UseMask(NewMask);
9402     }
9403 
9404     // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9405     if (VT == MVT::i64) {
9406       APInt NewMask = APInt(64, 0xffffffff);
9407       if (IsLegalMask(NewMask))
9408         return UseMask(NewMask);
9409     }
9410   }
9411 
9412   // For the remaining optimizations, we need to be able to make a negative
9413   // number through a combination of mask and undemanded bits.
9414   if (!ExpandedMask.isNegative())
9415     return false;
9416 
9417   // What is the fewest number of bits we need to represent the negative number.
9418   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9419 
9420   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9421   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9422   // If we can't create a simm12, we shouldn't change opaque constants.
9423   APInt NewMask = ShrunkMask;
9424   if (MinSignedBits <= 12)
9425     NewMask.setBitsFrom(11);
9426   else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9427     NewMask.setBitsFrom(31);
9428   else
9429     return false;
9430 
9431   // Check that our new mask is a subset of the demanded mask.
9432   assert(IsLegalMask(NewMask));
9433   return UseMask(NewMask);
9434 }
9435 
9436 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9437   static const uint64_t GREVMasks[] = {
9438       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9439       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9440 
9441   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9442     unsigned Shift = 1 << Stage;
9443     if (ShAmt & Shift) {
9444       uint64_t Mask = GREVMasks[Stage];
9445       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9446       if (IsGORC)
9447         Res |= x;
9448       x = Res;
9449     }
9450   }
9451 
9452   return x;
9453 }
9454 
9455 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9456                                                         KnownBits &Known,
9457                                                         const APInt &DemandedElts,
9458                                                         const SelectionDAG &DAG,
9459                                                         unsigned Depth) const {
9460   unsigned BitWidth = Known.getBitWidth();
9461   unsigned Opc = Op.getOpcode();
9462   assert((Opc >= ISD::BUILTIN_OP_END ||
9463           Opc == ISD::INTRINSIC_WO_CHAIN ||
9464           Opc == ISD::INTRINSIC_W_CHAIN ||
9465           Opc == ISD::INTRINSIC_VOID) &&
9466          "Should use MaskedValueIsZero if you don't know whether Op"
9467          " is a target node!");
9468 
9469   Known.resetAll();
9470   switch (Opc) {
9471   default: break;
9472   case RISCVISD::SELECT_CC: {
9473     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9474     // If we don't know any bits, early out.
9475     if (Known.isUnknown())
9476       break;
9477     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9478 
9479     // Only known if known in both the LHS and RHS.
9480     Known = KnownBits::commonBits(Known, Known2);
9481     break;
9482   }
9483   case RISCVISD::REMUW: {
9484     KnownBits Known2;
9485     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9486     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9487     // We only care about the lower 32 bits.
9488     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9489     // Restore the original width by sign extending.
9490     Known = Known.sext(BitWidth);
9491     break;
9492   }
9493   case RISCVISD::DIVUW: {
9494     KnownBits Known2;
9495     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9496     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9497     // We only care about the lower 32 bits.
9498     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9499     // Restore the original width by sign extending.
9500     Known = Known.sext(BitWidth);
9501     break;
9502   }
9503   case RISCVISD::CTZW: {
9504     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9505     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9506     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9507     Known.Zero.setBitsFrom(LowBits);
9508     break;
9509   }
9510   case RISCVISD::CLZW: {
9511     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9512     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9513     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9514     Known.Zero.setBitsFrom(LowBits);
9515     break;
9516   }
9517   case RISCVISD::GREV:
9518   case RISCVISD::GORC: {
9519     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9520       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9521       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9522       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9523       // To compute zeros, we need to invert the value and invert it back after.
9524       Known.Zero =
9525           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9526       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9527     }
9528     break;
9529   }
9530   case RISCVISD::READ_VLENB: {
9531     // We can use the minimum and maximum VLEN values to bound VLENB.  We
9532     // know VLEN must be a power of two.
9533     const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8;
9534     const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8;
9535     assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?");
9536     Known.Zero.setLowBits(Log2_32(MinVLenB));
9537     Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1);
9538     if (MaxVLenB == MinVLenB)
9539       Known.One.setBit(Log2_32(MinVLenB));
9540     break;
9541   }
9542   case ISD::INTRINSIC_W_CHAIN:
9543   case ISD::INTRINSIC_WO_CHAIN: {
9544     unsigned IntNo =
9545         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9546     switch (IntNo) {
9547     default:
9548       // We can't do anything for most intrinsics.
9549       break;
9550     case Intrinsic::riscv_vsetvli:
9551     case Intrinsic::riscv_vsetvlimax:
9552     case Intrinsic::riscv_vsetvli_opt:
9553     case Intrinsic::riscv_vsetvlimax_opt:
9554       // Assume that VL output is positive and would fit in an int32_t.
9555       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9556       if (BitWidth >= 32)
9557         Known.Zero.setBitsFrom(31);
9558       break;
9559     }
9560     break;
9561   }
9562   }
9563 }
9564 
9565 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9566     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9567     unsigned Depth) const {
9568   switch (Op.getOpcode()) {
9569   default:
9570     break;
9571   case RISCVISD::SELECT_CC: {
9572     unsigned Tmp =
9573         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9574     if (Tmp == 1) return 1;  // Early out.
9575     unsigned Tmp2 =
9576         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9577     return std::min(Tmp, Tmp2);
9578   }
9579   case RISCVISD::SLLW:
9580   case RISCVISD::SRAW:
9581   case RISCVISD::SRLW:
9582   case RISCVISD::DIVW:
9583   case RISCVISD::DIVUW:
9584   case RISCVISD::REMUW:
9585   case RISCVISD::ROLW:
9586   case RISCVISD::RORW:
9587   case RISCVISD::GREVW:
9588   case RISCVISD::GORCW:
9589   case RISCVISD::FSLW:
9590   case RISCVISD::FSRW:
9591   case RISCVISD::SHFLW:
9592   case RISCVISD::UNSHFLW:
9593   case RISCVISD::BCOMPRESSW:
9594   case RISCVISD::BDECOMPRESSW:
9595   case RISCVISD::BFPW:
9596   case RISCVISD::FCVT_W_RV64:
9597   case RISCVISD::FCVT_WU_RV64:
9598   case RISCVISD::STRICT_FCVT_W_RV64:
9599   case RISCVISD::STRICT_FCVT_WU_RV64:
9600     // TODO: As the result is sign-extended, this is conservatively correct. A
9601     // more precise answer could be calculated for SRAW depending on known
9602     // bits in the shift amount.
9603     return 33;
9604   case RISCVISD::SHFL:
9605   case RISCVISD::UNSHFL: {
9606     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9607     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9608     // will stay within the upper 32 bits. If there were more than 32 sign bits
9609     // before there will be at least 33 sign bits after.
9610     if (Op.getValueType() == MVT::i64 &&
9611         isa<ConstantSDNode>(Op.getOperand(1)) &&
9612         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9613       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9614       if (Tmp > 32)
9615         return 33;
9616     }
9617     break;
9618   }
9619   case RISCVISD::VMV_X_S: {
9620     // The number of sign bits of the scalar result is computed by obtaining the
9621     // element type of the input vector operand, subtracting its width from the
9622     // XLEN, and then adding one (sign bit within the element type). If the
9623     // element type is wider than XLen, the least-significant XLEN bits are
9624     // taken.
9625     unsigned XLen = Subtarget.getXLen();
9626     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9627     if (EltBits <= XLen)
9628       return XLen - EltBits + 1;
9629     break;
9630   }
9631   }
9632 
9633   return 1;
9634 }
9635 
9636 const Constant *
9637 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9638   assert(Ld && "Unexpected null LoadSDNode");
9639   if (!ISD::isNormalLoad(Ld))
9640     return nullptr;
9641 
9642   SDValue Ptr = Ld->getBasePtr();
9643 
9644   // Only constant pools with no offset are supported.
9645   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9646     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9647     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9648         CNode->getOffset() != 0)
9649       return nullptr;
9650 
9651     return CNode;
9652   };
9653 
9654   // Simple case, LLA.
9655   if (Ptr.getOpcode() == RISCVISD::LLA) {
9656     auto *CNode = GetSupportedConstantPool(Ptr);
9657     if (!CNode || CNode->getTargetFlags() != 0)
9658       return nullptr;
9659 
9660     return CNode->getConstVal();
9661   }
9662 
9663   // Look for a HI and ADD_LO pair.
9664   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9665       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9666     return nullptr;
9667 
9668   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9669   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9670 
9671   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9672       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9673     return nullptr;
9674 
9675   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9676     return nullptr;
9677 
9678   return CNodeLo->getConstVal();
9679 }
9680 
9681 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9682                                                   MachineBasicBlock *BB) {
9683   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9684 
9685   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9686   // Should the count have wrapped while it was being read, we need to try
9687   // again.
9688   // ...
9689   // read:
9690   // rdcycleh x3 # load high word of cycle
9691   // rdcycle  x2 # load low word of cycle
9692   // rdcycleh x4 # load high word of cycle
9693   // bne x3, x4, read # check if high word reads match, otherwise try again
9694   // ...
9695 
9696   MachineFunction &MF = *BB->getParent();
9697   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9698   MachineFunction::iterator It = ++BB->getIterator();
9699 
9700   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9701   MF.insert(It, LoopMBB);
9702 
9703   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9704   MF.insert(It, DoneMBB);
9705 
9706   // Transfer the remainder of BB and its successor edges to DoneMBB.
9707   DoneMBB->splice(DoneMBB->begin(), BB,
9708                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9709   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9710 
9711   BB->addSuccessor(LoopMBB);
9712 
9713   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9714   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9715   Register LoReg = MI.getOperand(0).getReg();
9716   Register HiReg = MI.getOperand(1).getReg();
9717   DebugLoc DL = MI.getDebugLoc();
9718 
9719   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9720   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9721       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9722       .addReg(RISCV::X0);
9723   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9724       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9725       .addReg(RISCV::X0);
9726   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9727       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9728       .addReg(RISCV::X0);
9729 
9730   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9731       .addReg(HiReg)
9732       .addReg(ReadAgainReg)
9733       .addMBB(LoopMBB);
9734 
9735   LoopMBB->addSuccessor(LoopMBB);
9736   LoopMBB->addSuccessor(DoneMBB);
9737 
9738   MI.eraseFromParent();
9739 
9740   return DoneMBB;
9741 }
9742 
9743 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9744                                              MachineBasicBlock *BB) {
9745   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9746 
9747   MachineFunction &MF = *BB->getParent();
9748   DebugLoc DL = MI.getDebugLoc();
9749   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9750   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9751   Register LoReg = MI.getOperand(0).getReg();
9752   Register HiReg = MI.getOperand(1).getReg();
9753   Register SrcReg = MI.getOperand(2).getReg();
9754   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9755   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9756 
9757   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9758                           RI);
9759   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9760   MachineMemOperand *MMOLo =
9761       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9762   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9763       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9764   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9765       .addFrameIndex(FI)
9766       .addImm(0)
9767       .addMemOperand(MMOLo);
9768   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9769       .addFrameIndex(FI)
9770       .addImm(4)
9771       .addMemOperand(MMOHi);
9772   MI.eraseFromParent(); // The pseudo instruction is gone now.
9773   return BB;
9774 }
9775 
9776 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9777                                                  MachineBasicBlock *BB) {
9778   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9779          "Unexpected instruction");
9780 
9781   MachineFunction &MF = *BB->getParent();
9782   DebugLoc DL = MI.getDebugLoc();
9783   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9784   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9785   Register DstReg = MI.getOperand(0).getReg();
9786   Register LoReg = MI.getOperand(1).getReg();
9787   Register HiReg = MI.getOperand(2).getReg();
9788   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9789   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9790 
9791   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9792   MachineMemOperand *MMOLo =
9793       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9794   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9795       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9796   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9797       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9798       .addFrameIndex(FI)
9799       .addImm(0)
9800       .addMemOperand(MMOLo);
9801   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9802       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9803       .addFrameIndex(FI)
9804       .addImm(4)
9805       .addMemOperand(MMOHi);
9806   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9807   MI.eraseFromParent(); // The pseudo instruction is gone now.
9808   return BB;
9809 }
9810 
9811 static bool isSelectPseudo(MachineInstr &MI) {
9812   switch (MI.getOpcode()) {
9813   default:
9814     return false;
9815   case RISCV::Select_GPR_Using_CC_GPR:
9816   case RISCV::Select_FPR16_Using_CC_GPR:
9817   case RISCV::Select_FPR32_Using_CC_GPR:
9818   case RISCV::Select_FPR64_Using_CC_GPR:
9819     return true;
9820   }
9821 }
9822 
9823 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9824                                         unsigned RelOpcode, unsigned EqOpcode,
9825                                         const RISCVSubtarget &Subtarget) {
9826   DebugLoc DL = MI.getDebugLoc();
9827   Register DstReg = MI.getOperand(0).getReg();
9828   Register Src1Reg = MI.getOperand(1).getReg();
9829   Register Src2Reg = MI.getOperand(2).getReg();
9830   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9831   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9832   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9833 
9834   // Save the current FFLAGS.
9835   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9836 
9837   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9838                  .addReg(Src1Reg)
9839                  .addReg(Src2Reg);
9840   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9841     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9842 
9843   // Restore the FFLAGS.
9844   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9845       .addReg(SavedFFlags, RegState::Kill);
9846 
9847   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9848   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9849                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9850                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9851   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9852     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9853 
9854   // Erase the pseudoinstruction.
9855   MI.eraseFromParent();
9856   return BB;
9857 }
9858 
9859 static MachineBasicBlock *
9860 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second,
9861                           MachineBasicBlock *ThisMBB,
9862                           const RISCVSubtarget &Subtarget) {
9863   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)
9864   // Without this, custom-inserter would have generated:
9865   //
9866   //   A
9867   //   | \
9868   //   |  B
9869   //   | /
9870   //   C
9871   //   | \
9872   //   |  D
9873   //   | /
9874   //   E
9875   //
9876   // A: X = ...; Y = ...
9877   // B: empty
9878   // C: Z = PHI [X, A], [Y, B]
9879   // D: empty
9880   // E: PHI [X, C], [Z, D]
9881   //
9882   // If we lower both Select_FPRX_ in a single step, we can instead generate:
9883   //
9884   //   A
9885   //   | \
9886   //   |  C
9887   //   | /|
9888   //   |/ |
9889   //   |  |
9890   //   |  D
9891   //   | /
9892   //   E
9893   //
9894   // A: X = ...; Y = ...
9895   // D: empty
9896   // E: PHI [X, A], [X, C], [Y, D]
9897 
9898   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9899   const DebugLoc &DL = First.getDebugLoc();
9900   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
9901   MachineFunction *F = ThisMBB->getParent();
9902   MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903   MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB);
9904   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9905   MachineFunction::iterator It = ++ThisMBB->getIterator();
9906   F->insert(It, FirstMBB);
9907   F->insert(It, SecondMBB);
9908   F->insert(It, SinkMBB);
9909 
9910   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
9911   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
9912                   std::next(MachineBasicBlock::iterator(First)),
9913                   ThisMBB->end());
9914   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
9915 
9916   // Fallthrough block for ThisMBB.
9917   ThisMBB->addSuccessor(FirstMBB);
9918   // Fallthrough block for FirstMBB.
9919   FirstMBB->addSuccessor(SecondMBB);
9920   ThisMBB->addSuccessor(SinkMBB);
9921   FirstMBB->addSuccessor(SinkMBB);
9922   // This is fallthrough.
9923   SecondMBB->addSuccessor(SinkMBB);
9924 
9925   auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm());
9926   Register FLHS = First.getOperand(1).getReg();
9927   Register FRHS = First.getOperand(2).getReg();
9928   // Insert appropriate branch.
9929   BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC))
9930       .addReg(FLHS)
9931       .addReg(FRHS)
9932       .addMBB(SinkMBB);
9933 
9934   Register SLHS = Second.getOperand(1).getReg();
9935   Register SRHS = Second.getOperand(2).getReg();
9936   Register Op1Reg4 = First.getOperand(4).getReg();
9937   Register Op1Reg5 = First.getOperand(5).getReg();
9938 
9939   auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm());
9940   // Insert appropriate branch.
9941   BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC))
9942       .addReg(SLHS)
9943       .addReg(SRHS)
9944       .addMBB(SinkMBB);
9945 
9946   Register DestReg = Second.getOperand(0).getReg();
9947   Register Op2Reg4 = Second.getOperand(4).getReg();
9948   BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg)
9949       .addReg(Op2Reg4)
9950       .addMBB(ThisMBB)
9951       .addReg(Op1Reg4)
9952       .addMBB(FirstMBB)
9953       .addReg(Op1Reg5)
9954       .addMBB(SecondMBB);
9955 
9956   // Now remove the Select_FPRX_s.
9957   First.eraseFromParent();
9958   Second.eraseFromParent();
9959   return SinkMBB;
9960 }
9961 
9962 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9963                                            MachineBasicBlock *BB,
9964                                            const RISCVSubtarget &Subtarget) {
9965   // To "insert" Select_* instructions, we actually have to insert the triangle
9966   // control-flow pattern.  The incoming instructions know the destination vreg
9967   // to set, the condition code register to branch on, the true/false values to
9968   // select between, and the condcode to use to select the appropriate branch.
9969   //
9970   // We produce the following control flow:
9971   //     HeadMBB
9972   //     |  \
9973   //     |  IfFalseMBB
9974   //     | /
9975   //    TailMBB
9976   //
9977   // When we find a sequence of selects we attempt to optimize their emission
9978   // by sharing the control flow. Currently we only handle cases where we have
9979   // multiple selects with the exact same condition (same LHS, RHS and CC).
9980   // The selects may be interleaved with other instructions if the other
9981   // instructions meet some requirements we deem safe:
9982   // - They are debug instructions. Otherwise,
9983   // - They do not have side-effects, do not access memory and their inputs do
9984   //   not depend on the results of the select pseudo-instructions.
9985   // The TrueV/FalseV operands of the selects cannot depend on the result of
9986   // previous selects in the sequence.
9987   // These conditions could be further relaxed. See the X86 target for a
9988   // related approach and more information.
9989   //
9990   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5))
9991   // is checked here and handled by a separate function -
9992   // EmitLoweredCascadedSelect.
9993   Register LHS = MI.getOperand(1).getReg();
9994   Register RHS = MI.getOperand(2).getReg();
9995   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9996 
9997   SmallVector<MachineInstr *, 4> SelectDebugValues;
9998   SmallSet<Register, 4> SelectDests;
9999   SelectDests.insert(MI.getOperand(0).getReg());
10000 
10001   MachineInstr *LastSelectPseudo = &MI;
10002   auto Next = next_nodbg(MI.getIterator(), BB->instr_end());
10003   if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() &&
10004       Next->getOpcode() == MI.getOpcode() &&
10005       Next->getOperand(5).getReg() == MI.getOperand(0).getReg() &&
10006       Next->getOperand(5).isKill()) {
10007     return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget);
10008   }
10009 
10010   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
10011        SequenceMBBI != E; ++SequenceMBBI) {
10012     if (SequenceMBBI->isDebugInstr())
10013       continue;
10014     if (isSelectPseudo(*SequenceMBBI)) {
10015       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
10016           SequenceMBBI->getOperand(2).getReg() != RHS ||
10017           SequenceMBBI->getOperand(3).getImm() != CC ||
10018           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
10019           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
10020         break;
10021       LastSelectPseudo = &*SequenceMBBI;
10022       SequenceMBBI->collectDebugValues(SelectDebugValues);
10023       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
10024     } else {
10025       if (SequenceMBBI->hasUnmodeledSideEffects() ||
10026           SequenceMBBI->mayLoadOrStore())
10027         break;
10028       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
10029             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
10030           }))
10031         break;
10032     }
10033   }
10034 
10035   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
10036   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10037   DebugLoc DL = MI.getDebugLoc();
10038   MachineFunction::iterator I = ++BB->getIterator();
10039 
10040   MachineBasicBlock *HeadMBB = BB;
10041   MachineFunction *F = BB->getParent();
10042   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
10043   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
10044 
10045   F->insert(I, IfFalseMBB);
10046   F->insert(I, TailMBB);
10047 
10048   // Transfer debug instructions associated with the selects to TailMBB.
10049   for (MachineInstr *DebugInstr : SelectDebugValues) {
10050     TailMBB->push_back(DebugInstr->removeFromParent());
10051   }
10052 
10053   // Move all instructions after the sequence to TailMBB.
10054   TailMBB->splice(TailMBB->end(), HeadMBB,
10055                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
10056   // Update machine-CFG edges by transferring all successors of the current
10057   // block to the new block which will contain the Phi nodes for the selects.
10058   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
10059   // Set the successors for HeadMBB.
10060   HeadMBB->addSuccessor(IfFalseMBB);
10061   HeadMBB->addSuccessor(TailMBB);
10062 
10063   // Insert appropriate branch.
10064   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
10065     .addReg(LHS)
10066     .addReg(RHS)
10067     .addMBB(TailMBB);
10068 
10069   // IfFalseMBB just falls through to TailMBB.
10070   IfFalseMBB->addSuccessor(TailMBB);
10071 
10072   // Create PHIs for all of the select pseudo-instructions.
10073   auto SelectMBBI = MI.getIterator();
10074   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
10075   auto InsertionPoint = TailMBB->begin();
10076   while (SelectMBBI != SelectEnd) {
10077     auto Next = std::next(SelectMBBI);
10078     if (isSelectPseudo(*SelectMBBI)) {
10079       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
10080       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
10081               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
10082           .addReg(SelectMBBI->getOperand(4).getReg())
10083           .addMBB(HeadMBB)
10084           .addReg(SelectMBBI->getOperand(5).getReg())
10085           .addMBB(IfFalseMBB);
10086       SelectMBBI->eraseFromParent();
10087     }
10088     SelectMBBI = Next;
10089   }
10090 
10091   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
10092   return TailMBB;
10093 }
10094 
10095 MachineBasicBlock *
10096 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10097                                                  MachineBasicBlock *BB) const {
10098   switch (MI.getOpcode()) {
10099   default:
10100     llvm_unreachable("Unexpected instr type to insert");
10101   case RISCV::ReadCycleWide:
10102     assert(!Subtarget.is64Bit() &&
10103            "ReadCycleWrite is only to be used on riscv32");
10104     return emitReadCycleWidePseudo(MI, BB);
10105   case RISCV::Select_GPR_Using_CC_GPR:
10106   case RISCV::Select_FPR16_Using_CC_GPR:
10107   case RISCV::Select_FPR32_Using_CC_GPR:
10108   case RISCV::Select_FPR64_Using_CC_GPR:
10109     return emitSelectPseudo(MI, BB, Subtarget);
10110   case RISCV::BuildPairF64Pseudo:
10111     return emitBuildPairF64Pseudo(MI, BB);
10112   case RISCV::SplitF64Pseudo:
10113     return emitSplitF64Pseudo(MI, BB);
10114   case RISCV::PseudoQuietFLE_H:
10115     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
10116   case RISCV::PseudoQuietFLT_H:
10117     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
10118   case RISCV::PseudoQuietFLE_S:
10119     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
10120   case RISCV::PseudoQuietFLT_S:
10121     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
10122   case RISCV::PseudoQuietFLE_D:
10123     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
10124   case RISCV::PseudoQuietFLT_D:
10125     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
10126   }
10127 }
10128 
10129 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10130                                                         SDNode *Node) const {
10131   // Add FRM dependency to any instructions with dynamic rounding mode.
10132   unsigned Opc = MI.getOpcode();
10133   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
10134   if (Idx < 0)
10135     return;
10136   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
10137     return;
10138   // If the instruction already reads FRM, don't add another read.
10139   if (MI.readsRegister(RISCV::FRM))
10140     return;
10141   MI.addOperand(
10142       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
10143 }
10144 
10145 // Calling Convention Implementation.
10146 // The expectations for frontend ABI lowering vary from target to target.
10147 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
10148 // details, but this is a longer term goal. For now, we simply try to keep the
10149 // role of the frontend as simple and well-defined as possible. The rules can
10150 // be summarised as:
10151 // * Never split up large scalar arguments. We handle them here.
10152 // * If a hardfloat calling convention is being used, and the struct may be
10153 // passed in a pair of registers (fp+fp, int+fp), and both registers are
10154 // available, then pass as two separate arguments. If either the GPRs or FPRs
10155 // are exhausted, then pass according to the rule below.
10156 // * If a struct could never be passed in registers or directly in a stack
10157 // slot (as it is larger than 2*XLEN and the floating point rules don't
10158 // apply), then pass it using a pointer with the byval attribute.
10159 // * If a struct is less than 2*XLEN, then coerce to either a two-element
10160 // word-sized array or a 2*XLEN scalar (depending on alignment).
10161 // * The frontend can determine whether a struct is returned by reference or
10162 // not based on its size and fields. If it will be returned by reference, the
10163 // frontend must modify the prototype so a pointer with the sret annotation is
10164 // passed as the first argument. This is not necessary for large scalar
10165 // returns.
10166 // * Struct return values and varargs should be coerced to structs containing
10167 // register-size fields in the same situations they would be for fixed
10168 // arguments.
10169 
10170 static const MCPhysReg ArgGPRs[] = {
10171   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
10172   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
10173 };
10174 static const MCPhysReg ArgFPR16s[] = {
10175   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
10176   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
10177 };
10178 static const MCPhysReg ArgFPR32s[] = {
10179   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
10180   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
10181 };
10182 static const MCPhysReg ArgFPR64s[] = {
10183   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
10184   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
10185 };
10186 // This is an interim calling convention and it may be changed in the future.
10187 static const MCPhysReg ArgVRs[] = {
10188     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
10189     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
10190     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
10191 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
10192                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
10193                                      RISCV::V20M2, RISCV::V22M2};
10194 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
10195                                      RISCV::V20M4};
10196 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
10197 
10198 // Pass a 2*XLEN argument that has been split into two XLEN values through
10199 // registers or the stack as necessary.
10200 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
10201                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
10202                                 MVT ValVT2, MVT LocVT2,
10203                                 ISD::ArgFlagsTy ArgFlags2) {
10204   unsigned XLenInBytes = XLen / 8;
10205   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10206     // At least one half can be passed via register.
10207     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
10208                                      VA1.getLocVT(), CCValAssign::Full));
10209   } else {
10210     // Both halves must be passed on the stack, with proper alignment.
10211     Align StackAlign =
10212         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
10213     State.addLoc(
10214         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
10215                             State.AllocateStack(XLenInBytes, StackAlign),
10216                             VA1.getLocVT(), CCValAssign::Full));
10217     State.addLoc(CCValAssign::getMem(
10218         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10219         LocVT2, CCValAssign::Full));
10220     return false;
10221   }
10222 
10223   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10224     // The second half can also be passed via register.
10225     State.addLoc(
10226         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
10227   } else {
10228     // The second half is passed via the stack, without additional alignment.
10229     State.addLoc(CCValAssign::getMem(
10230         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10231         LocVT2, CCValAssign::Full));
10232   }
10233 
10234   return false;
10235 }
10236 
10237 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
10238                                Optional<unsigned> FirstMaskArgument,
10239                                CCState &State, const RISCVTargetLowering &TLI) {
10240   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
10241   if (RC == &RISCV::VRRegClass) {
10242     // Assign the first mask argument to V0.
10243     // This is an interim calling convention and it may be changed in the
10244     // future.
10245     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
10246       return State.AllocateReg(RISCV::V0);
10247     return State.AllocateReg(ArgVRs);
10248   }
10249   if (RC == &RISCV::VRM2RegClass)
10250     return State.AllocateReg(ArgVRM2s);
10251   if (RC == &RISCV::VRM4RegClass)
10252     return State.AllocateReg(ArgVRM4s);
10253   if (RC == &RISCV::VRM8RegClass)
10254     return State.AllocateReg(ArgVRM8s);
10255   llvm_unreachable("Unhandled register class for ValueType");
10256 }
10257 
10258 // Implements the RISC-V calling convention. Returns true upon failure.
10259 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
10260                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
10261                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
10262                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
10263                      Optional<unsigned> FirstMaskArgument) {
10264   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
10265   assert(XLen == 32 || XLen == 64);
10266   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
10267 
10268   // Any return value split in to more than two values can't be returned
10269   // directly. Vectors are returned via the available vector registers.
10270   if (!LocVT.isVector() && IsRet && ValNo > 1)
10271     return true;
10272 
10273   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
10274   // variadic argument, or if no F16/F32 argument registers are available.
10275   bool UseGPRForF16_F32 = true;
10276   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
10277   // variadic argument, or if no F64 argument registers are available.
10278   bool UseGPRForF64 = true;
10279 
10280   switch (ABI) {
10281   default:
10282     llvm_unreachable("Unexpected ABI");
10283   case RISCVABI::ABI_ILP32:
10284   case RISCVABI::ABI_LP64:
10285     break;
10286   case RISCVABI::ABI_ILP32F:
10287   case RISCVABI::ABI_LP64F:
10288     UseGPRForF16_F32 = !IsFixed;
10289     break;
10290   case RISCVABI::ABI_ILP32D:
10291   case RISCVABI::ABI_LP64D:
10292     UseGPRForF16_F32 = !IsFixed;
10293     UseGPRForF64 = !IsFixed;
10294     break;
10295   }
10296 
10297   // FPR16, FPR32, and FPR64 alias each other.
10298   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
10299     UseGPRForF16_F32 = true;
10300     UseGPRForF64 = true;
10301   }
10302 
10303   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
10304   // similar local variables rather than directly checking against the target
10305   // ABI.
10306 
10307   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
10308     LocVT = XLenVT;
10309     LocInfo = CCValAssign::BCvt;
10310   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
10311     LocVT = MVT::i64;
10312     LocInfo = CCValAssign::BCvt;
10313   }
10314 
10315   // If this is a variadic argument, the RISC-V calling convention requires
10316   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
10317   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
10318   // be used regardless of whether the original argument was split during
10319   // legalisation or not. The argument will not be passed by registers if the
10320   // original type is larger than 2*XLEN, so the register alignment rule does
10321   // not apply.
10322   unsigned TwoXLenInBytes = (2 * XLen) / 8;
10323   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
10324       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
10325     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10326     // Skip 'odd' register if necessary.
10327     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
10328       State.AllocateReg(ArgGPRs);
10329   }
10330 
10331   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10332   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10333       State.getPendingArgFlags();
10334 
10335   assert(PendingLocs.size() == PendingArgFlags.size() &&
10336          "PendingLocs and PendingArgFlags out of sync");
10337 
10338   // Handle passing f64 on RV32D with a soft float ABI or when floating point
10339   // registers are exhausted.
10340   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
10341     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
10342            "Can't lower f64 if it is split");
10343     // Depending on available argument GPRS, f64 may be passed in a pair of
10344     // GPRs, split between a GPR and the stack, or passed completely on the
10345     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10346     // cases.
10347     Register Reg = State.AllocateReg(ArgGPRs);
10348     LocVT = MVT::i32;
10349     if (!Reg) {
10350       unsigned StackOffset = State.AllocateStack(8, Align(8));
10351       State.addLoc(
10352           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10353       return false;
10354     }
10355     if (!State.AllocateReg(ArgGPRs))
10356       State.AllocateStack(4, Align(4));
10357     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10358     return false;
10359   }
10360 
10361   // Fixed-length vectors are located in the corresponding scalable-vector
10362   // container types.
10363   if (ValVT.isFixedLengthVector())
10364     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10365 
10366   // Split arguments might be passed indirectly, so keep track of the pending
10367   // values. Split vectors are passed via a mix of registers and indirectly, so
10368   // treat them as we would any other argument.
10369   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10370     LocVT = XLenVT;
10371     LocInfo = CCValAssign::Indirect;
10372     PendingLocs.push_back(
10373         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10374     PendingArgFlags.push_back(ArgFlags);
10375     if (!ArgFlags.isSplitEnd()) {
10376       return false;
10377     }
10378   }
10379 
10380   // If the split argument only had two elements, it should be passed directly
10381   // in registers or on the stack.
10382   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10383       PendingLocs.size() <= 2) {
10384     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10385     // Apply the normal calling convention rules to the first half of the
10386     // split argument.
10387     CCValAssign VA = PendingLocs[0];
10388     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10389     PendingLocs.clear();
10390     PendingArgFlags.clear();
10391     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10392                                ArgFlags);
10393   }
10394 
10395   // Allocate to a register if possible, or else a stack slot.
10396   Register Reg;
10397   unsigned StoreSizeBytes = XLen / 8;
10398   Align StackAlign = Align(XLen / 8);
10399 
10400   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10401     Reg = State.AllocateReg(ArgFPR16s);
10402   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10403     Reg = State.AllocateReg(ArgFPR32s);
10404   else if (ValVT == MVT::f64 && !UseGPRForF64)
10405     Reg = State.AllocateReg(ArgFPR64s);
10406   else if (ValVT.isVector()) {
10407     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10408     if (!Reg) {
10409       // For return values, the vector must be passed fully via registers or
10410       // via the stack.
10411       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10412       // but we're using all of them.
10413       if (IsRet)
10414         return true;
10415       // Try using a GPR to pass the address
10416       if ((Reg = State.AllocateReg(ArgGPRs))) {
10417         LocVT = XLenVT;
10418         LocInfo = CCValAssign::Indirect;
10419       } else if (ValVT.isScalableVector()) {
10420         LocVT = XLenVT;
10421         LocInfo = CCValAssign::Indirect;
10422       } else {
10423         // Pass fixed-length vectors on the stack.
10424         LocVT = ValVT;
10425         StoreSizeBytes = ValVT.getStoreSize();
10426         // Align vectors to their element sizes, being careful for vXi1
10427         // vectors.
10428         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10429       }
10430     }
10431   } else {
10432     Reg = State.AllocateReg(ArgGPRs);
10433   }
10434 
10435   unsigned StackOffset =
10436       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10437 
10438   // If we reach this point and PendingLocs is non-empty, we must be at the
10439   // end of a split argument that must be passed indirectly.
10440   if (!PendingLocs.empty()) {
10441     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10442     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10443 
10444     for (auto &It : PendingLocs) {
10445       if (Reg)
10446         It.convertToReg(Reg);
10447       else
10448         It.convertToMem(StackOffset);
10449       State.addLoc(It);
10450     }
10451     PendingLocs.clear();
10452     PendingArgFlags.clear();
10453     return false;
10454   }
10455 
10456   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10457           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10458          "Expected an XLenVT or vector types at this stage");
10459 
10460   if (Reg) {
10461     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10462     return false;
10463   }
10464 
10465   // When a floating-point value is passed on the stack, no bit-conversion is
10466   // needed.
10467   if (ValVT.isFloatingPoint()) {
10468     LocVT = ValVT;
10469     LocInfo = CCValAssign::Full;
10470   }
10471   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10472   return false;
10473 }
10474 
10475 template <typename ArgTy>
10476 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10477   for (const auto &ArgIdx : enumerate(Args)) {
10478     MVT ArgVT = ArgIdx.value().VT;
10479     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10480       return ArgIdx.index();
10481   }
10482   return None;
10483 }
10484 
10485 void RISCVTargetLowering::analyzeInputArgs(
10486     MachineFunction &MF, CCState &CCInfo,
10487     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10488     RISCVCCAssignFn Fn) const {
10489   unsigned NumArgs = Ins.size();
10490   FunctionType *FType = MF.getFunction().getFunctionType();
10491 
10492   Optional<unsigned> FirstMaskArgument;
10493   if (Subtarget.hasVInstructions())
10494     FirstMaskArgument = preAssignMask(Ins);
10495 
10496   for (unsigned i = 0; i != NumArgs; ++i) {
10497     MVT ArgVT = Ins[i].VT;
10498     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10499 
10500     Type *ArgTy = nullptr;
10501     if (IsRet)
10502       ArgTy = FType->getReturnType();
10503     else if (Ins[i].isOrigArg())
10504       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10505 
10506     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10507     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10508            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10509            FirstMaskArgument)) {
10510       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10511                         << EVT(ArgVT).getEVTString() << '\n');
10512       llvm_unreachable(nullptr);
10513     }
10514   }
10515 }
10516 
10517 void RISCVTargetLowering::analyzeOutputArgs(
10518     MachineFunction &MF, CCState &CCInfo,
10519     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10520     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10521   unsigned NumArgs = Outs.size();
10522 
10523   Optional<unsigned> FirstMaskArgument;
10524   if (Subtarget.hasVInstructions())
10525     FirstMaskArgument = preAssignMask(Outs);
10526 
10527   for (unsigned i = 0; i != NumArgs; i++) {
10528     MVT ArgVT = Outs[i].VT;
10529     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10530     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10531 
10532     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10533     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10534            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10535            FirstMaskArgument)) {
10536       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10537                         << EVT(ArgVT).getEVTString() << "\n");
10538       llvm_unreachable(nullptr);
10539     }
10540   }
10541 }
10542 
10543 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10544 // values.
10545 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10546                                    const CCValAssign &VA, const SDLoc &DL,
10547                                    const RISCVSubtarget &Subtarget) {
10548   switch (VA.getLocInfo()) {
10549   default:
10550     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10551   case CCValAssign::Full:
10552     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10553       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10554     break;
10555   case CCValAssign::BCvt:
10556     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10557       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10558     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10559       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10560     else
10561       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10562     break;
10563   }
10564   return Val;
10565 }
10566 
10567 // The caller is responsible for loading the full value if the argument is
10568 // passed with CCValAssign::Indirect.
10569 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10570                                 const CCValAssign &VA, const SDLoc &DL,
10571                                 const RISCVTargetLowering &TLI) {
10572   MachineFunction &MF = DAG.getMachineFunction();
10573   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10574   EVT LocVT = VA.getLocVT();
10575   SDValue Val;
10576   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10577   Register VReg = RegInfo.createVirtualRegister(RC);
10578   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10579   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10580 
10581   if (VA.getLocInfo() == CCValAssign::Indirect)
10582     return Val;
10583 
10584   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10585 }
10586 
10587 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10588                                    const CCValAssign &VA, const SDLoc &DL,
10589                                    const RISCVSubtarget &Subtarget) {
10590   EVT LocVT = VA.getLocVT();
10591 
10592   switch (VA.getLocInfo()) {
10593   default:
10594     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10595   case CCValAssign::Full:
10596     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10597       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10598     break;
10599   case CCValAssign::BCvt:
10600     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10601       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10602     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10603       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10604     else
10605       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10606     break;
10607   }
10608   return Val;
10609 }
10610 
10611 // The caller is responsible for loading the full value if the argument is
10612 // passed with CCValAssign::Indirect.
10613 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10614                                 const CCValAssign &VA, const SDLoc &DL) {
10615   MachineFunction &MF = DAG.getMachineFunction();
10616   MachineFrameInfo &MFI = MF.getFrameInfo();
10617   EVT LocVT = VA.getLocVT();
10618   EVT ValVT = VA.getValVT();
10619   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10620   if (ValVT.isScalableVector()) {
10621     // When the value is a scalable vector, we save the pointer which points to
10622     // the scalable vector value in the stack. The ValVT will be the pointer
10623     // type, instead of the scalable vector type.
10624     ValVT = LocVT;
10625   }
10626   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10627                                  /*IsImmutable=*/true);
10628   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10629   SDValue Val;
10630 
10631   ISD::LoadExtType ExtType;
10632   switch (VA.getLocInfo()) {
10633   default:
10634     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10635   case CCValAssign::Full:
10636   case CCValAssign::Indirect:
10637   case CCValAssign::BCvt:
10638     ExtType = ISD::NON_EXTLOAD;
10639     break;
10640   }
10641   Val = DAG.getExtLoad(
10642       ExtType, DL, LocVT, Chain, FIN,
10643       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10644   return Val;
10645 }
10646 
10647 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10648                                        const CCValAssign &VA, const SDLoc &DL) {
10649   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10650          "Unexpected VA");
10651   MachineFunction &MF = DAG.getMachineFunction();
10652   MachineFrameInfo &MFI = MF.getFrameInfo();
10653   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10654 
10655   if (VA.isMemLoc()) {
10656     // f64 is passed on the stack.
10657     int FI =
10658         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10659     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10660     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10661                        MachinePointerInfo::getFixedStack(MF, FI));
10662   }
10663 
10664   assert(VA.isRegLoc() && "Expected register VA assignment");
10665 
10666   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10667   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10668   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10669   SDValue Hi;
10670   if (VA.getLocReg() == RISCV::X17) {
10671     // Second half of f64 is passed on the stack.
10672     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10673     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10674     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10675                      MachinePointerInfo::getFixedStack(MF, FI));
10676   } else {
10677     // Second half of f64 is passed in another GPR.
10678     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10679     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10680     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10681   }
10682   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10683 }
10684 
10685 // FastCC has less than 1% performance improvement for some particular
10686 // benchmark. But theoretically, it may has benenfit for some cases.
10687 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10688                             unsigned ValNo, MVT ValVT, MVT LocVT,
10689                             CCValAssign::LocInfo LocInfo,
10690                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10691                             bool IsFixed, bool IsRet, Type *OrigTy,
10692                             const RISCVTargetLowering &TLI,
10693                             Optional<unsigned> FirstMaskArgument) {
10694 
10695   // X5 and X6 might be used for save-restore libcall.
10696   static const MCPhysReg GPRList[] = {
10697       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10698       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10699       RISCV::X29, RISCV::X30, RISCV::X31};
10700 
10701   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10702     if (unsigned Reg = State.AllocateReg(GPRList)) {
10703       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10704       return false;
10705     }
10706   }
10707 
10708   if (LocVT == MVT::f16) {
10709     static const MCPhysReg FPR16List[] = {
10710         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10711         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10712         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10713         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10714     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10715       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10716       return false;
10717     }
10718   }
10719 
10720   if (LocVT == MVT::f32) {
10721     static const MCPhysReg FPR32List[] = {
10722         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10723         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10724         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10725         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10726     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10727       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10728       return false;
10729     }
10730   }
10731 
10732   if (LocVT == MVT::f64) {
10733     static const MCPhysReg FPR64List[] = {
10734         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10735         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10736         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10737         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10738     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10739       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10740       return false;
10741     }
10742   }
10743 
10744   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10745     unsigned Offset4 = State.AllocateStack(4, Align(4));
10746     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10747     return false;
10748   }
10749 
10750   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10751     unsigned Offset5 = State.AllocateStack(8, Align(8));
10752     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10753     return false;
10754   }
10755 
10756   if (LocVT.isVector()) {
10757     if (unsigned Reg =
10758             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10759       // Fixed-length vectors are located in the corresponding scalable-vector
10760       // container types.
10761       if (ValVT.isFixedLengthVector())
10762         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10763       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10764     } else {
10765       // Try and pass the address via a "fast" GPR.
10766       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10767         LocInfo = CCValAssign::Indirect;
10768         LocVT = TLI.getSubtarget().getXLenVT();
10769         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10770       } else if (ValVT.isFixedLengthVector()) {
10771         auto StackAlign =
10772             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10773         unsigned StackOffset =
10774             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10775         State.addLoc(
10776             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10777       } else {
10778         // Can't pass scalable vectors on the stack.
10779         return true;
10780       }
10781     }
10782 
10783     return false;
10784   }
10785 
10786   return true; // CC didn't match.
10787 }
10788 
10789 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10790                          CCValAssign::LocInfo LocInfo,
10791                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10792 
10793   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10794     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10795     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10796     static const MCPhysReg GPRList[] = {
10797         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10798         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10799     if (unsigned Reg = State.AllocateReg(GPRList)) {
10800       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10801       return false;
10802     }
10803   }
10804 
10805   if (LocVT == MVT::f32) {
10806     // Pass in STG registers: F1, ..., F6
10807     //                        fs0 ... fs5
10808     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10809                                           RISCV::F18_F, RISCV::F19_F,
10810                                           RISCV::F20_F, RISCV::F21_F};
10811     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10812       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10813       return false;
10814     }
10815   }
10816 
10817   if (LocVT == MVT::f64) {
10818     // Pass in STG registers: D1, ..., D6
10819     //                        fs6 ... fs11
10820     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10821                                           RISCV::F24_D, RISCV::F25_D,
10822                                           RISCV::F26_D, RISCV::F27_D};
10823     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10824       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10825       return false;
10826     }
10827   }
10828 
10829   report_fatal_error("No registers left in GHC calling convention");
10830   return true;
10831 }
10832 
10833 // Transform physical registers into virtual registers.
10834 SDValue RISCVTargetLowering::LowerFormalArguments(
10835     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10836     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10837     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10838 
10839   MachineFunction &MF = DAG.getMachineFunction();
10840 
10841   switch (CallConv) {
10842   default:
10843     report_fatal_error("Unsupported calling convention");
10844   case CallingConv::C:
10845   case CallingConv::Fast:
10846     break;
10847   case CallingConv::GHC:
10848     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10849         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10850       report_fatal_error(
10851         "GHC calling convention requires the F and D instruction set extensions");
10852   }
10853 
10854   const Function &Func = MF.getFunction();
10855   if (Func.hasFnAttribute("interrupt")) {
10856     if (!Func.arg_empty())
10857       report_fatal_error(
10858         "Functions with the interrupt attribute cannot have arguments!");
10859 
10860     StringRef Kind =
10861       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10862 
10863     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10864       report_fatal_error(
10865         "Function interrupt attribute argument not supported!");
10866   }
10867 
10868   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10869   MVT XLenVT = Subtarget.getXLenVT();
10870   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10871   // Used with vargs to acumulate store chains.
10872   std::vector<SDValue> OutChains;
10873 
10874   // Assign locations to all of the incoming arguments.
10875   SmallVector<CCValAssign, 16> ArgLocs;
10876   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10877 
10878   if (CallConv == CallingConv::GHC)
10879     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10880   else
10881     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10882                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10883                                                    : CC_RISCV);
10884 
10885   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10886     CCValAssign &VA = ArgLocs[i];
10887     SDValue ArgValue;
10888     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10889     // case.
10890     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10891       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10892     else if (VA.isRegLoc())
10893       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10894     else
10895       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10896 
10897     if (VA.getLocInfo() == CCValAssign::Indirect) {
10898       // If the original argument was split and passed by reference (e.g. i128
10899       // on RV32), we need to load all parts of it here (using the same
10900       // address). Vectors may be partly split to registers and partly to the
10901       // stack, in which case the base address is partly offset and subsequent
10902       // stores are relative to that.
10903       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10904                                    MachinePointerInfo()));
10905       unsigned ArgIndex = Ins[i].OrigArgIndex;
10906       unsigned ArgPartOffset = Ins[i].PartOffset;
10907       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10908       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10909         CCValAssign &PartVA = ArgLocs[i + 1];
10910         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10911         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10912         if (PartVA.getValVT().isScalableVector())
10913           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10914         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10915         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10916                                      MachinePointerInfo()));
10917         ++i;
10918       }
10919       continue;
10920     }
10921     InVals.push_back(ArgValue);
10922   }
10923 
10924   if (IsVarArg) {
10925     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10926     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10927     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10928     MachineFrameInfo &MFI = MF.getFrameInfo();
10929     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10930     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10931 
10932     // Offset of the first variable argument from stack pointer, and size of
10933     // the vararg save area. For now, the varargs save area is either zero or
10934     // large enough to hold a0-a7.
10935     int VaArgOffset, VarArgsSaveSize;
10936 
10937     // If all registers are allocated, then all varargs must be passed on the
10938     // stack and we don't need to save any argregs.
10939     if (ArgRegs.size() == Idx) {
10940       VaArgOffset = CCInfo.getNextStackOffset();
10941       VarArgsSaveSize = 0;
10942     } else {
10943       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10944       VaArgOffset = -VarArgsSaveSize;
10945     }
10946 
10947     // Record the frame index of the first variable argument
10948     // which is a value necessary to VASTART.
10949     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10950     RVFI->setVarArgsFrameIndex(FI);
10951 
10952     // If saving an odd number of registers then create an extra stack slot to
10953     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10954     // offsets to even-numbered registered remain 2*XLEN-aligned.
10955     if (Idx % 2) {
10956       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10957       VarArgsSaveSize += XLenInBytes;
10958     }
10959 
10960     // Copy the integer registers that may have been used for passing varargs
10961     // to the vararg save area.
10962     for (unsigned I = Idx; I < ArgRegs.size();
10963          ++I, VaArgOffset += XLenInBytes) {
10964       const Register Reg = RegInfo.createVirtualRegister(RC);
10965       RegInfo.addLiveIn(ArgRegs[I], Reg);
10966       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10967       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10968       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10969       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10970                                    MachinePointerInfo::getFixedStack(MF, FI));
10971       cast<StoreSDNode>(Store.getNode())
10972           ->getMemOperand()
10973           ->setValue((Value *)nullptr);
10974       OutChains.push_back(Store);
10975     }
10976     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10977   }
10978 
10979   // All stores are grouped in one node to allow the matching between
10980   // the size of Ins and InVals. This only happens for vararg functions.
10981   if (!OutChains.empty()) {
10982     OutChains.push_back(Chain);
10983     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10984   }
10985 
10986   return Chain;
10987 }
10988 
10989 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10990 /// for tail call optimization.
10991 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10992 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10993     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10994     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10995 
10996   auto &Callee = CLI.Callee;
10997   auto CalleeCC = CLI.CallConv;
10998   auto &Outs = CLI.Outs;
10999   auto &Caller = MF.getFunction();
11000   auto CallerCC = Caller.getCallingConv();
11001 
11002   // Exception-handling functions need a special set of instructions to
11003   // indicate a return to the hardware. Tail-calling another function would
11004   // probably break this.
11005   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
11006   // should be expanded as new function attributes are introduced.
11007   if (Caller.hasFnAttribute("interrupt"))
11008     return false;
11009 
11010   // Do not tail call opt if the stack is used to pass parameters.
11011   if (CCInfo.getNextStackOffset() != 0)
11012     return false;
11013 
11014   // Do not tail call opt if any parameters need to be passed indirectly.
11015   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
11016   // passed indirectly. So the address of the value will be passed in a
11017   // register, or if not available, then the address is put on the stack. In
11018   // order to pass indirectly, space on the stack often needs to be allocated
11019   // in order to store the value. In this case the CCInfo.getNextStackOffset()
11020   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
11021   // are passed CCValAssign::Indirect.
11022   for (auto &VA : ArgLocs)
11023     if (VA.getLocInfo() == CCValAssign::Indirect)
11024       return false;
11025 
11026   // Do not tail call opt if either caller or callee uses struct return
11027   // semantics.
11028   auto IsCallerStructRet = Caller.hasStructRetAttr();
11029   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
11030   if (IsCallerStructRet || IsCalleeStructRet)
11031     return false;
11032 
11033   // Externally-defined functions with weak linkage should not be
11034   // tail-called. The behaviour of branch instructions in this situation (as
11035   // used for tail calls) is implementation-defined, so we cannot rely on the
11036   // linker replacing the tail call with a return.
11037   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
11038     const GlobalValue *GV = G->getGlobal();
11039     if (GV->hasExternalWeakLinkage())
11040       return false;
11041   }
11042 
11043   // The callee has to preserve all registers the caller needs to preserve.
11044   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
11045   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
11046   if (CalleeCC != CallerCC) {
11047     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
11048     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
11049       return false;
11050   }
11051 
11052   // Byval parameters hand the function a pointer directly into the stack area
11053   // we want to reuse during a tail call. Working around this *is* possible
11054   // but less efficient and uglier in LowerCall.
11055   for (auto &Arg : Outs)
11056     if (Arg.Flags.isByVal())
11057       return false;
11058 
11059   return true;
11060 }
11061 
11062 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
11063   return DAG.getDataLayout().getPrefTypeAlign(
11064       VT.getTypeForEVT(*DAG.getContext()));
11065 }
11066 
11067 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
11068 // and output parameter nodes.
11069 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
11070                                        SmallVectorImpl<SDValue> &InVals) const {
11071   SelectionDAG &DAG = CLI.DAG;
11072   SDLoc &DL = CLI.DL;
11073   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
11074   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
11075   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
11076   SDValue Chain = CLI.Chain;
11077   SDValue Callee = CLI.Callee;
11078   bool &IsTailCall = CLI.IsTailCall;
11079   CallingConv::ID CallConv = CLI.CallConv;
11080   bool IsVarArg = CLI.IsVarArg;
11081   EVT PtrVT = getPointerTy(DAG.getDataLayout());
11082   MVT XLenVT = Subtarget.getXLenVT();
11083 
11084   MachineFunction &MF = DAG.getMachineFunction();
11085 
11086   // Analyze the operands of the call, assigning locations to each operand.
11087   SmallVector<CCValAssign, 16> ArgLocs;
11088   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
11089 
11090   if (CallConv == CallingConv::GHC)
11091     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
11092   else
11093     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
11094                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
11095                                                     : CC_RISCV);
11096 
11097   // Check if it's really possible to do a tail call.
11098   if (IsTailCall)
11099     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
11100 
11101   if (IsTailCall)
11102     ++NumTailCalls;
11103   else if (CLI.CB && CLI.CB->isMustTailCall())
11104     report_fatal_error("failed to perform tail call elimination on a call "
11105                        "site marked musttail");
11106 
11107   // Get a count of how many bytes are to be pushed on the stack.
11108   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
11109 
11110   // Create local copies for byval args
11111   SmallVector<SDValue, 8> ByValArgs;
11112   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11113     ISD::ArgFlagsTy Flags = Outs[i].Flags;
11114     if (!Flags.isByVal())
11115       continue;
11116 
11117     SDValue Arg = OutVals[i];
11118     unsigned Size = Flags.getByValSize();
11119     Align Alignment = Flags.getNonZeroByValAlign();
11120 
11121     int FI =
11122         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
11123     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11124     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
11125 
11126     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
11127                           /*IsVolatile=*/false,
11128                           /*AlwaysInline=*/false, IsTailCall,
11129                           MachinePointerInfo(), MachinePointerInfo());
11130     ByValArgs.push_back(FIPtr);
11131   }
11132 
11133   if (!IsTailCall)
11134     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
11135 
11136   // Copy argument values to their designated locations.
11137   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
11138   SmallVector<SDValue, 8> MemOpChains;
11139   SDValue StackPtr;
11140   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
11141     CCValAssign &VA = ArgLocs[i];
11142     SDValue ArgValue = OutVals[i];
11143     ISD::ArgFlagsTy Flags = Outs[i].Flags;
11144 
11145     // Handle passing f64 on RV32D with a soft float ABI as a special case.
11146     bool IsF64OnRV32DSoftABI =
11147         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
11148     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
11149       SDValue SplitF64 = DAG.getNode(
11150           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
11151       SDValue Lo = SplitF64.getValue(0);
11152       SDValue Hi = SplitF64.getValue(1);
11153 
11154       Register RegLo = VA.getLocReg();
11155       RegsToPass.push_back(std::make_pair(RegLo, Lo));
11156 
11157       if (RegLo == RISCV::X17) {
11158         // Second half of f64 is passed on the stack.
11159         // Work out the address of the stack slot.
11160         if (!StackPtr.getNode())
11161           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11162         // Emit the store.
11163         MemOpChains.push_back(
11164             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
11165       } else {
11166         // Second half of f64 is passed in another GPR.
11167         assert(RegLo < RISCV::X31 && "Invalid register pair");
11168         Register RegHigh = RegLo + 1;
11169         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
11170       }
11171       continue;
11172     }
11173 
11174     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
11175     // as any other MemLoc.
11176 
11177     // Promote the value if needed.
11178     // For now, only handle fully promoted and indirect arguments.
11179     if (VA.getLocInfo() == CCValAssign::Indirect) {
11180       // Store the argument in a stack slot and pass its address.
11181       Align StackAlign =
11182           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
11183                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
11184       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
11185       // If the original argument was split (e.g. i128), we need
11186       // to store the required parts of it here (and pass just one address).
11187       // Vectors may be partly split to registers and partly to the stack, in
11188       // which case the base address is partly offset and subsequent stores are
11189       // relative to that.
11190       unsigned ArgIndex = Outs[i].OrigArgIndex;
11191       unsigned ArgPartOffset = Outs[i].PartOffset;
11192       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
11193       // Calculate the total size to store. We don't have access to what we're
11194       // actually storing other than performing the loop and collecting the
11195       // info.
11196       SmallVector<std::pair<SDValue, SDValue>> Parts;
11197       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
11198         SDValue PartValue = OutVals[i + 1];
11199         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
11200         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11201         EVT PartVT = PartValue.getValueType();
11202         if (PartVT.isScalableVector())
11203           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
11204         StoredSize += PartVT.getStoreSize();
11205         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
11206         Parts.push_back(std::make_pair(PartValue, Offset));
11207         ++i;
11208       }
11209       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
11210       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
11211       MemOpChains.push_back(
11212           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
11213                        MachinePointerInfo::getFixedStack(MF, FI)));
11214       for (const auto &Part : Parts) {
11215         SDValue PartValue = Part.first;
11216         SDValue PartOffset = Part.second;
11217         SDValue Address =
11218             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
11219         MemOpChains.push_back(
11220             DAG.getStore(Chain, DL, PartValue, Address,
11221                          MachinePointerInfo::getFixedStack(MF, FI)));
11222       }
11223       ArgValue = SpillSlot;
11224     } else {
11225       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
11226     }
11227 
11228     // Use local copy if it is a byval arg.
11229     if (Flags.isByVal())
11230       ArgValue = ByValArgs[j++];
11231 
11232     if (VA.isRegLoc()) {
11233       // Queue up the argument copies and emit them at the end.
11234       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
11235     } else {
11236       assert(VA.isMemLoc() && "Argument not register or memory");
11237       assert(!IsTailCall && "Tail call not allowed if stack is used "
11238                             "for passing parameters");
11239 
11240       // Work out the address of the stack slot.
11241       if (!StackPtr.getNode())
11242         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11243       SDValue Address =
11244           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11245                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
11246 
11247       // Emit the store.
11248       MemOpChains.push_back(
11249           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
11250     }
11251   }
11252 
11253   // Join the stores, which are independent of one another.
11254   if (!MemOpChains.empty())
11255     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
11256 
11257   SDValue Glue;
11258 
11259   // Build a sequence of copy-to-reg nodes, chained and glued together.
11260   for (auto &Reg : RegsToPass) {
11261     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11262     Glue = Chain.getValue(1);
11263   }
11264 
11265   // Validate that none of the argument registers have been marked as
11266   // reserved, if so report an error. Do the same for the return address if this
11267   // is not a tailcall.
11268   validateCCReservedRegs(RegsToPass, MF);
11269   if (!IsTailCall &&
11270       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
11271     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11272         MF.getFunction(),
11273         "Return address register required, but has been reserved."});
11274 
11275   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11276   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11277   // split it and then direct call can be matched by PseudoCALL.
11278   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
11279     const GlobalValue *GV = S->getGlobal();
11280 
11281     unsigned OpFlags = RISCVII::MO_CALL;
11282     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
11283       OpFlags = RISCVII::MO_PLT;
11284 
11285     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
11286   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11287     unsigned OpFlags = RISCVII::MO_CALL;
11288 
11289     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
11290                                                  nullptr))
11291       OpFlags = RISCVII::MO_PLT;
11292 
11293     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11294   }
11295 
11296   // The first call operand is the chain and the second is the target address.
11297   SmallVector<SDValue, 8> Ops;
11298   Ops.push_back(Chain);
11299   Ops.push_back(Callee);
11300 
11301   // Add argument registers to the end of the list so that they are
11302   // known live into the call.
11303   for (auto &Reg : RegsToPass)
11304     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11305 
11306   if (!IsTailCall) {
11307     // Add a register mask operand representing the call-preserved registers.
11308     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11309     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11310     assert(Mask && "Missing call preserved mask for calling convention");
11311     Ops.push_back(DAG.getRegisterMask(Mask));
11312   }
11313 
11314   // Glue the call to the argument copies, if any.
11315   if (Glue.getNode())
11316     Ops.push_back(Glue);
11317 
11318   // Emit the call.
11319   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11320 
11321   if (IsTailCall) {
11322     MF.getFrameInfo().setHasTailCall();
11323     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
11324   }
11325 
11326   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
11327   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11328   Glue = Chain.getValue(1);
11329 
11330   // Mark the end of the call, which is glued to the call itself.
11331   Chain = DAG.getCALLSEQ_END(Chain,
11332                              DAG.getConstant(NumBytes, DL, PtrVT, true),
11333                              DAG.getConstant(0, DL, PtrVT, true),
11334                              Glue, DL);
11335   Glue = Chain.getValue(1);
11336 
11337   // Assign locations to each value returned by this call.
11338   SmallVector<CCValAssign, 16> RVLocs;
11339   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11340   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
11341 
11342   // Copy all of the result registers out of their specified physreg.
11343   for (auto &VA : RVLocs) {
11344     // Copy the value out
11345     SDValue RetValue =
11346         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11347     // Glue the RetValue to the end of the call sequence
11348     Chain = RetValue.getValue(1);
11349     Glue = RetValue.getValue(2);
11350 
11351     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11352       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11353       SDValue RetValue2 =
11354           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11355       Chain = RetValue2.getValue(1);
11356       Glue = RetValue2.getValue(2);
11357       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11358                              RetValue2);
11359     }
11360 
11361     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11362 
11363     InVals.push_back(RetValue);
11364   }
11365 
11366   return Chain;
11367 }
11368 
11369 bool RISCVTargetLowering::CanLowerReturn(
11370     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11371     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11372   SmallVector<CCValAssign, 16> RVLocs;
11373   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11374 
11375   Optional<unsigned> FirstMaskArgument;
11376   if (Subtarget.hasVInstructions())
11377     FirstMaskArgument = preAssignMask(Outs);
11378 
11379   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11380     MVT VT = Outs[i].VT;
11381     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11382     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11383     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11384                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11385                  *this, FirstMaskArgument))
11386       return false;
11387   }
11388   return true;
11389 }
11390 
11391 SDValue
11392 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11393                                  bool IsVarArg,
11394                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11395                                  const SmallVectorImpl<SDValue> &OutVals,
11396                                  const SDLoc &DL, SelectionDAG &DAG) const {
11397   const MachineFunction &MF = DAG.getMachineFunction();
11398   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11399 
11400   // Stores the assignment of the return value to a location.
11401   SmallVector<CCValAssign, 16> RVLocs;
11402 
11403   // Info about the registers and stack slot.
11404   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11405                  *DAG.getContext());
11406 
11407   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11408                     nullptr, CC_RISCV);
11409 
11410   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11411     report_fatal_error("GHC functions return void only");
11412 
11413   SDValue Glue;
11414   SmallVector<SDValue, 4> RetOps(1, Chain);
11415 
11416   // Copy the result values into the output registers.
11417   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11418     SDValue Val = OutVals[i];
11419     CCValAssign &VA = RVLocs[i];
11420     assert(VA.isRegLoc() && "Can only return in registers!");
11421 
11422     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11423       // Handle returning f64 on RV32D with a soft float ABI.
11424       assert(VA.isRegLoc() && "Expected return via registers");
11425       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11426                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11427       SDValue Lo = SplitF64.getValue(0);
11428       SDValue Hi = SplitF64.getValue(1);
11429       Register RegLo = VA.getLocReg();
11430       assert(RegLo < RISCV::X31 && "Invalid register pair");
11431       Register RegHi = RegLo + 1;
11432 
11433       if (STI.isRegisterReservedByUser(RegLo) ||
11434           STI.isRegisterReservedByUser(RegHi))
11435         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11436             MF.getFunction(),
11437             "Return value register required, but has been reserved."});
11438 
11439       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11440       Glue = Chain.getValue(1);
11441       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11442       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11443       Glue = Chain.getValue(1);
11444       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11445     } else {
11446       // Handle a 'normal' return.
11447       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11448       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11449 
11450       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11451         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11452             MF.getFunction(),
11453             "Return value register required, but has been reserved."});
11454 
11455       // Guarantee that all emitted copies are stuck together.
11456       Glue = Chain.getValue(1);
11457       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11458     }
11459   }
11460 
11461   RetOps[0] = Chain; // Update chain.
11462 
11463   // Add the glue node if we have it.
11464   if (Glue.getNode()) {
11465     RetOps.push_back(Glue);
11466   }
11467 
11468   unsigned RetOpc = RISCVISD::RET_FLAG;
11469   // Interrupt service routines use different return instructions.
11470   const Function &Func = DAG.getMachineFunction().getFunction();
11471   if (Func.hasFnAttribute("interrupt")) {
11472     if (!Func.getReturnType()->isVoidTy())
11473       report_fatal_error(
11474           "Functions with the interrupt attribute must have void return type!");
11475 
11476     MachineFunction &MF = DAG.getMachineFunction();
11477     StringRef Kind =
11478       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11479 
11480     if (Kind == "user")
11481       RetOpc = RISCVISD::URET_FLAG;
11482     else if (Kind == "supervisor")
11483       RetOpc = RISCVISD::SRET_FLAG;
11484     else
11485       RetOpc = RISCVISD::MRET_FLAG;
11486   }
11487 
11488   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11489 }
11490 
11491 void RISCVTargetLowering::validateCCReservedRegs(
11492     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11493     MachineFunction &MF) const {
11494   const Function &F = MF.getFunction();
11495   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11496 
11497   if (llvm::any_of(Regs, [&STI](auto Reg) {
11498         return STI.isRegisterReservedByUser(Reg.first);
11499       }))
11500     F.getContext().diagnose(DiagnosticInfoUnsupported{
11501         F, "Argument register required, but has been reserved."});
11502 }
11503 
11504 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11505   return CI->isTailCall();
11506 }
11507 
11508 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11509 #define NODE_NAME_CASE(NODE)                                                   \
11510   case RISCVISD::NODE:                                                         \
11511     return "RISCVISD::" #NODE;
11512   // clang-format off
11513   switch ((RISCVISD::NodeType)Opcode) {
11514   case RISCVISD::FIRST_NUMBER:
11515     break;
11516   NODE_NAME_CASE(RET_FLAG)
11517   NODE_NAME_CASE(URET_FLAG)
11518   NODE_NAME_CASE(SRET_FLAG)
11519   NODE_NAME_CASE(MRET_FLAG)
11520   NODE_NAME_CASE(CALL)
11521   NODE_NAME_CASE(SELECT_CC)
11522   NODE_NAME_CASE(BR_CC)
11523   NODE_NAME_CASE(BuildPairF64)
11524   NODE_NAME_CASE(SplitF64)
11525   NODE_NAME_CASE(TAIL)
11526   NODE_NAME_CASE(ADD_LO)
11527   NODE_NAME_CASE(HI)
11528   NODE_NAME_CASE(LLA)
11529   NODE_NAME_CASE(ADD_TPREL)
11530   NODE_NAME_CASE(LA)
11531   NODE_NAME_CASE(LA_TLS_IE)
11532   NODE_NAME_CASE(LA_TLS_GD)
11533   NODE_NAME_CASE(MULHSU)
11534   NODE_NAME_CASE(SLLW)
11535   NODE_NAME_CASE(SRAW)
11536   NODE_NAME_CASE(SRLW)
11537   NODE_NAME_CASE(DIVW)
11538   NODE_NAME_CASE(DIVUW)
11539   NODE_NAME_CASE(REMUW)
11540   NODE_NAME_CASE(ROLW)
11541   NODE_NAME_CASE(RORW)
11542   NODE_NAME_CASE(CLZW)
11543   NODE_NAME_CASE(CTZW)
11544   NODE_NAME_CASE(FSLW)
11545   NODE_NAME_CASE(FSRW)
11546   NODE_NAME_CASE(FSL)
11547   NODE_NAME_CASE(FSR)
11548   NODE_NAME_CASE(FMV_H_X)
11549   NODE_NAME_CASE(FMV_X_ANYEXTH)
11550   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11551   NODE_NAME_CASE(FMV_W_X_RV64)
11552   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11553   NODE_NAME_CASE(FCVT_X)
11554   NODE_NAME_CASE(FCVT_XU)
11555   NODE_NAME_CASE(FCVT_W_RV64)
11556   NODE_NAME_CASE(FCVT_WU_RV64)
11557   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11558   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11559   NODE_NAME_CASE(READ_CYCLE_WIDE)
11560   NODE_NAME_CASE(GREV)
11561   NODE_NAME_CASE(GREVW)
11562   NODE_NAME_CASE(GORC)
11563   NODE_NAME_CASE(GORCW)
11564   NODE_NAME_CASE(SHFL)
11565   NODE_NAME_CASE(SHFLW)
11566   NODE_NAME_CASE(UNSHFL)
11567   NODE_NAME_CASE(UNSHFLW)
11568   NODE_NAME_CASE(BFP)
11569   NODE_NAME_CASE(BFPW)
11570   NODE_NAME_CASE(BCOMPRESS)
11571   NODE_NAME_CASE(BCOMPRESSW)
11572   NODE_NAME_CASE(BDECOMPRESS)
11573   NODE_NAME_CASE(BDECOMPRESSW)
11574   NODE_NAME_CASE(VMV_V_X_VL)
11575   NODE_NAME_CASE(VFMV_V_F_VL)
11576   NODE_NAME_CASE(VMV_X_S)
11577   NODE_NAME_CASE(VMV_S_X_VL)
11578   NODE_NAME_CASE(VFMV_S_F_VL)
11579   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11580   NODE_NAME_CASE(READ_VLENB)
11581   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11582   NODE_NAME_CASE(VSLIDEUP_VL)
11583   NODE_NAME_CASE(VSLIDE1UP_VL)
11584   NODE_NAME_CASE(VSLIDEDOWN_VL)
11585   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11586   NODE_NAME_CASE(VID_VL)
11587   NODE_NAME_CASE(VFNCVT_ROD_VL)
11588   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11589   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11590   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11591   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11592   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11593   NODE_NAME_CASE(VECREDUCE_AND_VL)
11594   NODE_NAME_CASE(VECREDUCE_OR_VL)
11595   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11596   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11597   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11598   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11599   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11600   NODE_NAME_CASE(ADD_VL)
11601   NODE_NAME_CASE(AND_VL)
11602   NODE_NAME_CASE(MUL_VL)
11603   NODE_NAME_CASE(OR_VL)
11604   NODE_NAME_CASE(SDIV_VL)
11605   NODE_NAME_CASE(SHL_VL)
11606   NODE_NAME_CASE(SREM_VL)
11607   NODE_NAME_CASE(SRA_VL)
11608   NODE_NAME_CASE(SRL_VL)
11609   NODE_NAME_CASE(SUB_VL)
11610   NODE_NAME_CASE(UDIV_VL)
11611   NODE_NAME_CASE(UREM_VL)
11612   NODE_NAME_CASE(XOR_VL)
11613   NODE_NAME_CASE(SADDSAT_VL)
11614   NODE_NAME_CASE(UADDSAT_VL)
11615   NODE_NAME_CASE(SSUBSAT_VL)
11616   NODE_NAME_CASE(USUBSAT_VL)
11617   NODE_NAME_CASE(FADD_VL)
11618   NODE_NAME_CASE(FSUB_VL)
11619   NODE_NAME_CASE(FMUL_VL)
11620   NODE_NAME_CASE(FDIV_VL)
11621   NODE_NAME_CASE(FNEG_VL)
11622   NODE_NAME_CASE(FABS_VL)
11623   NODE_NAME_CASE(FSQRT_VL)
11624   NODE_NAME_CASE(VFMADD_VL)
11625   NODE_NAME_CASE(VFNMADD_VL)
11626   NODE_NAME_CASE(VFMSUB_VL)
11627   NODE_NAME_CASE(VFNMSUB_VL)
11628   NODE_NAME_CASE(FCOPYSIGN_VL)
11629   NODE_NAME_CASE(SMIN_VL)
11630   NODE_NAME_CASE(SMAX_VL)
11631   NODE_NAME_CASE(UMIN_VL)
11632   NODE_NAME_CASE(UMAX_VL)
11633   NODE_NAME_CASE(FMINNUM_VL)
11634   NODE_NAME_CASE(FMAXNUM_VL)
11635   NODE_NAME_CASE(MULHS_VL)
11636   NODE_NAME_CASE(MULHU_VL)
11637   NODE_NAME_CASE(FP_TO_SINT_VL)
11638   NODE_NAME_CASE(FP_TO_UINT_VL)
11639   NODE_NAME_CASE(SINT_TO_FP_VL)
11640   NODE_NAME_CASE(UINT_TO_FP_VL)
11641   NODE_NAME_CASE(FP_EXTEND_VL)
11642   NODE_NAME_CASE(FP_ROUND_VL)
11643   NODE_NAME_CASE(VWMUL_VL)
11644   NODE_NAME_CASE(VWMULU_VL)
11645   NODE_NAME_CASE(VWMULSU_VL)
11646   NODE_NAME_CASE(VWADD_VL)
11647   NODE_NAME_CASE(VWADDU_VL)
11648   NODE_NAME_CASE(VWSUB_VL)
11649   NODE_NAME_CASE(VWSUBU_VL)
11650   NODE_NAME_CASE(VWADD_W_VL)
11651   NODE_NAME_CASE(VWADDU_W_VL)
11652   NODE_NAME_CASE(VWSUB_W_VL)
11653   NODE_NAME_CASE(VWSUBU_W_VL)
11654   NODE_NAME_CASE(SETCC_VL)
11655   NODE_NAME_CASE(VSELECT_VL)
11656   NODE_NAME_CASE(VP_MERGE_VL)
11657   NODE_NAME_CASE(VMAND_VL)
11658   NODE_NAME_CASE(VMOR_VL)
11659   NODE_NAME_CASE(VMXOR_VL)
11660   NODE_NAME_CASE(VMCLR_VL)
11661   NODE_NAME_CASE(VMSET_VL)
11662   NODE_NAME_CASE(VRGATHER_VX_VL)
11663   NODE_NAME_CASE(VRGATHER_VV_VL)
11664   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11665   NODE_NAME_CASE(VSEXT_VL)
11666   NODE_NAME_CASE(VZEXT_VL)
11667   NODE_NAME_CASE(VCPOP_VL)
11668   NODE_NAME_CASE(READ_CSR)
11669   NODE_NAME_CASE(WRITE_CSR)
11670   NODE_NAME_CASE(SWAP_CSR)
11671   }
11672   // clang-format on
11673   return nullptr;
11674 #undef NODE_NAME_CASE
11675 }
11676 
11677 /// getConstraintType - Given a constraint letter, return the type of
11678 /// constraint it is for this target.
11679 RISCVTargetLowering::ConstraintType
11680 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11681   if (Constraint.size() == 1) {
11682     switch (Constraint[0]) {
11683     default:
11684       break;
11685     case 'f':
11686       return C_RegisterClass;
11687     case 'I':
11688     case 'J':
11689     case 'K':
11690       return C_Immediate;
11691     case 'A':
11692       return C_Memory;
11693     case 'S': // A symbolic address
11694       return C_Other;
11695     }
11696   } else {
11697     if (Constraint == "vr" || Constraint == "vm")
11698       return C_RegisterClass;
11699   }
11700   return TargetLowering::getConstraintType(Constraint);
11701 }
11702 
11703 std::pair<unsigned, const TargetRegisterClass *>
11704 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11705                                                   StringRef Constraint,
11706                                                   MVT VT) const {
11707   // First, see if this is a constraint that directly corresponds to a
11708   // RISCV register class.
11709   if (Constraint.size() == 1) {
11710     switch (Constraint[0]) {
11711     case 'r':
11712       // TODO: Support fixed vectors up to XLen for P extension?
11713       if (VT.isVector())
11714         break;
11715       return std::make_pair(0U, &RISCV::GPRRegClass);
11716     case 'f':
11717       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11718         return std::make_pair(0U, &RISCV::FPR16RegClass);
11719       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11720         return std::make_pair(0U, &RISCV::FPR32RegClass);
11721       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11722         return std::make_pair(0U, &RISCV::FPR64RegClass);
11723       break;
11724     default:
11725       break;
11726     }
11727   } else if (Constraint == "vr") {
11728     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11729                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11730       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11731         return std::make_pair(0U, RC);
11732     }
11733   } else if (Constraint == "vm") {
11734     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11735       return std::make_pair(0U, &RISCV::VMV0RegClass);
11736   }
11737 
11738   // Clang will correctly decode the usage of register name aliases into their
11739   // official names. However, other frontends like `rustc` do not. This allows
11740   // users of these frontends to use the ABI names for registers in LLVM-style
11741   // register constraints.
11742   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11743                                .Case("{zero}", RISCV::X0)
11744                                .Case("{ra}", RISCV::X1)
11745                                .Case("{sp}", RISCV::X2)
11746                                .Case("{gp}", RISCV::X3)
11747                                .Case("{tp}", RISCV::X4)
11748                                .Case("{t0}", RISCV::X5)
11749                                .Case("{t1}", RISCV::X6)
11750                                .Case("{t2}", RISCV::X7)
11751                                .Cases("{s0}", "{fp}", RISCV::X8)
11752                                .Case("{s1}", RISCV::X9)
11753                                .Case("{a0}", RISCV::X10)
11754                                .Case("{a1}", RISCV::X11)
11755                                .Case("{a2}", RISCV::X12)
11756                                .Case("{a3}", RISCV::X13)
11757                                .Case("{a4}", RISCV::X14)
11758                                .Case("{a5}", RISCV::X15)
11759                                .Case("{a6}", RISCV::X16)
11760                                .Case("{a7}", RISCV::X17)
11761                                .Case("{s2}", RISCV::X18)
11762                                .Case("{s3}", RISCV::X19)
11763                                .Case("{s4}", RISCV::X20)
11764                                .Case("{s5}", RISCV::X21)
11765                                .Case("{s6}", RISCV::X22)
11766                                .Case("{s7}", RISCV::X23)
11767                                .Case("{s8}", RISCV::X24)
11768                                .Case("{s9}", RISCV::X25)
11769                                .Case("{s10}", RISCV::X26)
11770                                .Case("{s11}", RISCV::X27)
11771                                .Case("{t3}", RISCV::X28)
11772                                .Case("{t4}", RISCV::X29)
11773                                .Case("{t5}", RISCV::X30)
11774                                .Case("{t6}", RISCV::X31)
11775                                .Default(RISCV::NoRegister);
11776   if (XRegFromAlias != RISCV::NoRegister)
11777     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11778 
11779   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11780   // TableGen record rather than the AsmName to choose registers for InlineAsm
11781   // constraints, plus we want to match those names to the widest floating point
11782   // register type available, manually select floating point registers here.
11783   //
11784   // The second case is the ABI name of the register, so that frontends can also
11785   // use the ABI names in register constraint lists.
11786   if (Subtarget.hasStdExtF()) {
11787     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11788                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11789                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11790                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11791                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11792                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11793                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11794                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11795                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11796                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11797                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11798                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11799                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11800                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11801                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11802                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11803                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11804                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11805                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11806                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11807                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11808                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11809                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11810                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11811                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11812                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11813                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11814                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11815                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11816                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11817                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11818                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11819                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11820                         .Default(RISCV::NoRegister);
11821     if (FReg != RISCV::NoRegister) {
11822       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11823       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11824         unsigned RegNo = FReg - RISCV::F0_F;
11825         unsigned DReg = RISCV::F0_D + RegNo;
11826         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11827       }
11828       if (VT == MVT::f32 || VT == MVT::Other)
11829         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11830       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11831         unsigned RegNo = FReg - RISCV::F0_F;
11832         unsigned HReg = RISCV::F0_H + RegNo;
11833         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11834       }
11835     }
11836   }
11837 
11838   if (Subtarget.hasVInstructions()) {
11839     Register VReg = StringSwitch<Register>(Constraint.lower())
11840                         .Case("{v0}", RISCV::V0)
11841                         .Case("{v1}", RISCV::V1)
11842                         .Case("{v2}", RISCV::V2)
11843                         .Case("{v3}", RISCV::V3)
11844                         .Case("{v4}", RISCV::V4)
11845                         .Case("{v5}", RISCV::V5)
11846                         .Case("{v6}", RISCV::V6)
11847                         .Case("{v7}", RISCV::V7)
11848                         .Case("{v8}", RISCV::V8)
11849                         .Case("{v9}", RISCV::V9)
11850                         .Case("{v10}", RISCV::V10)
11851                         .Case("{v11}", RISCV::V11)
11852                         .Case("{v12}", RISCV::V12)
11853                         .Case("{v13}", RISCV::V13)
11854                         .Case("{v14}", RISCV::V14)
11855                         .Case("{v15}", RISCV::V15)
11856                         .Case("{v16}", RISCV::V16)
11857                         .Case("{v17}", RISCV::V17)
11858                         .Case("{v18}", RISCV::V18)
11859                         .Case("{v19}", RISCV::V19)
11860                         .Case("{v20}", RISCV::V20)
11861                         .Case("{v21}", RISCV::V21)
11862                         .Case("{v22}", RISCV::V22)
11863                         .Case("{v23}", RISCV::V23)
11864                         .Case("{v24}", RISCV::V24)
11865                         .Case("{v25}", RISCV::V25)
11866                         .Case("{v26}", RISCV::V26)
11867                         .Case("{v27}", RISCV::V27)
11868                         .Case("{v28}", RISCV::V28)
11869                         .Case("{v29}", RISCV::V29)
11870                         .Case("{v30}", RISCV::V30)
11871                         .Case("{v31}", RISCV::V31)
11872                         .Default(RISCV::NoRegister);
11873     if (VReg != RISCV::NoRegister) {
11874       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11875         return std::make_pair(VReg, &RISCV::VMRegClass);
11876       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11877         return std::make_pair(VReg, &RISCV::VRRegClass);
11878       for (const auto *RC :
11879            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11880         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11881           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11882           return std::make_pair(VReg, RC);
11883         }
11884       }
11885     }
11886   }
11887 
11888   std::pair<Register, const TargetRegisterClass *> Res =
11889       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11890 
11891   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11892   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11893   // Subtarget into account.
11894   if (Res.second == &RISCV::GPRF16RegClass ||
11895       Res.second == &RISCV::GPRF32RegClass ||
11896       Res.second == &RISCV::GPRF64RegClass)
11897     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11898 
11899   return Res;
11900 }
11901 
11902 unsigned
11903 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11904   // Currently only support length 1 constraints.
11905   if (ConstraintCode.size() == 1) {
11906     switch (ConstraintCode[0]) {
11907     case 'A':
11908       return InlineAsm::Constraint_A;
11909     default:
11910       break;
11911     }
11912   }
11913 
11914   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11915 }
11916 
11917 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11918     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11919     SelectionDAG &DAG) const {
11920   // Currently only support length 1 constraints.
11921   if (Constraint.length() == 1) {
11922     switch (Constraint[0]) {
11923     case 'I':
11924       // Validate & create a 12-bit signed immediate operand.
11925       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11926         uint64_t CVal = C->getSExtValue();
11927         if (isInt<12>(CVal))
11928           Ops.push_back(
11929               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11930       }
11931       return;
11932     case 'J':
11933       // Validate & create an integer zero operand.
11934       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11935         if (C->getZExtValue() == 0)
11936           Ops.push_back(
11937               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11938       return;
11939     case 'K':
11940       // Validate & create a 5-bit unsigned immediate operand.
11941       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11942         uint64_t CVal = C->getZExtValue();
11943         if (isUInt<5>(CVal))
11944           Ops.push_back(
11945               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11946       }
11947       return;
11948     case 'S':
11949       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11950         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11951                                                  GA->getValueType(0)));
11952       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11953         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11954                                                 BA->getValueType(0)));
11955       }
11956       return;
11957     default:
11958       break;
11959     }
11960   }
11961   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11962 }
11963 
11964 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11965                                                    Instruction *Inst,
11966                                                    AtomicOrdering Ord) const {
11967   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11968     return Builder.CreateFence(Ord);
11969   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11970     return Builder.CreateFence(AtomicOrdering::Release);
11971   return nullptr;
11972 }
11973 
11974 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11975                                                     Instruction *Inst,
11976                                                     AtomicOrdering Ord) const {
11977   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11978     return Builder.CreateFence(AtomicOrdering::Acquire);
11979   return nullptr;
11980 }
11981 
11982 TargetLowering::AtomicExpansionKind
11983 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11984   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11985   // point operations can't be used in an lr/sc sequence without breaking the
11986   // forward-progress guarantee.
11987   if (AI->isFloatingPointOperation())
11988     return AtomicExpansionKind::CmpXChg;
11989 
11990   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11991   if (Size == 8 || Size == 16)
11992     return AtomicExpansionKind::MaskedIntrinsic;
11993   return AtomicExpansionKind::None;
11994 }
11995 
11996 static Intrinsic::ID
11997 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11998   if (XLen == 32) {
11999     switch (BinOp) {
12000     default:
12001       llvm_unreachable("Unexpected AtomicRMW BinOp");
12002     case AtomicRMWInst::Xchg:
12003       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
12004     case AtomicRMWInst::Add:
12005       return Intrinsic::riscv_masked_atomicrmw_add_i32;
12006     case AtomicRMWInst::Sub:
12007       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
12008     case AtomicRMWInst::Nand:
12009       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
12010     case AtomicRMWInst::Max:
12011       return Intrinsic::riscv_masked_atomicrmw_max_i32;
12012     case AtomicRMWInst::Min:
12013       return Intrinsic::riscv_masked_atomicrmw_min_i32;
12014     case AtomicRMWInst::UMax:
12015       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
12016     case AtomicRMWInst::UMin:
12017       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
12018     }
12019   }
12020 
12021   if (XLen == 64) {
12022     switch (BinOp) {
12023     default:
12024       llvm_unreachable("Unexpected AtomicRMW BinOp");
12025     case AtomicRMWInst::Xchg:
12026       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
12027     case AtomicRMWInst::Add:
12028       return Intrinsic::riscv_masked_atomicrmw_add_i64;
12029     case AtomicRMWInst::Sub:
12030       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
12031     case AtomicRMWInst::Nand:
12032       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
12033     case AtomicRMWInst::Max:
12034       return Intrinsic::riscv_masked_atomicrmw_max_i64;
12035     case AtomicRMWInst::Min:
12036       return Intrinsic::riscv_masked_atomicrmw_min_i64;
12037     case AtomicRMWInst::UMax:
12038       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
12039     case AtomicRMWInst::UMin:
12040       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
12041     }
12042   }
12043 
12044   llvm_unreachable("Unexpected XLen\n");
12045 }
12046 
12047 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
12048     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
12049     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
12050   unsigned XLen = Subtarget.getXLen();
12051   Value *Ordering =
12052       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
12053   Type *Tys[] = {AlignedAddr->getType()};
12054   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
12055       AI->getModule(),
12056       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
12057 
12058   if (XLen == 64) {
12059     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
12060     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12061     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
12062   }
12063 
12064   Value *Result;
12065 
12066   // Must pass the shift amount needed to sign extend the loaded value prior
12067   // to performing a signed comparison for min/max. ShiftAmt is the number of
12068   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
12069   // is the number of bits to left+right shift the value in order to
12070   // sign-extend.
12071   if (AI->getOperation() == AtomicRMWInst::Min ||
12072       AI->getOperation() == AtomicRMWInst::Max) {
12073     const DataLayout &DL = AI->getModule()->getDataLayout();
12074     unsigned ValWidth =
12075         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
12076     Value *SextShamt =
12077         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
12078     Result = Builder.CreateCall(LrwOpScwLoop,
12079                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
12080   } else {
12081     Result =
12082         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
12083   }
12084 
12085   if (XLen == 64)
12086     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12087   return Result;
12088 }
12089 
12090 TargetLowering::AtomicExpansionKind
12091 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
12092     AtomicCmpXchgInst *CI) const {
12093   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
12094   if (Size == 8 || Size == 16)
12095     return AtomicExpansionKind::MaskedIntrinsic;
12096   return AtomicExpansionKind::None;
12097 }
12098 
12099 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
12100     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
12101     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
12102   unsigned XLen = Subtarget.getXLen();
12103   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
12104   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
12105   if (XLen == 64) {
12106     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
12107     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
12108     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12109     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
12110   }
12111   Type *Tys[] = {AlignedAddr->getType()};
12112   Function *MaskedCmpXchg =
12113       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
12114   Value *Result = Builder.CreateCall(
12115       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
12116   if (XLen == 64)
12117     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12118   return Result;
12119 }
12120 
12121 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
12122                                                         EVT DataVT) const {
12123   return false;
12124 }
12125 
12126 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
12127                                                EVT VT) const {
12128   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
12129     return false;
12130 
12131   switch (FPVT.getSimpleVT().SimpleTy) {
12132   case MVT::f16:
12133     return Subtarget.hasStdExtZfh();
12134   case MVT::f32:
12135     return Subtarget.hasStdExtF();
12136   case MVT::f64:
12137     return Subtarget.hasStdExtD();
12138   default:
12139     return false;
12140   }
12141 }
12142 
12143 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
12144   // If we are using the small code model, we can reduce size of jump table
12145   // entry to 4 bytes.
12146   if (Subtarget.is64Bit() && !isPositionIndependent() &&
12147       getTargetMachine().getCodeModel() == CodeModel::Small) {
12148     return MachineJumpTableInfo::EK_Custom32;
12149   }
12150   return TargetLowering::getJumpTableEncoding();
12151 }
12152 
12153 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
12154     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
12155     unsigned uid, MCContext &Ctx) const {
12156   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
12157          getTargetMachine().getCodeModel() == CodeModel::Small);
12158   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
12159 }
12160 
12161 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const {
12162   // We define vscale to be VLEN/RVVBitsPerBlock.  VLEN is always a power
12163   // of two >= 64, and RVVBitsPerBlock is 64.  Thus, vscale must be
12164   // a power of two as well.
12165   // FIXME: This doesn't work for zve32, but that's already broken
12166   // elsewhere for the same reason.
12167   assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported");
12168   assert(RISCV::RVVBitsPerBlock == 64 && "RVVBitsPerBlock changed, audit needed");
12169   return true;
12170 }
12171 
12172 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
12173                                                      EVT VT) const {
12174   VT = VT.getScalarType();
12175 
12176   if (!VT.isSimple())
12177     return false;
12178 
12179   switch (VT.getSimpleVT().SimpleTy) {
12180   case MVT::f16:
12181     return Subtarget.hasStdExtZfh();
12182   case MVT::f32:
12183     return Subtarget.hasStdExtF();
12184   case MVT::f64:
12185     return Subtarget.hasStdExtD();
12186   default:
12187     break;
12188   }
12189 
12190   return false;
12191 }
12192 
12193 Register RISCVTargetLowering::getExceptionPointerRegister(
12194     const Constant *PersonalityFn) const {
12195   return RISCV::X10;
12196 }
12197 
12198 Register RISCVTargetLowering::getExceptionSelectorRegister(
12199     const Constant *PersonalityFn) const {
12200   return RISCV::X11;
12201 }
12202 
12203 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
12204   // Return false to suppress the unnecessary extensions if the LibCall
12205   // arguments or return value is f32 type for LP64 ABI.
12206   RISCVABI::ABI ABI = Subtarget.getTargetABI();
12207   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
12208     return false;
12209 
12210   return true;
12211 }
12212 
12213 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
12214   if (Subtarget.is64Bit() && Type == MVT::i32)
12215     return true;
12216 
12217   return IsSigned;
12218 }
12219 
12220 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
12221                                                  SDValue C) const {
12222   // Check integral scalar types.
12223   if (VT.isScalarInteger()) {
12224     // Omit the optimization if the sub target has the M extension and the data
12225     // size exceeds XLen.
12226     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
12227       return false;
12228     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
12229       // Break the MUL to a SLLI and an ADD/SUB.
12230       const APInt &Imm = ConstNode->getAPIntValue();
12231       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
12232           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
12233         return true;
12234       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
12235       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
12236           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
12237            (Imm - 8).isPowerOf2()))
12238         return true;
12239       // Omit the following optimization if the sub target has the M extension
12240       // and the data size >= XLen.
12241       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
12242         return false;
12243       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
12244       // a pair of LUI/ADDI.
12245       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
12246         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
12247         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
12248             (1 - ImmS).isPowerOf2())
12249           return true;
12250       }
12251     }
12252   }
12253 
12254   return false;
12255 }
12256 
12257 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
12258                                                       SDValue ConstNode) const {
12259   // Let the DAGCombiner decide for vectors.
12260   EVT VT = AddNode.getValueType();
12261   if (VT.isVector())
12262     return true;
12263 
12264   // Let the DAGCombiner decide for larger types.
12265   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
12266     return true;
12267 
12268   // It is worse if c1 is simm12 while c1*c2 is not.
12269   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12270   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12271   const APInt &C1 = C1Node->getAPIntValue();
12272   const APInt &C2 = C2Node->getAPIntValue();
12273   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
12274     return false;
12275 
12276   // Default to true and let the DAGCombiner decide.
12277   return true;
12278 }
12279 
12280 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
12281     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
12282     bool *Fast) const {
12283   if (!VT.isVector()) {
12284     if (Fast)
12285       *Fast = false;
12286     return Subtarget.enableUnalignedScalarMem();
12287   }
12288 
12289   // All vector implementations must support element alignment
12290   EVT ElemVT = VT.getVectorElementType();
12291   if (Alignment >= ElemVT.getStoreSize()) {
12292     if (Fast)
12293       *Fast = true;
12294     return true;
12295   }
12296 
12297   return false;
12298 }
12299 
12300 bool RISCVTargetLowering::splitValueIntoRegisterParts(
12301     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12302     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
12303   bool IsABIRegCopy = CC.has_value();
12304   EVT ValueVT = Val.getValueType();
12305   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12306     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
12307     // and cast to f32.
12308     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12309     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12310     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12311                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12312     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12313     Parts[0] = Val;
12314     return true;
12315   }
12316 
12317   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12318     LLVMContext &Context = *DAG.getContext();
12319     EVT ValueEltVT = ValueVT.getVectorElementType();
12320     EVT PartEltVT = PartVT.getVectorElementType();
12321     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12322     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12323     if (PartVTBitSize % ValueVTBitSize == 0) {
12324       assert(PartVTBitSize >= ValueVTBitSize);
12325       // If the element types are different, bitcast to the same element type of
12326       // PartVT first.
12327       // Give an example here, we want copy a <vscale x 1 x i8> value to
12328       // <vscale x 4 x i16>.
12329       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
12330       // subvector, then we can bitcast to <vscale x 4 x i16>.
12331       if (ValueEltVT != PartEltVT) {
12332         if (PartVTBitSize > ValueVTBitSize) {
12333           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12334           assert(Count != 0 && "The number of element should not be zero.");
12335           EVT SameEltTypeVT =
12336               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12337           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
12338                             DAG.getUNDEF(SameEltTypeVT), Val,
12339                             DAG.getVectorIdxConstant(0, DL));
12340         }
12341         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
12342       } else {
12343         Val =
12344             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
12345                         Val, DAG.getVectorIdxConstant(0, DL));
12346       }
12347       Parts[0] = Val;
12348       return true;
12349     }
12350   }
12351   return false;
12352 }
12353 
12354 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
12355     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12356     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
12357   bool IsABIRegCopy = CC.has_value();
12358   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12359     SDValue Val = Parts[0];
12360 
12361     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12362     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12363     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12364     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12365     return Val;
12366   }
12367 
12368   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12369     LLVMContext &Context = *DAG.getContext();
12370     SDValue Val = Parts[0];
12371     EVT ValueEltVT = ValueVT.getVectorElementType();
12372     EVT PartEltVT = PartVT.getVectorElementType();
12373     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12374     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12375     if (PartVTBitSize % ValueVTBitSize == 0) {
12376       assert(PartVTBitSize >= ValueVTBitSize);
12377       EVT SameEltTypeVT = ValueVT;
12378       // If the element types are different, convert it to the same element type
12379       // of PartVT.
12380       // Give an example here, we want copy a <vscale x 1 x i8> value from
12381       // <vscale x 4 x i16>.
12382       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12383       // then we can extract <vscale x 1 x i8>.
12384       if (ValueEltVT != PartEltVT) {
12385         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12386         assert(Count != 0 && "The number of element should not be zero.");
12387         SameEltTypeVT =
12388             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12389         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12390       }
12391       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12392                         DAG.getVectorIdxConstant(0, DL));
12393       return Val;
12394     }
12395   }
12396   return SDValue();
12397 }
12398 
12399 SDValue
12400 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12401                                    SelectionDAG &DAG,
12402                                    SmallVectorImpl<SDNode *> &Created) const {
12403   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12404   if (isIntDivCheap(N->getValueType(0), Attr))
12405     return SDValue(N, 0); // Lower SDIV as SDIV
12406 
12407   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12408          "Unexpected divisor!");
12409 
12410   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12411   if (!Subtarget.hasStdExtZbt())
12412     return SDValue();
12413 
12414   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12415   // Besides, more critical path instructions will be generated when dividing
12416   // by 2. So we keep using the original DAGs for these cases.
12417   unsigned Lg2 = Divisor.countTrailingZeros();
12418   if (Lg2 == 1 || Lg2 >= 12)
12419     return SDValue();
12420 
12421   // fold (sdiv X, pow2)
12422   EVT VT = N->getValueType(0);
12423   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12424     return SDValue();
12425 
12426   SDLoc DL(N);
12427   SDValue N0 = N->getOperand(0);
12428   SDValue Zero = DAG.getConstant(0, DL, VT);
12429   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12430 
12431   // Add (N0 < 0) ? Pow2 - 1 : 0;
12432   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12433   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12434   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12435 
12436   Created.push_back(Cmp.getNode());
12437   Created.push_back(Add.getNode());
12438   Created.push_back(Sel.getNode());
12439 
12440   // Divide by pow2.
12441   SDValue SRA =
12442       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12443 
12444   // If we're dividing by a positive value, we're done.  Otherwise, we must
12445   // negate the result.
12446   if (Divisor.isNonNegative())
12447     return SRA;
12448 
12449   Created.push_back(SRA.getNode());
12450   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12451 }
12452 
12453 #define GET_REGISTER_MATCHER
12454 #include "RISCVGenAsmMatcher.inc"
12455 
12456 Register
12457 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12458                                        const MachineFunction &MF) const {
12459   Register Reg = MatchRegisterAltName(RegName);
12460   if (Reg == RISCV::NoRegister)
12461     Reg = MatchRegisterName(RegName);
12462   if (Reg == RISCV::NoRegister)
12463     report_fatal_error(
12464         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12465   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12466   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12467     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12468                              StringRef(RegName) + "\"."));
12469   return Reg;
12470 }
12471 
12472 namespace llvm {
12473 namespace RISCVVIntrinsicsTable {
12474 
12475 #define GET_RISCVVIntrinsicsTable_IMPL
12476 #include "RISCVGenSearchableTables.inc"
12477 
12478 } // namespace RISCVVIntrinsicsTable
12479 
12480 } // namespace llvm
12481