1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
254       Subtarget.hasStdExtZbkb()) {
255     if (Subtarget.is64Bit()) {
256       setOperationAction(ISD::ROTL, MVT::i32, Custom);
257       setOperationAction(ISD::ROTR, MVT::i32, Custom);
258     }
259   } else {
260     setOperationAction(ISD::ROTL, XLenVT, Expand);
261     setOperationAction(ISD::ROTR, XLenVT, Expand);
262   }
263 
264   if (Subtarget.hasStdExtZbp()) {
265     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
266     // more combining.
267     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
268     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
269     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
270     // BSWAP i8 doesn't exist.
271     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
272     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
273 
274     if (Subtarget.is64Bit()) {
275       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
276       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
277     }
278   } else {
279     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
280     // pattern match it directly in isel.
281     setOperationAction(ISD::BSWAP, XLenVT,
282                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
283                            ? Legal
284                            : Expand);
285     // Zbkb can use rev8+brev8 to implement bitreverse.
286     setOperationAction(ISD::BITREVERSE, XLenVT,
287                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
288   }
289 
290   if (Subtarget.hasStdExtZbb()) {
291     setOperationAction(ISD::SMIN, XLenVT, Legal);
292     setOperationAction(ISD::SMAX, XLenVT, Legal);
293     setOperationAction(ISD::UMIN, XLenVT, Legal);
294     setOperationAction(ISD::UMAX, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit()) {
297       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
298       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
299       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
300       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
301     }
302   } else {
303     setOperationAction(ISD::CTTZ, XLenVT, Expand);
304     setOperationAction(ISD::CTLZ, XLenVT, Expand);
305     setOperationAction(ISD::CTPOP, XLenVT, Expand);
306 
307     if (Subtarget.is64Bit())
308       setOperationAction(ISD::ABS, MVT::i32, Custom);
309   }
310 
311   if (Subtarget.hasStdExtZbt()) {
312     setOperationAction(ISD::FSHL, XLenVT, Custom);
313     setOperationAction(ISD::FSHR, XLenVT, Custom);
314     setOperationAction(ISD::SELECT, XLenVT, Legal);
315 
316     if (Subtarget.is64Bit()) {
317       setOperationAction(ISD::FSHL, MVT::i32, Custom);
318       setOperationAction(ISD::FSHR, MVT::i32, Custom);
319     }
320   } else {
321     setOperationAction(ISD::SELECT, XLenVT, Custom);
322   }
323 
324   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
325       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
326       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
327       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
328       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
329       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
330       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
331 
332   static const ISD::CondCode FPCCToExpand[] = {
333       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
334       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
335       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
336 
337   static const ISD::NodeType FPOpToExpand[] = {
338       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
339       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
340 
341   if (Subtarget.hasStdExtZfh())
342     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
343 
344   if (Subtarget.hasStdExtZfh()) {
345     for (auto NT : FPLegalNodeTypes)
346       setOperationAction(NT, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
349     for (auto CC : FPCCToExpand)
350       setCondCodeAction(CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
352     setOperationAction(ISD::SELECT, MVT::f16, Custom);
353     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
354 
355     setOperationAction(ISD::FREM,       MVT::f16, Promote);
356     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
357     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
358     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
359     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
360     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
361     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
362     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
363     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
364     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
365     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
366     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
367     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
368     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
369     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
370     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
371     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
372     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
373 
374     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
375     // complete support for all operations in LegalizeDAG.
376 
377     // We need to custom promote this.
378     if (Subtarget.is64Bit())
379       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
380   }
381 
382   if (Subtarget.hasStdExtF()) {
383     for (auto NT : FPLegalNodeTypes)
384       setOperationAction(NT, MVT::f32, Legal);
385     for (auto CC : FPCCToExpand)
386       setCondCodeAction(CC, MVT::f32, Expand);
387     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
388     setOperationAction(ISD::SELECT, MVT::f32, Custom);
389     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
390     for (auto Op : FPOpToExpand)
391       setOperationAction(Op, MVT::f32, Expand);
392     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
393     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   }
395 
396   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
397     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
398 
399   if (Subtarget.hasStdExtD()) {
400     for (auto NT : FPLegalNodeTypes)
401       setOperationAction(NT, MVT::f64, Legal);
402     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
404     for (auto CC : FPCCToExpand)
405       setCondCodeAction(CC, MVT::f64, Expand);
406     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
407     setOperationAction(ISD::SELECT, MVT::f64, Custom);
408     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
409     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
410     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f64, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.is64Bit()) {
418     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
419     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
420     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
421     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
422   }
423 
424   if (Subtarget.hasStdExtF()) {
425     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
426     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
427 
428     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
429     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
430     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
431     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
432 
433     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
434     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
435   }
436 
437   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
438   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
439   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
440   setOperationAction(ISD::JumpTable, XLenVT, Custom);
441 
442   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
443 
444   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
445   // Unfortunately this can't be determined just from the ISA naming string.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
447                      Subtarget.is64Bit() ? Legal : Custom);
448 
449   setOperationAction(ISD::TRAP, MVT::Other, Legal);
450   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
451   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
452   if (Subtarget.is64Bit())
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
454 
455   if (Subtarget.hasStdExtA()) {
456     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
457     setMinCmpXchgSizeInBits(32);
458   } else {
459     setMaxAtomicSizeInBitsSupported(0);
460   }
461 
462   setBooleanContents(ZeroOrOneBooleanContent);
463 
464   if (Subtarget.hasVInstructions()) {
465     setBooleanVectorContents(ZeroOrOneBooleanContent);
466 
467     setOperationAction(ISD::VSCALE, XLenVT, Custom);
468 
469     // RVV intrinsics may have illegal operands.
470     // We also need to custom legalize vmv.x.s.
471     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
472     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
473     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
474     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
475     if (Subtarget.is64Bit()) {
476       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
477     } else {
478       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
479       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
480     }
481 
482     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
483     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485     static const unsigned IntegerVPOps[] = {
486         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
487         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
488         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
489         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
490         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
491         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
492         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
493         ISD::VP_MERGE,       ISD::VP_SELECT};
494 
495     static const unsigned FloatingPointVPOps[] = {
496         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
497         ISD::VP_FDIV,        ISD::VP_FNEG,        ISD::VP_FMA,
498         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN,
499         ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,       ISD::VP_SELECT};
500 
501     if (!Subtarget.is64Bit()) {
502       // We must custom-lower certain vXi64 operations on RV32 due to the vector
503       // element type being illegal.
504       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
505       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
506 
507       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
508       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
509       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
510       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
511       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
512       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
513       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
515 
516       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
517       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
518       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
519       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
520       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
521       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
522       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
524     }
525 
526     for (MVT VT : BoolVecVTs) {
527       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
528 
529       // Mask VTs are custom-expanded into a series of standard nodes
530       setOperationAction(ISD::TRUNCATE, VT, Custom);
531       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
532       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
533       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
534 
535       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
536       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
537 
538       setOperationAction(ISD::SELECT, VT, Custom);
539       setOperationAction(ISD::SELECT_CC, VT, Expand);
540       setOperationAction(ISD::VSELECT, VT, Expand);
541       setOperationAction(ISD::VP_MERGE, VT, Expand);
542       setOperationAction(ISD::VP_SELECT, VT, Expand);
543 
544       setOperationAction(ISD::VP_AND, VT, Custom);
545       setOperationAction(ISD::VP_OR, VT, Custom);
546       setOperationAction(ISD::VP_XOR, VT, Custom);
547 
548       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
549       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
550       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
551 
552       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
553       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
554       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
555 
556       // RVV has native int->float & float->int conversions where the
557       // element type sizes are within one power-of-two of each other. Any
558       // wider distances between type sizes have to be lowered as sequences
559       // which progressively narrow the gap in stages.
560       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
561       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
562       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
563       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
564 
565       // Expand all extending loads to types larger than this, and truncating
566       // stores from types larger than this.
567       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
568         setTruncStoreAction(OtherVT, VT, Expand);
569         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
570         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
571         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
572       }
573     }
574 
575     for (MVT VT : IntVecVTs) {
576       if (VT.getVectorElementType() == MVT::i64 &&
577           !Subtarget.hasVInstructionsI64())
578         continue;
579 
580       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
581       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
582 
583       // Vectors implement MULHS/MULHU.
584       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
585       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
586 
587       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
588       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
589         setOperationAction(ISD::MULHU, VT, Expand);
590         setOperationAction(ISD::MULHS, VT, Expand);
591       }
592 
593       setOperationAction(ISD::SMIN, VT, Legal);
594       setOperationAction(ISD::SMAX, VT, Legal);
595       setOperationAction(ISD::UMIN, VT, Legal);
596       setOperationAction(ISD::UMAX, VT, Legal);
597 
598       setOperationAction(ISD::ROTL, VT, Expand);
599       setOperationAction(ISD::ROTR, VT, Expand);
600 
601       setOperationAction(ISD::CTTZ, VT, Expand);
602       setOperationAction(ISD::CTLZ, VT, Expand);
603       setOperationAction(ISD::CTPOP, VT, Expand);
604 
605       setOperationAction(ISD::BSWAP, VT, Expand);
606 
607       // Custom-lower extensions and truncations from/to mask types.
608       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
609       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
610       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
611 
612       // RVV has native int->float & float->int conversions where the
613       // element type sizes are within one power-of-two of each other. Any
614       // wider distances between type sizes have to be lowered as sequences
615       // which progressively narrow the gap in stages.
616       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
617       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
618       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
619       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
620 
621       setOperationAction(ISD::SADDSAT, VT, Legal);
622       setOperationAction(ISD::UADDSAT, VT, Legal);
623       setOperationAction(ISD::SSUBSAT, VT, Legal);
624       setOperationAction(ISD::USUBSAT, VT, Legal);
625 
626       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
627       // nodes which truncate by one power of two at a time.
628       setOperationAction(ISD::TRUNCATE, VT, Custom);
629 
630       // Custom-lower insert/extract operations to simplify patterns.
631       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
632       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
633 
634       // Custom-lower reduction operations to set up the corresponding custom
635       // nodes' operands.
636       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
637       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
638       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
639       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
640       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
641       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
642       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
643       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
644 
645       for (unsigned VPOpc : IntegerVPOps)
646         setOperationAction(VPOpc, VT, Custom);
647 
648       setOperationAction(ISD::LOAD, VT, Custom);
649       setOperationAction(ISD::STORE, VT, Custom);
650 
651       setOperationAction(ISD::MLOAD, VT, Custom);
652       setOperationAction(ISD::MSTORE, VT, Custom);
653       setOperationAction(ISD::MGATHER, VT, Custom);
654       setOperationAction(ISD::MSCATTER, VT, Custom);
655 
656       setOperationAction(ISD::VP_LOAD, VT, Custom);
657       setOperationAction(ISD::VP_STORE, VT, Custom);
658       setOperationAction(ISD::VP_GATHER, VT, Custom);
659       setOperationAction(ISD::VP_SCATTER, VT, Custom);
660 
661       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
662       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
663       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
664 
665       setOperationAction(ISD::SELECT, VT, Custom);
666       setOperationAction(ISD::SELECT_CC, VT, Expand);
667 
668       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
669       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
670 
671       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
672         setTruncStoreAction(VT, OtherVT, Expand);
673         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
674         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
675         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
676       }
677 
678       // Splice
679       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
680 
681       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
682       // type that can represent the value exactly.
683       if (VT.getVectorElementType() != MVT::i64) {
684         MVT FloatEltVT =
685             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
686         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
687         if (isTypeLegal(FloatVT)) {
688           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
689           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
690         }
691       }
692     }
693 
694     // Expand various CCs to best match the RVV ISA, which natively supports UNE
695     // but no other unordered comparisons, and supports all ordered comparisons
696     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
697     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
698     // and we pattern-match those back to the "original", swapping operands once
699     // more. This way we catch both operations and both "vf" and "fv" forms with
700     // fewer patterns.
701     static const ISD::CondCode VFPCCToExpand[] = {
702         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
703         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
704         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
705     };
706 
707     // Sets common operation actions on RVV floating-point vector types.
708     const auto SetCommonVFPActions = [&](MVT VT) {
709       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
710       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
711       // sizes are within one power-of-two of each other. Therefore conversions
712       // between vXf16 and vXf64 must be lowered as sequences which convert via
713       // vXf32.
714       setOperationAction(ISD::FP_ROUND, VT, Custom);
715       setOperationAction(ISD::FP_EXTEND, VT, Custom);
716       // Custom-lower insert/extract operations to simplify patterns.
717       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
718       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
719       // Expand various condition codes (explained above).
720       for (auto CC : VFPCCToExpand)
721         setCondCodeAction(CC, VT, Expand);
722 
723       setOperationAction(ISD::FMINNUM, VT, Legal);
724       setOperationAction(ISD::FMAXNUM, VT, Legal);
725 
726       setOperationAction(ISD::FTRUNC, VT, Custom);
727       setOperationAction(ISD::FCEIL, VT, Custom);
728       setOperationAction(ISD::FFLOOR, VT, Custom);
729       setOperationAction(ISD::FROUND, VT, Custom);
730 
731       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
732       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
733       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
734       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
735 
736       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
737 
738       setOperationAction(ISD::LOAD, VT, Custom);
739       setOperationAction(ISD::STORE, VT, Custom);
740 
741       setOperationAction(ISD::MLOAD, VT, Custom);
742       setOperationAction(ISD::MSTORE, VT, Custom);
743       setOperationAction(ISD::MGATHER, VT, Custom);
744       setOperationAction(ISD::MSCATTER, VT, Custom);
745 
746       setOperationAction(ISD::VP_LOAD, VT, Custom);
747       setOperationAction(ISD::VP_STORE, VT, Custom);
748       setOperationAction(ISD::VP_GATHER, VT, Custom);
749       setOperationAction(ISD::VP_SCATTER, VT, Custom);
750 
751       setOperationAction(ISD::SELECT, VT, Custom);
752       setOperationAction(ISD::SELECT_CC, VT, Expand);
753 
754       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
755       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
756       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
757 
758       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
759       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
760 
761       for (unsigned VPOpc : FloatingPointVPOps)
762         setOperationAction(VPOpc, VT, Custom);
763     };
764 
765     // Sets common extload/truncstore actions on RVV floating-point vector
766     // types.
767     const auto SetCommonVFPExtLoadTruncStoreActions =
768         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
769           for (auto SmallVT : SmallerVTs) {
770             setTruncStoreAction(VT, SmallVT, Expand);
771             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
772           }
773         };
774 
775     if (Subtarget.hasVInstructionsF16())
776       for (MVT VT : F16VecVTs)
777         SetCommonVFPActions(VT);
778 
779     for (MVT VT : F32VecVTs) {
780       if (Subtarget.hasVInstructionsF32())
781         SetCommonVFPActions(VT);
782       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
783     }
784 
785     for (MVT VT : F64VecVTs) {
786       if (Subtarget.hasVInstructionsF64())
787         SetCommonVFPActions(VT);
788       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
789       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
790     }
791 
792     if (Subtarget.useRVVForFixedLengthVectors()) {
793       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
794         if (!useRVVForFixedLengthVectorVT(VT))
795           continue;
796 
797         // By default everything must be expanded.
798         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
799           setOperationAction(Op, VT, Expand);
800         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
801           setTruncStoreAction(VT, OtherVT, Expand);
802           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
803           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
804           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
805         }
806 
807         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
808         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
809         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
810 
811         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
812         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
813 
814         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
815         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
816 
817         setOperationAction(ISD::LOAD, VT, Custom);
818         setOperationAction(ISD::STORE, VT, Custom);
819 
820         setOperationAction(ISD::SETCC, VT, Custom);
821 
822         setOperationAction(ISD::SELECT, VT, Custom);
823 
824         setOperationAction(ISD::TRUNCATE, VT, Custom);
825 
826         setOperationAction(ISD::BITCAST, VT, Custom);
827 
828         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
829         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
830         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
831 
832         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
833         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
834         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
835 
836         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
837         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
838         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
839         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
840 
841         // Operations below are different for between masks and other vectors.
842         if (VT.getVectorElementType() == MVT::i1) {
843           setOperationAction(ISD::VP_AND, VT, Custom);
844           setOperationAction(ISD::VP_OR, VT, Custom);
845           setOperationAction(ISD::VP_XOR, VT, Custom);
846           setOperationAction(ISD::AND, VT, Custom);
847           setOperationAction(ISD::OR, VT, Custom);
848           setOperationAction(ISD::XOR, VT, Custom);
849           continue;
850         }
851 
852         // Use SPLAT_VECTOR to prevent type legalization from destroying the
853         // splats when type legalizing i64 scalar on RV32.
854         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
855         // improvements first.
856         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
857           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
858           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
859         }
860 
861         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
862         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
863 
864         setOperationAction(ISD::MLOAD, VT, Custom);
865         setOperationAction(ISD::MSTORE, VT, Custom);
866         setOperationAction(ISD::MGATHER, VT, Custom);
867         setOperationAction(ISD::MSCATTER, VT, Custom);
868 
869         setOperationAction(ISD::VP_LOAD, VT, Custom);
870         setOperationAction(ISD::VP_STORE, VT, Custom);
871         setOperationAction(ISD::VP_GATHER, VT, Custom);
872         setOperationAction(ISD::VP_SCATTER, VT, Custom);
873 
874         setOperationAction(ISD::ADD, VT, Custom);
875         setOperationAction(ISD::MUL, VT, Custom);
876         setOperationAction(ISD::SUB, VT, Custom);
877         setOperationAction(ISD::AND, VT, Custom);
878         setOperationAction(ISD::OR, VT, Custom);
879         setOperationAction(ISD::XOR, VT, Custom);
880         setOperationAction(ISD::SDIV, VT, Custom);
881         setOperationAction(ISD::SREM, VT, Custom);
882         setOperationAction(ISD::UDIV, VT, Custom);
883         setOperationAction(ISD::UREM, VT, Custom);
884         setOperationAction(ISD::SHL, VT, Custom);
885         setOperationAction(ISD::SRA, VT, Custom);
886         setOperationAction(ISD::SRL, VT, Custom);
887 
888         setOperationAction(ISD::SMIN, VT, Custom);
889         setOperationAction(ISD::SMAX, VT, Custom);
890         setOperationAction(ISD::UMIN, VT, Custom);
891         setOperationAction(ISD::UMAX, VT, Custom);
892         setOperationAction(ISD::ABS,  VT, Custom);
893 
894         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
895         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
896           setOperationAction(ISD::MULHS, VT, Custom);
897           setOperationAction(ISD::MULHU, VT, Custom);
898         }
899 
900         setOperationAction(ISD::SADDSAT, VT, Custom);
901         setOperationAction(ISD::UADDSAT, VT, Custom);
902         setOperationAction(ISD::SSUBSAT, VT, Custom);
903         setOperationAction(ISD::USUBSAT, VT, Custom);
904 
905         setOperationAction(ISD::VSELECT, VT, Custom);
906         setOperationAction(ISD::SELECT_CC, VT, Expand);
907 
908         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
909         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
910         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
911 
912         // Custom-lower reduction operations to set up the corresponding custom
913         // nodes' operands.
914         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
915         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
916         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
917         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
918         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
919 
920         for (unsigned VPOpc : IntegerVPOps)
921           setOperationAction(VPOpc, VT, Custom);
922 
923         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
924         // type that can represent the value exactly.
925         if (VT.getVectorElementType() != MVT::i64) {
926           MVT FloatEltVT =
927               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
928           EVT FloatVT =
929               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
930           if (isTypeLegal(FloatVT)) {
931             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
932             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
933           }
934         }
935       }
936 
937       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
938         if (!useRVVForFixedLengthVectorVT(VT))
939           continue;
940 
941         // By default everything must be expanded.
942         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
943           setOperationAction(Op, VT, Expand);
944         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
945           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
946           setTruncStoreAction(VT, OtherVT, Expand);
947         }
948 
949         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
950         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
951         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
952 
953         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
954         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
955         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
956         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
957         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
958 
959         setOperationAction(ISD::LOAD, VT, Custom);
960         setOperationAction(ISD::STORE, VT, Custom);
961         setOperationAction(ISD::MLOAD, VT, Custom);
962         setOperationAction(ISD::MSTORE, VT, Custom);
963         setOperationAction(ISD::MGATHER, VT, Custom);
964         setOperationAction(ISD::MSCATTER, VT, Custom);
965 
966         setOperationAction(ISD::VP_LOAD, VT, Custom);
967         setOperationAction(ISD::VP_STORE, VT, Custom);
968         setOperationAction(ISD::VP_GATHER, VT, Custom);
969         setOperationAction(ISD::VP_SCATTER, VT, Custom);
970 
971         setOperationAction(ISD::FADD, VT, Custom);
972         setOperationAction(ISD::FSUB, VT, Custom);
973         setOperationAction(ISD::FMUL, VT, Custom);
974         setOperationAction(ISD::FDIV, VT, Custom);
975         setOperationAction(ISD::FNEG, VT, Custom);
976         setOperationAction(ISD::FABS, VT, Custom);
977         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
978         setOperationAction(ISD::FSQRT, VT, Custom);
979         setOperationAction(ISD::FMA, VT, Custom);
980         setOperationAction(ISD::FMINNUM, VT, Custom);
981         setOperationAction(ISD::FMAXNUM, VT, Custom);
982 
983         setOperationAction(ISD::FP_ROUND, VT, Custom);
984         setOperationAction(ISD::FP_EXTEND, VT, Custom);
985 
986         setOperationAction(ISD::FTRUNC, VT, Custom);
987         setOperationAction(ISD::FCEIL, VT, Custom);
988         setOperationAction(ISD::FFLOOR, VT, Custom);
989         setOperationAction(ISD::FROUND, VT, Custom);
990 
991         for (auto CC : VFPCCToExpand)
992           setCondCodeAction(CC, VT, Expand);
993 
994         setOperationAction(ISD::VSELECT, VT, Custom);
995         setOperationAction(ISD::SELECT, VT, Custom);
996         setOperationAction(ISD::SELECT_CC, VT, Expand);
997 
998         setOperationAction(ISD::BITCAST, VT, Custom);
999 
1000         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1001         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1002         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1003         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1004 
1005         for (unsigned VPOpc : FloatingPointVPOps)
1006           setOperationAction(VPOpc, VT, Custom);
1007       }
1008 
1009       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1010       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1011       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1012       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1013       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1014       if (Subtarget.hasStdExtZfh())
1015         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1016       if (Subtarget.hasStdExtF())
1017         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1018       if (Subtarget.hasStdExtD())
1019         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1020     }
1021   }
1022 
1023   // Function alignments.
1024   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1025   setMinFunctionAlignment(FunctionAlignment);
1026   setPrefFunctionAlignment(FunctionAlignment);
1027 
1028   setMinimumJumpTableEntries(5);
1029 
1030   // Jumps are expensive, compared to logic
1031   setJumpIsExpensive();
1032 
1033   setTargetDAGCombine(ISD::ADD);
1034   setTargetDAGCombine(ISD::SUB);
1035   setTargetDAGCombine(ISD::AND);
1036   setTargetDAGCombine(ISD::OR);
1037   setTargetDAGCombine(ISD::XOR);
1038   if (Subtarget.hasStdExtZbp()) {
1039     setTargetDAGCombine(ISD::ROTL);
1040     setTargetDAGCombine(ISD::ROTR);
1041   }
1042   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1043   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1044     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1045   if (Subtarget.hasStdExtF()) {
1046     setTargetDAGCombine(ISD::ZERO_EXTEND);
1047     setTargetDAGCombine(ISD::FP_TO_SINT);
1048     setTargetDAGCombine(ISD::FP_TO_UINT);
1049     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1050     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1051   }
1052   if (Subtarget.hasVInstructions()) {
1053     setTargetDAGCombine(ISD::FCOPYSIGN);
1054     setTargetDAGCombine(ISD::MGATHER);
1055     setTargetDAGCombine(ISD::MSCATTER);
1056     setTargetDAGCombine(ISD::VP_GATHER);
1057     setTargetDAGCombine(ISD::VP_SCATTER);
1058     setTargetDAGCombine(ISD::SRA);
1059     setTargetDAGCombine(ISD::SRL);
1060     setTargetDAGCombine(ISD::SHL);
1061     setTargetDAGCombine(ISD::STORE);
1062     setTargetDAGCombine(ISD::SPLAT_VECTOR);
1063   }
1064 
1065   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1066   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1067 }
1068 
1069 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1070                                             LLVMContext &Context,
1071                                             EVT VT) const {
1072   if (!VT.isVector())
1073     return getPointerTy(DL);
1074   if (Subtarget.hasVInstructions() &&
1075       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1076     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1077   return VT.changeVectorElementTypeToInteger();
1078 }
1079 
1080 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1081   return Subtarget.getXLenVT();
1082 }
1083 
1084 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1085                                              const CallInst &I,
1086                                              MachineFunction &MF,
1087                                              unsigned Intrinsic) const {
1088   auto &DL = I.getModule()->getDataLayout();
1089   switch (Intrinsic) {
1090   default:
1091     return false;
1092   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1093   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1100   case Intrinsic::riscv_masked_cmpxchg_i32:
1101     Info.opc = ISD::INTRINSIC_W_CHAIN;
1102     Info.memVT = MVT::i32;
1103     Info.ptrVal = I.getArgOperand(0);
1104     Info.offset = 0;
1105     Info.align = Align(4);
1106     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1107                  MachineMemOperand::MOVolatile;
1108     return true;
1109   case Intrinsic::riscv_masked_strided_load:
1110     Info.opc = ISD::INTRINSIC_W_CHAIN;
1111     Info.ptrVal = I.getArgOperand(1);
1112     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1113     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1114     Info.size = MemoryLocation::UnknownSize;
1115     Info.flags |= MachineMemOperand::MOLoad;
1116     return true;
1117   case Intrinsic::riscv_masked_strided_store:
1118     Info.opc = ISD::INTRINSIC_VOID;
1119     Info.ptrVal = I.getArgOperand(1);
1120     Info.memVT =
1121         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1122     Info.align = Align(
1123         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1124         8);
1125     Info.size = MemoryLocation::UnknownSize;
1126     Info.flags |= MachineMemOperand::MOStore;
1127     return true;
1128   case Intrinsic::riscv_seg2_load:
1129   case Intrinsic::riscv_seg3_load:
1130   case Intrinsic::riscv_seg4_load:
1131   case Intrinsic::riscv_seg5_load:
1132   case Intrinsic::riscv_seg6_load:
1133   case Intrinsic::riscv_seg7_load:
1134   case Intrinsic::riscv_seg8_load:
1135     Info.opc = ISD::INTRINSIC_W_CHAIN;
1136     Info.ptrVal = I.getArgOperand(0);
1137     Info.memVT =
1138         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1139     Info.align =
1140         Align(DL.getTypeSizeInBits(
1141                   I.getType()->getStructElementType(0)->getScalarType()) /
1142               8);
1143     Info.size = MemoryLocation::UnknownSize;
1144     Info.flags |= MachineMemOperand::MOLoad;
1145     return true;
1146   }
1147 }
1148 
1149 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1150                                                 const AddrMode &AM, Type *Ty,
1151                                                 unsigned AS,
1152                                                 Instruction *I) const {
1153   // No global is ever allowed as a base.
1154   if (AM.BaseGV)
1155     return false;
1156 
1157   // Require a 12-bit signed offset.
1158   if (!isInt<12>(AM.BaseOffs))
1159     return false;
1160 
1161   switch (AM.Scale) {
1162   case 0: // "r+i" or just "i", depending on HasBaseReg.
1163     break;
1164   case 1:
1165     if (!AM.HasBaseReg) // allow "r+i".
1166       break;
1167     return false; // disallow "r+r" or "r+r+i".
1168   default:
1169     return false;
1170   }
1171 
1172   return true;
1173 }
1174 
1175 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1176   return isInt<12>(Imm);
1177 }
1178 
1179 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1180   return isInt<12>(Imm);
1181 }
1182 
1183 // On RV32, 64-bit integers are split into their high and low parts and held
1184 // in two different registers, so the trunc is free since the low register can
1185 // just be used.
1186 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1187   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1188     return false;
1189   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1190   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1191   return (SrcBits == 64 && DestBits == 32);
1192 }
1193 
1194 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1195   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1196       !SrcVT.isInteger() || !DstVT.isInteger())
1197     return false;
1198   unsigned SrcBits = SrcVT.getSizeInBits();
1199   unsigned DestBits = DstVT.getSizeInBits();
1200   return (SrcBits == 64 && DestBits == 32);
1201 }
1202 
1203 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1204   // Zexts are free if they can be combined with a load.
1205   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1206   // poorly with type legalization of compares preferring sext.
1207   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1208     EVT MemVT = LD->getMemoryVT();
1209     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1210         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1211          LD->getExtensionType() == ISD::ZEXTLOAD))
1212       return true;
1213   }
1214 
1215   return TargetLowering::isZExtFree(Val, VT2);
1216 }
1217 
1218 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1219   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1220 }
1221 
1222 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1223   return Subtarget.hasStdExtZbb();
1224 }
1225 
1226 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1227   return Subtarget.hasStdExtZbb();
1228 }
1229 
1230 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1231   EVT VT = Y.getValueType();
1232 
1233   // FIXME: Support vectors once we have tests.
1234   if (VT.isVector())
1235     return false;
1236 
1237   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1238           Subtarget.hasStdExtZbkb()) &&
1239          !isa<ConstantSDNode>(Y);
1240 }
1241 
1242 /// Check if sinking \p I's operands to I's basic block is profitable, because
1243 /// the operands can be folded into a target instruction, e.g.
1244 /// splats of scalars can fold into vector instructions.
1245 bool RISCVTargetLowering::shouldSinkOperands(
1246     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1247   using namespace llvm::PatternMatch;
1248 
1249   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1250     return false;
1251 
1252   auto IsSinker = [&](Instruction *I, int Operand) {
1253     switch (I->getOpcode()) {
1254     case Instruction::Add:
1255     case Instruction::Sub:
1256     case Instruction::Mul:
1257     case Instruction::And:
1258     case Instruction::Or:
1259     case Instruction::Xor:
1260     case Instruction::FAdd:
1261     case Instruction::FSub:
1262     case Instruction::FMul:
1263     case Instruction::FDiv:
1264     case Instruction::ICmp:
1265     case Instruction::FCmp:
1266       return true;
1267     case Instruction::Shl:
1268     case Instruction::LShr:
1269     case Instruction::AShr:
1270     case Instruction::UDiv:
1271     case Instruction::SDiv:
1272     case Instruction::URem:
1273     case Instruction::SRem:
1274       return Operand == 1;
1275     case Instruction::Call:
1276       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1277         switch (II->getIntrinsicID()) {
1278         case Intrinsic::fma:
1279         case Intrinsic::vp_fma:
1280           return Operand == 0 || Operand == 1;
1281         // FIXME: Our patterns can only match vx/vf instructions when the splat
1282         // it on the RHS, because TableGen doesn't recognize our VP operations
1283         // as commutative.
1284         case Intrinsic::vp_add:
1285         case Intrinsic::vp_mul:
1286         case Intrinsic::vp_and:
1287         case Intrinsic::vp_or:
1288         case Intrinsic::vp_xor:
1289         case Intrinsic::vp_fadd:
1290         case Intrinsic::vp_fmul:
1291         case Intrinsic::vp_shl:
1292         case Intrinsic::vp_lshr:
1293         case Intrinsic::vp_ashr:
1294         case Intrinsic::vp_udiv:
1295         case Intrinsic::vp_sdiv:
1296         case Intrinsic::vp_urem:
1297         case Intrinsic::vp_srem:
1298           return Operand == 1;
1299         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1300         // explicit patterns for both LHS and RHS (as 'vr' versions).
1301         case Intrinsic::vp_sub:
1302         case Intrinsic::vp_fsub:
1303         case Intrinsic::vp_fdiv:
1304           return Operand == 0 || Operand == 1;
1305         default:
1306           return false;
1307         }
1308       }
1309       return false;
1310     default:
1311       return false;
1312     }
1313   };
1314 
1315   for (auto OpIdx : enumerate(I->operands())) {
1316     if (!IsSinker(I, OpIdx.index()))
1317       continue;
1318 
1319     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1320     // Make sure we are not already sinking this operand
1321     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1322       continue;
1323 
1324     // We are looking for a splat that can be sunk.
1325     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1326                              m_Undef(), m_ZeroMask())))
1327       continue;
1328 
1329     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1330     // and vector registers
1331     for (Use &U : Op->uses()) {
1332       Instruction *Insn = cast<Instruction>(U.getUser());
1333       if (!IsSinker(Insn, U.getOperandNo()))
1334         return false;
1335     }
1336 
1337     Ops.push_back(&Op->getOperandUse(0));
1338     Ops.push_back(&OpIdx.value());
1339   }
1340   return true;
1341 }
1342 
1343 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1344                                        bool ForCodeSize) const {
1345   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1346   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1347     return false;
1348   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1349     return false;
1350   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1351     return false;
1352   return Imm.isZero();
1353 }
1354 
1355 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1356   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1357          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1358          (VT == MVT::f64 && Subtarget.hasStdExtD());
1359 }
1360 
1361 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1362                                                       CallingConv::ID CC,
1363                                                       EVT VT) const {
1364   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1365   // We might still end up using a GPR but that will be decided based on ABI.
1366   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1367   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1368     return MVT::f32;
1369 
1370   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1371 }
1372 
1373 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1374                                                            CallingConv::ID CC,
1375                                                            EVT VT) const {
1376   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1377   // We might still end up using a GPR but that will be decided based on ABI.
1378   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1379   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1380     return 1;
1381 
1382   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1383 }
1384 
1385 // Changes the condition code and swaps operands if necessary, so the SetCC
1386 // operation matches one of the comparisons supported directly by branches
1387 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1388 // with 1/-1.
1389 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1390                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1391   // Convert X > -1 to X >= 0.
1392   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1393     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1394     CC = ISD::SETGE;
1395     return;
1396   }
1397   // Convert X < 1 to 0 >= X.
1398   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1399     RHS = LHS;
1400     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1401     CC = ISD::SETGE;
1402     return;
1403   }
1404 
1405   switch (CC) {
1406   default:
1407     break;
1408   case ISD::SETGT:
1409   case ISD::SETLE:
1410   case ISD::SETUGT:
1411   case ISD::SETULE:
1412     CC = ISD::getSetCCSwappedOperands(CC);
1413     std::swap(LHS, RHS);
1414     break;
1415   }
1416 }
1417 
1418 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1419   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1420   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1421   if (VT.getVectorElementType() == MVT::i1)
1422     KnownSize *= 8;
1423 
1424   switch (KnownSize) {
1425   default:
1426     llvm_unreachable("Invalid LMUL.");
1427   case 8:
1428     return RISCVII::VLMUL::LMUL_F8;
1429   case 16:
1430     return RISCVII::VLMUL::LMUL_F4;
1431   case 32:
1432     return RISCVII::VLMUL::LMUL_F2;
1433   case 64:
1434     return RISCVII::VLMUL::LMUL_1;
1435   case 128:
1436     return RISCVII::VLMUL::LMUL_2;
1437   case 256:
1438     return RISCVII::VLMUL::LMUL_4;
1439   case 512:
1440     return RISCVII::VLMUL::LMUL_8;
1441   }
1442 }
1443 
1444 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1445   switch (LMul) {
1446   default:
1447     llvm_unreachable("Invalid LMUL.");
1448   case RISCVII::VLMUL::LMUL_F8:
1449   case RISCVII::VLMUL::LMUL_F4:
1450   case RISCVII::VLMUL::LMUL_F2:
1451   case RISCVII::VLMUL::LMUL_1:
1452     return RISCV::VRRegClassID;
1453   case RISCVII::VLMUL::LMUL_2:
1454     return RISCV::VRM2RegClassID;
1455   case RISCVII::VLMUL::LMUL_4:
1456     return RISCV::VRM4RegClassID;
1457   case RISCVII::VLMUL::LMUL_8:
1458     return RISCV::VRM8RegClassID;
1459   }
1460 }
1461 
1462 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1463   RISCVII::VLMUL LMUL = getLMUL(VT);
1464   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1465       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1466       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1467       LMUL == RISCVII::VLMUL::LMUL_1) {
1468     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1469                   "Unexpected subreg numbering");
1470     return RISCV::sub_vrm1_0 + Index;
1471   }
1472   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1473     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1474                   "Unexpected subreg numbering");
1475     return RISCV::sub_vrm2_0 + Index;
1476   }
1477   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1478     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1479                   "Unexpected subreg numbering");
1480     return RISCV::sub_vrm4_0 + Index;
1481   }
1482   llvm_unreachable("Invalid vector type.");
1483 }
1484 
1485 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1486   if (VT.getVectorElementType() == MVT::i1)
1487     return RISCV::VRRegClassID;
1488   return getRegClassIDForLMUL(getLMUL(VT));
1489 }
1490 
1491 // Attempt to decompose a subvector insert/extract between VecVT and
1492 // SubVecVT via subregister indices. Returns the subregister index that
1493 // can perform the subvector insert/extract with the given element index, as
1494 // well as the index corresponding to any leftover subvectors that must be
1495 // further inserted/extracted within the register class for SubVecVT.
1496 std::pair<unsigned, unsigned>
1497 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1498     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1499     const RISCVRegisterInfo *TRI) {
1500   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1501                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1502                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1503                 "Register classes not ordered");
1504   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1505   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1506   // Try to compose a subregister index that takes us from the incoming
1507   // LMUL>1 register class down to the outgoing one. At each step we half
1508   // the LMUL:
1509   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1510   // Note that this is not guaranteed to find a subregister index, such as
1511   // when we are extracting from one VR type to another.
1512   unsigned SubRegIdx = RISCV::NoSubRegister;
1513   for (const unsigned RCID :
1514        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1515     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1516       VecVT = VecVT.getHalfNumVectorElementsVT();
1517       bool IsHi =
1518           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1519       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1520                                             getSubregIndexByMVT(VecVT, IsHi));
1521       if (IsHi)
1522         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1523     }
1524   return {SubRegIdx, InsertExtractIdx};
1525 }
1526 
1527 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1528 // stores for those types.
1529 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1530   return !Subtarget.useRVVForFixedLengthVectors() ||
1531          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1532 }
1533 
1534 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1535   if (ScalarTy->isPointerTy())
1536     return true;
1537 
1538   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1539       ScalarTy->isIntegerTy(32))
1540     return true;
1541 
1542   if (ScalarTy->isIntegerTy(64))
1543     return Subtarget.hasVInstructionsI64();
1544 
1545   if (ScalarTy->isHalfTy())
1546     return Subtarget.hasVInstructionsF16();
1547   if (ScalarTy->isFloatTy())
1548     return Subtarget.hasVInstructionsF32();
1549   if (ScalarTy->isDoubleTy())
1550     return Subtarget.hasVInstructionsF64();
1551 
1552   return false;
1553 }
1554 
1555 static SDValue getVLOperand(SDValue Op) {
1556   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1557           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1558          "Unexpected opcode");
1559   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1560   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1561   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1562       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1563   if (!II)
1564     return SDValue();
1565   return Op.getOperand(II->VLOperand + 1 + HasChain);
1566 }
1567 
1568 static bool useRVVForFixedLengthVectorVT(MVT VT,
1569                                          const RISCVSubtarget &Subtarget) {
1570   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1571   if (!Subtarget.useRVVForFixedLengthVectors())
1572     return false;
1573 
1574   // We only support a set of vector types with a consistent maximum fixed size
1575   // across all supported vector element types to avoid legalization issues.
1576   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1577   // fixed-length vector type we support is 1024 bytes.
1578   if (VT.getFixedSizeInBits() > 1024 * 8)
1579     return false;
1580 
1581   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1582 
1583   MVT EltVT = VT.getVectorElementType();
1584 
1585   // Don't use RVV for vectors we cannot scalarize if required.
1586   switch (EltVT.SimpleTy) {
1587   // i1 is supported but has different rules.
1588   default:
1589     return false;
1590   case MVT::i1:
1591     // Masks can only use a single register.
1592     if (VT.getVectorNumElements() > MinVLen)
1593       return false;
1594     MinVLen /= 8;
1595     break;
1596   case MVT::i8:
1597   case MVT::i16:
1598   case MVT::i32:
1599     break;
1600   case MVT::i64:
1601     if (!Subtarget.hasVInstructionsI64())
1602       return false;
1603     break;
1604   case MVT::f16:
1605     if (!Subtarget.hasVInstructionsF16())
1606       return false;
1607     break;
1608   case MVT::f32:
1609     if (!Subtarget.hasVInstructionsF32())
1610       return false;
1611     break;
1612   case MVT::f64:
1613     if (!Subtarget.hasVInstructionsF64())
1614       return false;
1615     break;
1616   }
1617 
1618   // Reject elements larger than ELEN.
1619   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1620     return false;
1621 
1622   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1623   // Don't use RVV for types that don't fit.
1624   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1625     return false;
1626 
1627   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1628   // the base fixed length RVV support in place.
1629   if (!VT.isPow2VectorType())
1630     return false;
1631 
1632   return true;
1633 }
1634 
1635 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1636   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1637 }
1638 
1639 // Return the largest legal scalable vector type that matches VT's element type.
1640 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1641                                             const RISCVSubtarget &Subtarget) {
1642   // This may be called before legal types are setup.
1643   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1644           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1645          "Expected legal fixed length vector!");
1646 
1647   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1648   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1649 
1650   MVT EltVT = VT.getVectorElementType();
1651   switch (EltVT.SimpleTy) {
1652   default:
1653     llvm_unreachable("unexpected element type for RVV container");
1654   case MVT::i1:
1655   case MVT::i8:
1656   case MVT::i16:
1657   case MVT::i32:
1658   case MVT::i64:
1659   case MVT::f16:
1660   case MVT::f32:
1661   case MVT::f64: {
1662     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1663     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1664     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1665     unsigned NumElts =
1666         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1667     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1668     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1669     return MVT::getScalableVectorVT(EltVT, NumElts);
1670   }
1671   }
1672 }
1673 
1674 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1675                                             const RISCVSubtarget &Subtarget) {
1676   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1677                                           Subtarget);
1678 }
1679 
1680 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1681   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1682 }
1683 
1684 // Grow V to consume an entire RVV register.
1685 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1686                                        const RISCVSubtarget &Subtarget) {
1687   assert(VT.isScalableVector() &&
1688          "Expected to convert into a scalable vector!");
1689   assert(V.getValueType().isFixedLengthVector() &&
1690          "Expected a fixed length vector operand!");
1691   SDLoc DL(V);
1692   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1693   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1694 }
1695 
1696 // Shrink V so it's just big enough to maintain a VT's worth of data.
1697 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1698                                          const RISCVSubtarget &Subtarget) {
1699   assert(VT.isFixedLengthVector() &&
1700          "Expected to convert into a fixed length vector!");
1701   assert(V.getValueType().isScalableVector() &&
1702          "Expected a scalable vector operand!");
1703   SDLoc DL(V);
1704   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1705   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1706 }
1707 
1708 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1709 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1710 // the vector type that it is contained in.
1711 static std::pair<SDValue, SDValue>
1712 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1713                 const RISCVSubtarget &Subtarget) {
1714   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1715   MVT XLenVT = Subtarget.getXLenVT();
1716   SDValue VL = VecVT.isFixedLengthVector()
1717                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1718                    : DAG.getRegister(RISCV::X0, XLenVT);
1719   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1720   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1721   return {Mask, VL};
1722 }
1723 
1724 // As above but assuming the given type is a scalable vector type.
1725 static std::pair<SDValue, SDValue>
1726 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1727                         const RISCVSubtarget &Subtarget) {
1728   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1729   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1730 }
1731 
1732 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1733 // of either is (currently) supported. This can get us into an infinite loop
1734 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1735 // as a ..., etc.
1736 // Until either (or both) of these can reliably lower any node, reporting that
1737 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1738 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1739 // which is not desirable.
1740 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1741     EVT VT, unsigned DefinedValues) const {
1742   return false;
1743 }
1744 
1745 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1746                                   const RISCVSubtarget &Subtarget) {
1747   // RISCV FP-to-int conversions saturate to the destination register size, but
1748   // don't produce 0 for nan. We can use a conversion instruction and fix the
1749   // nan case with a compare and a select.
1750   SDValue Src = Op.getOperand(0);
1751 
1752   EVT DstVT = Op.getValueType();
1753   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1754 
1755   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1756   unsigned Opc;
1757   if (SatVT == DstVT)
1758     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1759   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1760     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1761   else
1762     return SDValue();
1763   // FIXME: Support other SatVTs by clamping before or after the conversion.
1764 
1765   SDLoc DL(Op);
1766   SDValue FpToInt = DAG.getNode(
1767       Opc, DL, DstVT, Src,
1768       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1769 
1770   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1771   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1772 }
1773 
1774 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1775 // and back. Taking care to avoid converting values that are nan or already
1776 // correct.
1777 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1778 // have FRM dependencies modeled yet.
1779 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1780   MVT VT = Op.getSimpleValueType();
1781   assert(VT.isVector() && "Unexpected type");
1782 
1783   SDLoc DL(Op);
1784 
1785   // Freeze the source since we are increasing the number of uses.
1786   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1787 
1788   // Truncate to integer and convert back to FP.
1789   MVT IntVT = VT.changeVectorElementTypeToInteger();
1790   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1791   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1792 
1793   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1794 
1795   if (Op.getOpcode() == ISD::FCEIL) {
1796     // If the truncated value is the greater than or equal to the original
1797     // value, we've computed the ceil. Otherwise, we went the wrong way and
1798     // need to increase by 1.
1799     // FIXME: This should use a masked operation. Handle here or in isel?
1800     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1801                                  DAG.getConstantFP(1.0, DL, VT));
1802     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1803     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1804   } else if (Op.getOpcode() == ISD::FFLOOR) {
1805     // If the truncated value is the less than or equal to the original value,
1806     // we've computed the floor. Otherwise, we went the wrong way and need to
1807     // decrease by 1.
1808     // FIXME: This should use a masked operation. Handle here or in isel?
1809     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1810                                  DAG.getConstantFP(1.0, DL, VT));
1811     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1812     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1813   }
1814 
1815   // Restore the original sign so that -0.0 is preserved.
1816   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1817 
1818   // Determine the largest integer that can be represented exactly. This and
1819   // values larger than it don't have any fractional bits so don't need to
1820   // be converted.
1821   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1822   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1823   APFloat MaxVal = APFloat(FltSem);
1824   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1825                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1826   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1827 
1828   // If abs(Src) was larger than MaxVal or nan, keep it.
1829   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1830   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1831   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1832 }
1833 
1834 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1835 // This mode isn't supported in vector hardware on RISCV. But as long as we
1836 // aren't compiling with trapping math, we can emulate this with
1837 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1838 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1839 // dependencies modeled yet.
1840 // FIXME: Use masked operations to avoid final merge.
1841 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1842   MVT VT = Op.getSimpleValueType();
1843   assert(VT.isVector() && "Unexpected type");
1844 
1845   SDLoc DL(Op);
1846 
1847   // Freeze the source since we are increasing the number of uses.
1848   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1849 
1850   // We do the conversion on the absolute value and fix the sign at the end.
1851   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1852 
1853   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1854   bool Ignored;
1855   APFloat Point5Pred = APFloat(0.5f);
1856   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1857   Point5Pred.next(/*nextDown*/ true);
1858 
1859   // Add the adjustment.
1860   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1861                                DAG.getConstantFP(Point5Pred, DL, VT));
1862 
1863   // Truncate to integer and convert back to fp.
1864   MVT IntVT = VT.changeVectorElementTypeToInteger();
1865   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1866   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1867 
1868   // Restore the original sign.
1869   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1870 
1871   // Determine the largest integer that can be represented exactly. This and
1872   // values larger than it don't have any fractional bits so don't need to
1873   // be converted.
1874   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1875   APFloat MaxVal = APFloat(FltSem);
1876   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1877                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1878   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1879 
1880   // If abs(Src) was larger than MaxVal or nan, keep it.
1881   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1882   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1883   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1884 }
1885 
1886 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1887                                  const RISCVSubtarget &Subtarget) {
1888   MVT VT = Op.getSimpleValueType();
1889   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1890 
1891   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1892 
1893   SDLoc DL(Op);
1894   SDValue Mask, VL;
1895   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1896 
1897   unsigned Opc =
1898       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1899   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
1900                               Op.getOperand(0), VL);
1901   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1902 }
1903 
1904 struct VIDSequence {
1905   int64_t StepNumerator;
1906   unsigned StepDenominator;
1907   int64_t Addend;
1908 };
1909 
1910 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1911 // to the (non-zero) step S and start value X. This can be then lowered as the
1912 // RVV sequence (VID * S) + X, for example.
1913 // The step S is represented as an integer numerator divided by a positive
1914 // denominator. Note that the implementation currently only identifies
1915 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1916 // cannot detect 2/3, for example.
1917 // Note that this method will also match potentially unappealing index
1918 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1919 // determine whether this is worth generating code for.
1920 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1921   unsigned NumElts = Op.getNumOperands();
1922   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1923   if (!Op.getValueType().isInteger())
1924     return None;
1925 
1926   Optional<unsigned> SeqStepDenom;
1927   Optional<int64_t> SeqStepNum, SeqAddend;
1928   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1929   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1930   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1931     // Assume undef elements match the sequence; we just have to be careful
1932     // when interpolating across them.
1933     if (Op.getOperand(Idx).isUndef())
1934       continue;
1935     // The BUILD_VECTOR must be all constants.
1936     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1937       return None;
1938 
1939     uint64_t Val = Op.getConstantOperandVal(Idx) &
1940                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1941 
1942     if (PrevElt) {
1943       // Calculate the step since the last non-undef element, and ensure
1944       // it's consistent across the entire sequence.
1945       unsigned IdxDiff = Idx - PrevElt->second;
1946       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1947 
1948       // A zero-value value difference means that we're somewhere in the middle
1949       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1950       // step change before evaluating the sequence.
1951       if (ValDiff != 0) {
1952         int64_t Remainder = ValDiff % IdxDiff;
1953         // Normalize the step if it's greater than 1.
1954         if (Remainder != ValDiff) {
1955           // The difference must cleanly divide the element span.
1956           if (Remainder != 0)
1957             return None;
1958           ValDiff /= IdxDiff;
1959           IdxDiff = 1;
1960         }
1961 
1962         if (!SeqStepNum)
1963           SeqStepNum = ValDiff;
1964         else if (ValDiff != SeqStepNum)
1965           return None;
1966 
1967         if (!SeqStepDenom)
1968           SeqStepDenom = IdxDiff;
1969         else if (IdxDiff != *SeqStepDenom)
1970           return None;
1971       }
1972     }
1973 
1974     // Record and/or check any addend.
1975     if (SeqStepNum && SeqStepDenom) {
1976       uint64_t ExpectedVal =
1977           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1978       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1979       if (!SeqAddend)
1980         SeqAddend = Addend;
1981       else if (SeqAddend != Addend)
1982         return None;
1983     }
1984 
1985     // Record this non-undef element for later.
1986     if (!PrevElt || PrevElt->first != Val)
1987       PrevElt = std::make_pair(Val, Idx);
1988   }
1989   // We need to have logged both a step and an addend for this to count as
1990   // a legal index sequence.
1991   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1992     return None;
1993 
1994   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1995 }
1996 
1997 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1998 // and lower it as a VRGATHER_VX_VL from the source vector.
1999 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
2000                                   SelectionDAG &DAG,
2001                                   const RISCVSubtarget &Subtarget) {
2002   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2003     return SDValue();
2004   SDValue Vec = SplatVal.getOperand(0);
2005   // Only perform this optimization on vectors of the same size for simplicity.
2006   if (Vec.getValueType() != VT)
2007     return SDValue();
2008   SDValue Idx = SplatVal.getOperand(1);
2009   // The index must be a legal type.
2010   if (Idx.getValueType() != Subtarget.getXLenVT())
2011     return SDValue();
2012 
2013   MVT ContainerVT = VT;
2014   if (VT.isFixedLengthVector()) {
2015     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2016     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2017   }
2018 
2019   SDValue Mask, VL;
2020   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2021 
2022   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2023                                Idx, Mask, VL);
2024 
2025   if (!VT.isFixedLengthVector())
2026     return Gather;
2027 
2028   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2029 }
2030 
2031 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2032                                  const RISCVSubtarget &Subtarget) {
2033   MVT VT = Op.getSimpleValueType();
2034   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2035 
2036   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2037 
2038   SDLoc DL(Op);
2039   SDValue Mask, VL;
2040   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2041 
2042   MVT XLenVT = Subtarget.getXLenVT();
2043   unsigned NumElts = Op.getNumOperands();
2044 
2045   if (VT.getVectorElementType() == MVT::i1) {
2046     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2047       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2048       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2049     }
2050 
2051     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2052       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2053       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2054     }
2055 
2056     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2057     // scalar integer chunks whose bit-width depends on the number of mask
2058     // bits and XLEN.
2059     // First, determine the most appropriate scalar integer type to use. This
2060     // is at most XLenVT, but may be shrunk to a smaller vector element type
2061     // according to the size of the final vector - use i8 chunks rather than
2062     // XLenVT if we're producing a v8i1. This results in more consistent
2063     // codegen across RV32 and RV64.
2064     unsigned NumViaIntegerBits =
2065         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2066     NumViaIntegerBits = std::min(NumViaIntegerBits,
2067                                  Subtarget.getMaxELENForFixedLengthVectors());
2068     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2069       // If we have to use more than one INSERT_VECTOR_ELT then this
2070       // optimization is likely to increase code size; avoid peforming it in
2071       // such a case. We can use a load from a constant pool in this case.
2072       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2073         return SDValue();
2074       // Now we can create our integer vector type. Note that it may be larger
2075       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2076       MVT IntegerViaVecVT =
2077           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2078                            divideCeil(NumElts, NumViaIntegerBits));
2079 
2080       uint64_t Bits = 0;
2081       unsigned BitPos = 0, IntegerEltIdx = 0;
2082       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2083 
2084       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2085         // Once we accumulate enough bits to fill our scalar type, insert into
2086         // our vector and clear our accumulated data.
2087         if (I != 0 && I % NumViaIntegerBits == 0) {
2088           if (NumViaIntegerBits <= 32)
2089             Bits = SignExtend64(Bits, 32);
2090           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2091           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2092                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2093           Bits = 0;
2094           BitPos = 0;
2095           IntegerEltIdx++;
2096         }
2097         SDValue V = Op.getOperand(I);
2098         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2099         Bits |= ((uint64_t)BitValue << BitPos);
2100       }
2101 
2102       // Insert the (remaining) scalar value into position in our integer
2103       // vector type.
2104       if (NumViaIntegerBits <= 32)
2105         Bits = SignExtend64(Bits, 32);
2106       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2107       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2108                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2109 
2110       if (NumElts < NumViaIntegerBits) {
2111         // If we're producing a smaller vector than our minimum legal integer
2112         // type, bitcast to the equivalent (known-legal) mask type, and extract
2113         // our final mask.
2114         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2115         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2116         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2117                           DAG.getConstant(0, DL, XLenVT));
2118       } else {
2119         // Else we must have produced an integer type with the same size as the
2120         // mask type; bitcast for the final result.
2121         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2122         Vec = DAG.getBitcast(VT, Vec);
2123       }
2124 
2125       return Vec;
2126     }
2127 
2128     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2129     // vector type, we have a legal equivalently-sized i8 type, so we can use
2130     // that.
2131     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2132     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2133 
2134     SDValue WideVec;
2135     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2136       // For a splat, perform a scalar truncate before creating the wider
2137       // vector.
2138       assert(Splat.getValueType() == XLenVT &&
2139              "Unexpected type for i1 splat value");
2140       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2141                           DAG.getConstant(1, DL, XLenVT));
2142       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2143     } else {
2144       SmallVector<SDValue, 8> Ops(Op->op_values());
2145       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2146       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2147       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2148     }
2149 
2150     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2151   }
2152 
2153   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2154     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2155       return Gather;
2156     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2157                                         : RISCVISD::VMV_V_X_VL;
2158     Splat =
2159         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2160     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2161   }
2162 
2163   // Try and match index sequences, which we can lower to the vid instruction
2164   // with optional modifications. An all-undef vector is matched by
2165   // getSplatValue, above.
2166   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2167     int64_t StepNumerator = SimpleVID->StepNumerator;
2168     unsigned StepDenominator = SimpleVID->StepDenominator;
2169     int64_t Addend = SimpleVID->Addend;
2170 
2171     assert(StepNumerator != 0 && "Invalid step");
2172     bool Negate = false;
2173     int64_t SplatStepVal = StepNumerator;
2174     unsigned StepOpcode = ISD::MUL;
2175     if (StepNumerator != 1) {
2176       if (isPowerOf2_64(std::abs(StepNumerator))) {
2177         Negate = StepNumerator < 0;
2178         StepOpcode = ISD::SHL;
2179         SplatStepVal = Log2_64(std::abs(StepNumerator));
2180       }
2181     }
2182 
2183     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2184     // threshold since it's the immediate value many RVV instructions accept.
2185     // There is no vmul.vi instruction so ensure multiply constant can fit in
2186     // a single addi instruction.
2187     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2188          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2189         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2190       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2191       // Convert right out of the scalable type so we can use standard ISD
2192       // nodes for the rest of the computation. If we used scalable types with
2193       // these, we'd lose the fixed-length vector info and generate worse
2194       // vsetvli code.
2195       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2196       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2197           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2198         SDValue SplatStep = DAG.getSplatVector(
2199             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2200         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2201       }
2202       if (StepDenominator != 1) {
2203         SDValue SplatStep = DAG.getSplatVector(
2204             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2205         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2206       }
2207       if (Addend != 0 || Negate) {
2208         SDValue SplatAddend =
2209             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2210         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2211       }
2212       return VID;
2213     }
2214   }
2215 
2216   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2217   // when re-interpreted as a vector with a larger element type. For example,
2218   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2219   // could be instead splat as
2220   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2221   // TODO: This optimization could also work on non-constant splats, but it
2222   // would require bit-manipulation instructions to construct the splat value.
2223   SmallVector<SDValue> Sequence;
2224   unsigned EltBitSize = VT.getScalarSizeInBits();
2225   const auto *BV = cast<BuildVectorSDNode>(Op);
2226   if (VT.isInteger() && EltBitSize < 64 &&
2227       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2228       BV->getRepeatedSequence(Sequence) &&
2229       (Sequence.size() * EltBitSize) <= 64) {
2230     unsigned SeqLen = Sequence.size();
2231     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2232     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2233     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2234             ViaIntVT == MVT::i64) &&
2235            "Unexpected sequence type");
2236 
2237     unsigned EltIdx = 0;
2238     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2239     uint64_t SplatValue = 0;
2240     // Construct the amalgamated value which can be splatted as this larger
2241     // vector type.
2242     for (const auto &SeqV : Sequence) {
2243       if (!SeqV.isUndef())
2244         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2245                        << (EltIdx * EltBitSize));
2246       EltIdx++;
2247     }
2248 
2249     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2250     // achieve better constant materializion.
2251     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2252       SplatValue = SignExtend64(SplatValue, 32);
2253 
2254     // Since we can't introduce illegal i64 types at this stage, we can only
2255     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2256     // way we can use RVV instructions to splat.
2257     assert((ViaIntVT.bitsLE(XLenVT) ||
2258             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2259            "Unexpected bitcast sequence");
2260     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2261       SDValue ViaVL =
2262           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2263       MVT ViaContainerVT =
2264           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2265       SDValue Splat =
2266           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2267                       DAG.getUNDEF(ViaContainerVT),
2268                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2269       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2270       return DAG.getBitcast(VT, Splat);
2271     }
2272   }
2273 
2274   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2275   // which constitute a large proportion of the elements. In such cases we can
2276   // splat a vector with the dominant element and make up the shortfall with
2277   // INSERT_VECTOR_ELTs.
2278   // Note that this includes vectors of 2 elements by association. The
2279   // upper-most element is the "dominant" one, allowing us to use a splat to
2280   // "insert" the upper element, and an insert of the lower element at position
2281   // 0, which improves codegen.
2282   SDValue DominantValue;
2283   unsigned MostCommonCount = 0;
2284   DenseMap<SDValue, unsigned> ValueCounts;
2285   unsigned NumUndefElts =
2286       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2287 
2288   // Track the number of scalar loads we know we'd be inserting, estimated as
2289   // any non-zero floating-point constant. Other kinds of element are either
2290   // already in registers or are materialized on demand. The threshold at which
2291   // a vector load is more desirable than several scalar materializion and
2292   // vector-insertion instructions is not known.
2293   unsigned NumScalarLoads = 0;
2294 
2295   for (SDValue V : Op->op_values()) {
2296     if (V.isUndef())
2297       continue;
2298 
2299     ValueCounts.insert(std::make_pair(V, 0));
2300     unsigned &Count = ValueCounts[V];
2301 
2302     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2303       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2304 
2305     // Is this value dominant? In case of a tie, prefer the highest element as
2306     // it's cheaper to insert near the beginning of a vector than it is at the
2307     // end.
2308     if (++Count >= MostCommonCount) {
2309       DominantValue = V;
2310       MostCommonCount = Count;
2311     }
2312   }
2313 
2314   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2315   unsigned NumDefElts = NumElts - NumUndefElts;
2316   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2317 
2318   // Don't perform this optimization when optimizing for size, since
2319   // materializing elements and inserting them tends to cause code bloat.
2320   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2321       ((MostCommonCount > DominantValueCountThreshold) ||
2322        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2323     // Start by splatting the most common element.
2324     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2325 
2326     DenseSet<SDValue> Processed{DominantValue};
2327     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2328     for (const auto &OpIdx : enumerate(Op->ops())) {
2329       const SDValue &V = OpIdx.value();
2330       if (V.isUndef() || !Processed.insert(V).second)
2331         continue;
2332       if (ValueCounts[V] == 1) {
2333         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2334                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2335       } else {
2336         // Blend in all instances of this value using a VSELECT, using a
2337         // mask where each bit signals whether that element is the one
2338         // we're after.
2339         SmallVector<SDValue> Ops;
2340         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2341           return DAG.getConstant(V == V1, DL, XLenVT);
2342         });
2343         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2344                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2345                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2346       }
2347     }
2348 
2349     return Vec;
2350   }
2351 
2352   return SDValue();
2353 }
2354 
2355 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2356                                    SDValue Lo, SDValue Hi, SDValue VL,
2357                                    SelectionDAG &DAG) {
2358   bool HasPassthru = Passthru && !Passthru.isUndef();
2359   if (!HasPassthru && !Passthru)
2360     Passthru = DAG.getUNDEF(VT);
2361   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2362     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2363     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2364     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2365     // node in order to try and match RVV vector/scalar instructions.
2366     if ((LoC >> 31) == HiC)
2367       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2368 
2369     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2370     // vmv.v.x whose EEW = 32 to lower it.
2371     auto *Const = dyn_cast<ConstantSDNode>(VL);
2372     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2373       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2374       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2375       // access the subtarget here now.
2376       auto InterVec = DAG.getNode(
2377           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2378                                   DAG.getRegister(RISCV::X0, MVT::i32));
2379       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2380     }
2381   }
2382 
2383   // Fall back to a stack store and stride x0 vector load.
2384   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2385                      Hi, VL);
2386 }
2387 
2388 // Called by type legalization to handle splat of i64 on RV32.
2389 // FIXME: We can optimize this when the type has sign or zero bits in one
2390 // of the halves.
2391 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2392                                    SDValue Scalar, SDValue VL,
2393                                    SelectionDAG &DAG) {
2394   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2395   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2396                            DAG.getConstant(0, DL, MVT::i32));
2397   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2398                            DAG.getConstant(1, DL, MVT::i32));
2399   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2400 }
2401 
2402 // This function lowers a splat of a scalar operand Splat with the vector
2403 // length VL. It ensures the final sequence is type legal, which is useful when
2404 // lowering a splat after type legalization.
2405 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2406                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2407                                 const RISCVSubtarget &Subtarget) {
2408   bool HasPassthru = Passthru && !Passthru.isUndef();
2409   if (!HasPassthru && !Passthru)
2410     Passthru = DAG.getUNDEF(VT);
2411   if (VT.isFloatingPoint()) {
2412     // If VL is 1, we could use vfmv.s.f.
2413     if (isOneConstant(VL))
2414       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2415     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2416   }
2417 
2418   MVT XLenVT = Subtarget.getXLenVT();
2419 
2420   // Simplest case is that the operand needs to be promoted to XLenVT.
2421   if (Scalar.getValueType().bitsLE(XLenVT)) {
2422     // If the operand is a constant, sign extend to increase our chances
2423     // of being able to use a .vi instruction. ANY_EXTEND would become a
2424     // a zero extend and the simm5 check in isel would fail.
2425     // FIXME: Should we ignore the upper bits in isel instead?
2426     unsigned ExtOpc =
2427         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2428     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2429     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2430     // If VL is 1 and the scalar value won't benefit from immediate, we could
2431     // use vmv.s.x.
2432     if (isOneConstant(VL) &&
2433         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2434       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2435     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2436   }
2437 
2438   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2439          "Unexpected scalar for splat lowering!");
2440 
2441   if (isOneConstant(VL) && isNullConstant(Scalar))
2442     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2443                        DAG.getConstant(0, DL, XLenVT), VL);
2444 
2445   // Otherwise use the more complicated splatting algorithm.
2446   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2447 }
2448 
2449 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2450                                 const RISCVSubtarget &Subtarget) {
2451   // We need to be able to widen elements to the next larger integer type.
2452   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2453     return false;
2454 
2455   int Size = Mask.size();
2456   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2457 
2458   int Srcs[] = {-1, -1};
2459   for (int i = 0; i != Size; ++i) {
2460     // Ignore undef elements.
2461     if (Mask[i] < 0)
2462       continue;
2463 
2464     // Is this an even or odd element.
2465     int Pol = i % 2;
2466 
2467     // Ensure we consistently use the same source for this element polarity.
2468     int Src = Mask[i] / Size;
2469     if (Srcs[Pol] < 0)
2470       Srcs[Pol] = Src;
2471     if (Srcs[Pol] != Src)
2472       return false;
2473 
2474     // Make sure the element within the source is appropriate for this element
2475     // in the destination.
2476     int Elt = Mask[i] % Size;
2477     if (Elt != i / 2)
2478       return false;
2479   }
2480 
2481   // We need to find a source for each polarity and they can't be the same.
2482   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2483     return false;
2484 
2485   // Swap the sources if the second source was in the even polarity.
2486   SwapSources = Srcs[0] > Srcs[1];
2487 
2488   return true;
2489 }
2490 
2491 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2492 /// and then extract the original number of elements from the rotated result.
2493 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2494 /// returned rotation amount is for a rotate right, where elements move from
2495 /// higher elements to lower elements. \p LoSrc indicates the first source
2496 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2497 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2498 /// 0 or 1 if a rotation is found.
2499 ///
2500 /// NOTE: We talk about rotate to the right which matches how bit shift and
2501 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2502 /// and the table below write vectors with the lowest elements on the left.
2503 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2504   int Size = Mask.size();
2505 
2506   // We need to detect various ways of spelling a rotation:
2507   //   [11, 12, 13, 14, 15,  0,  1,  2]
2508   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2509   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2510   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2511   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2512   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2513   int Rotation = 0;
2514   LoSrc = -1;
2515   HiSrc = -1;
2516   for (int i = 0; i != Size; ++i) {
2517     int M = Mask[i];
2518     if (M < 0)
2519       continue;
2520 
2521     // Determine where a rotate vector would have started.
2522     int StartIdx = i - (M % Size);
2523     // The identity rotation isn't interesting, stop.
2524     if (StartIdx == 0)
2525       return -1;
2526 
2527     // If we found the tail of a vector the rotation must be the missing
2528     // front. If we found the head of a vector, it must be how much of the
2529     // head.
2530     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2531 
2532     if (Rotation == 0)
2533       Rotation = CandidateRotation;
2534     else if (Rotation != CandidateRotation)
2535       // The rotations don't match, so we can't match this mask.
2536       return -1;
2537 
2538     // Compute which value this mask is pointing at.
2539     int MaskSrc = M < Size ? 0 : 1;
2540 
2541     // Compute which of the two target values this index should be assigned to.
2542     // This reflects whether the high elements are remaining or the low elemnts
2543     // are remaining.
2544     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2545 
2546     // Either set up this value if we've not encountered it before, or check
2547     // that it remains consistent.
2548     if (TargetSrc < 0)
2549       TargetSrc = MaskSrc;
2550     else if (TargetSrc != MaskSrc)
2551       // This may be a rotation, but it pulls from the inputs in some
2552       // unsupported interleaving.
2553       return -1;
2554   }
2555 
2556   // Check that we successfully analyzed the mask, and normalize the results.
2557   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2558   assert((LoSrc >= 0 || HiSrc >= 0) &&
2559          "Failed to find a rotated input vector!");
2560 
2561   return Rotation;
2562 }
2563 
2564 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2565                                    const RISCVSubtarget &Subtarget) {
2566   SDValue V1 = Op.getOperand(0);
2567   SDValue V2 = Op.getOperand(1);
2568   SDLoc DL(Op);
2569   MVT XLenVT = Subtarget.getXLenVT();
2570   MVT VT = Op.getSimpleValueType();
2571   unsigned NumElts = VT.getVectorNumElements();
2572   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2573 
2574   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2575 
2576   SDValue TrueMask, VL;
2577   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2578 
2579   if (SVN->isSplat()) {
2580     const int Lane = SVN->getSplatIndex();
2581     if (Lane >= 0) {
2582       MVT SVT = VT.getVectorElementType();
2583 
2584       // Turn splatted vector load into a strided load with an X0 stride.
2585       SDValue V = V1;
2586       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2587       // with undef.
2588       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2589       int Offset = Lane;
2590       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2591         int OpElements =
2592             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2593         V = V.getOperand(Offset / OpElements);
2594         Offset %= OpElements;
2595       }
2596 
2597       // We need to ensure the load isn't atomic or volatile.
2598       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2599         auto *Ld = cast<LoadSDNode>(V);
2600         Offset *= SVT.getStoreSize();
2601         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2602                                                    TypeSize::Fixed(Offset), DL);
2603 
2604         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2605         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2606           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2607           SDValue IntID =
2608               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2609           SDValue Ops[] = {Ld->getChain(),
2610                            IntID,
2611                            DAG.getUNDEF(ContainerVT),
2612                            NewAddr,
2613                            DAG.getRegister(RISCV::X0, XLenVT),
2614                            VL};
2615           SDValue NewLoad = DAG.getMemIntrinsicNode(
2616               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2617               DAG.getMachineFunction().getMachineMemOperand(
2618                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2619           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2620           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2621         }
2622 
2623         // Otherwise use a scalar load and splat. This will give the best
2624         // opportunity to fold a splat into the operation. ISel can turn it into
2625         // the x0 strided load if we aren't able to fold away the select.
2626         if (SVT.isFloatingPoint())
2627           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2628                           Ld->getPointerInfo().getWithOffset(Offset),
2629                           Ld->getOriginalAlign(),
2630                           Ld->getMemOperand()->getFlags());
2631         else
2632           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2633                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2634                              Ld->getOriginalAlign(),
2635                              Ld->getMemOperand()->getFlags());
2636         DAG.makeEquivalentMemoryOrdering(Ld, V);
2637 
2638         unsigned Opc =
2639             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2640         SDValue Splat =
2641             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2642         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2643       }
2644 
2645       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2646       assert(Lane < (int)NumElts && "Unexpected lane!");
2647       SDValue Gather =
2648           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2649                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2650       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2651     }
2652   }
2653 
2654   ArrayRef<int> Mask = SVN->getMask();
2655 
2656   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2657   // be undef which can be handled with a single SLIDEDOWN/UP.
2658   int LoSrc, HiSrc;
2659   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2660   if (Rotation > 0) {
2661     SDValue LoV, HiV;
2662     if (LoSrc >= 0) {
2663       LoV = LoSrc == 0 ? V1 : V2;
2664       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2665     }
2666     if (HiSrc >= 0) {
2667       HiV = HiSrc == 0 ? V1 : V2;
2668       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2669     }
2670 
2671     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2672     // to slide LoV up by (NumElts - Rotation).
2673     unsigned InvRotate = NumElts - Rotation;
2674 
2675     SDValue Res = DAG.getUNDEF(ContainerVT);
2676     if (HiV) {
2677       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2678       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2679       // causes multiple vsetvlis in some test cases such as lowering
2680       // reduce.mul
2681       SDValue DownVL = VL;
2682       if (LoV)
2683         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2684       Res =
2685           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2686                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2687     }
2688     if (LoV)
2689       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2690                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2691 
2692     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2693   }
2694 
2695   // Detect an interleave shuffle and lower to
2696   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2697   bool SwapSources;
2698   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2699     // Swap sources if needed.
2700     if (SwapSources)
2701       std::swap(V1, V2);
2702 
2703     // Extract the lower half of the vectors.
2704     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2705     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2706                      DAG.getConstant(0, DL, XLenVT));
2707     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2708                      DAG.getConstant(0, DL, XLenVT));
2709 
2710     // Double the element width and halve the number of elements in an int type.
2711     unsigned EltBits = VT.getScalarSizeInBits();
2712     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2713     MVT WideIntVT =
2714         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2715     // Convert this to a scalable vector. We need to base this on the
2716     // destination size to ensure there's always a type with a smaller LMUL.
2717     MVT WideIntContainerVT =
2718         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2719 
2720     // Convert sources to scalable vectors with the same element count as the
2721     // larger type.
2722     MVT HalfContainerVT = MVT::getVectorVT(
2723         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2724     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2725     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2726 
2727     // Cast sources to integer.
2728     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2729     MVT IntHalfVT =
2730         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2731     V1 = DAG.getBitcast(IntHalfVT, V1);
2732     V2 = DAG.getBitcast(IntHalfVT, V2);
2733 
2734     // Freeze V2 since we use it twice and we need to be sure that the add and
2735     // multiply see the same value.
2736     V2 = DAG.getFreeze(V2);
2737 
2738     // Recreate TrueMask using the widened type's element count.
2739     MVT MaskVT =
2740         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2741     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2742 
2743     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2744     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2745                               V2, TrueMask, VL);
2746     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2747     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2748                                      DAG.getUNDEF(IntHalfVT),
2749                                      DAG.getAllOnesConstant(DL, XLenVT));
2750     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2751                                    V2, Multiplier, TrueMask, VL);
2752     // Add the new copies to our previous addition giving us 2^eltbits copies of
2753     // V2. This is equivalent to shifting V2 left by eltbits. This should
2754     // combine with the vwmulu.vv above to form vwmaccu.vv.
2755     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2756                       TrueMask, VL);
2757     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2758     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2759     // vector VT.
2760     ContainerVT =
2761         MVT::getVectorVT(VT.getVectorElementType(),
2762                          WideIntContainerVT.getVectorElementCount() * 2);
2763     Add = DAG.getBitcast(ContainerVT, Add);
2764     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2765   }
2766 
2767   // Detect shuffles which can be re-expressed as vector selects; these are
2768   // shuffles in which each element in the destination is taken from an element
2769   // at the corresponding index in either source vectors.
2770   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2771     int MaskIndex = MaskIdx.value();
2772     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2773   });
2774 
2775   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2776 
2777   SmallVector<SDValue> MaskVals;
2778   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2779   // merged with a second vrgather.
2780   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2781 
2782   // By default we preserve the original operand order, and use a mask to
2783   // select LHS as true and RHS as false. However, since RVV vector selects may
2784   // feature splats but only on the LHS, we may choose to invert our mask and
2785   // instead select between RHS and LHS.
2786   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2787   bool InvertMask = IsSelect == SwapOps;
2788 
2789   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2790   // half.
2791   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2792 
2793   // Now construct the mask that will be used by the vselect or blended
2794   // vrgather operation. For vrgathers, construct the appropriate indices into
2795   // each vector.
2796   for (int MaskIndex : Mask) {
2797     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2798     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2799     if (!IsSelect) {
2800       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2801       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2802                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2803                                      : DAG.getUNDEF(XLenVT));
2804       GatherIndicesRHS.push_back(
2805           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2806                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2807       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2808         ++LHSIndexCounts[MaskIndex];
2809       if (!IsLHSOrUndefIndex)
2810         ++RHSIndexCounts[MaskIndex - NumElts];
2811     }
2812   }
2813 
2814   if (SwapOps) {
2815     std::swap(V1, V2);
2816     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2817   }
2818 
2819   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2820   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2821   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2822 
2823   if (IsSelect)
2824     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2825 
2826   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2827     // On such a large vector we're unable to use i8 as the index type.
2828     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2829     // may involve vector splitting if we're already at LMUL=8, or our
2830     // user-supplied maximum fixed-length LMUL.
2831     return SDValue();
2832   }
2833 
2834   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2835   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2836   MVT IndexVT = VT.changeTypeToInteger();
2837   // Since we can't introduce illegal index types at this stage, use i16 and
2838   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2839   // than XLenVT.
2840   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2841     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2842     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2843   }
2844 
2845   MVT IndexContainerVT =
2846       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2847 
2848   SDValue Gather;
2849   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2850   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2851   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2852     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2853                               Subtarget);
2854   } else {
2855     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2856     // If only one index is used, we can use a "splat" vrgather.
2857     // TODO: We can splat the most-common index and fix-up any stragglers, if
2858     // that's beneficial.
2859     if (LHSIndexCounts.size() == 1) {
2860       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2861       Gather =
2862           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2863                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2864     } else {
2865       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2866       LHSIndices =
2867           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2868 
2869       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2870                            TrueMask, VL);
2871     }
2872   }
2873 
2874   // If a second vector operand is used by this shuffle, blend it in with an
2875   // additional vrgather.
2876   if (!V2.isUndef()) {
2877     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2878     // If only one index is used, we can use a "splat" vrgather.
2879     // TODO: We can splat the most-common index and fix-up any stragglers, if
2880     // that's beneficial.
2881     if (RHSIndexCounts.size() == 1) {
2882       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2883       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2884                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2885     } else {
2886       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2887       RHSIndices =
2888           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2889       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2890                        VL);
2891     }
2892 
2893     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2894     SelectMask =
2895         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2896 
2897     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2898                          Gather, VL);
2899   }
2900 
2901   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2902 }
2903 
2904 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2905   // Support splats for any type. These should type legalize well.
2906   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2907     return true;
2908 
2909   // Only support legal VTs for other shuffles for now.
2910   if (!isTypeLegal(VT))
2911     return false;
2912 
2913   MVT SVT = VT.getSimpleVT();
2914 
2915   bool SwapSources;
2916   int LoSrc, HiSrc;
2917   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2918          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2919 }
2920 
2921 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2922                                      SDLoc DL, SelectionDAG &DAG,
2923                                      const RISCVSubtarget &Subtarget) {
2924   if (VT.isScalableVector())
2925     return DAG.getFPExtendOrRound(Op, DL, VT);
2926   assert(VT.isFixedLengthVector() &&
2927          "Unexpected value type for RVV FP extend/round lowering");
2928   SDValue Mask, VL;
2929   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2930   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2931                         ? RISCVISD::FP_EXTEND_VL
2932                         : RISCVISD::FP_ROUND_VL;
2933   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2934 }
2935 
2936 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2937 // the exponent.
2938 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2939   MVT VT = Op.getSimpleValueType();
2940   unsigned EltSize = VT.getScalarSizeInBits();
2941   SDValue Src = Op.getOperand(0);
2942   SDLoc DL(Op);
2943 
2944   // We need a FP type that can represent the value.
2945   // TODO: Use f16 for i8 when possible?
2946   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2947   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2948 
2949   // Legal types should have been checked in the RISCVTargetLowering
2950   // constructor.
2951   // TODO: Splitting may make sense in some cases.
2952   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2953          "Expected legal float type!");
2954 
2955   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2956   // The trailing zero count is equal to log2 of this single bit value.
2957   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2958     SDValue Neg =
2959         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2960     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2961   }
2962 
2963   // We have a legal FP type, convert to it.
2964   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2965   // Bitcast to integer and shift the exponent to the LSB.
2966   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2967   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2968   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2969   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2970                               DAG.getConstant(ShiftAmt, DL, IntVT));
2971   // Truncate back to original type to allow vnsrl.
2972   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2973   // The exponent contains log2 of the value in biased form.
2974   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2975 
2976   // For trailing zeros, we just need to subtract the bias.
2977   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2978     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2979                        DAG.getConstant(ExponentBias, DL, VT));
2980 
2981   // For leading zeros, we need to remove the bias and convert from log2 to
2982   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2983   unsigned Adjust = ExponentBias + (EltSize - 1);
2984   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2985 }
2986 
2987 // While RVV has alignment restrictions, we should always be able to load as a
2988 // legal equivalently-sized byte-typed vector instead. This method is
2989 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2990 // the load is already correctly-aligned, it returns SDValue().
2991 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2992                                                     SelectionDAG &DAG) const {
2993   auto *Load = cast<LoadSDNode>(Op);
2994   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2995 
2996   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2997                                      Load->getMemoryVT(),
2998                                      *Load->getMemOperand()))
2999     return SDValue();
3000 
3001   SDLoc DL(Op);
3002   MVT VT = Op.getSimpleValueType();
3003   unsigned EltSizeBits = VT.getScalarSizeInBits();
3004   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3005          "Unexpected unaligned RVV load type");
3006   MVT NewVT =
3007       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3008   assert(NewVT.isValid() &&
3009          "Expecting equally-sized RVV vector types to be legal");
3010   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3011                           Load->getPointerInfo(), Load->getOriginalAlign(),
3012                           Load->getMemOperand()->getFlags());
3013   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3014 }
3015 
3016 // While RVV has alignment restrictions, we should always be able to store as a
3017 // legal equivalently-sized byte-typed vector instead. This method is
3018 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3019 // returns SDValue() if the store is already correctly aligned.
3020 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3021                                                      SelectionDAG &DAG) const {
3022   auto *Store = cast<StoreSDNode>(Op);
3023   assert(Store && Store->getValue().getValueType().isVector() &&
3024          "Expected vector store");
3025 
3026   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3027                                      Store->getMemoryVT(),
3028                                      *Store->getMemOperand()))
3029     return SDValue();
3030 
3031   SDLoc DL(Op);
3032   SDValue StoredVal = Store->getValue();
3033   MVT VT = StoredVal.getSimpleValueType();
3034   unsigned EltSizeBits = VT.getScalarSizeInBits();
3035   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3036          "Unexpected unaligned RVV store type");
3037   MVT NewVT =
3038       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3039   assert(NewVT.isValid() &&
3040          "Expecting equally-sized RVV vector types to be legal");
3041   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3042   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3043                       Store->getPointerInfo(), Store->getOriginalAlign(),
3044                       Store->getMemOperand()->getFlags());
3045 }
3046 
3047 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3048                                             SelectionDAG &DAG) const {
3049   switch (Op.getOpcode()) {
3050   default:
3051     report_fatal_error("unimplemented operand");
3052   case ISD::GlobalAddress:
3053     return lowerGlobalAddress(Op, DAG);
3054   case ISD::BlockAddress:
3055     return lowerBlockAddress(Op, DAG);
3056   case ISD::ConstantPool:
3057     return lowerConstantPool(Op, DAG);
3058   case ISD::JumpTable:
3059     return lowerJumpTable(Op, DAG);
3060   case ISD::GlobalTLSAddress:
3061     return lowerGlobalTLSAddress(Op, DAG);
3062   case ISD::SELECT:
3063     return lowerSELECT(Op, DAG);
3064   case ISD::BRCOND:
3065     return lowerBRCOND(Op, DAG);
3066   case ISD::VASTART:
3067     return lowerVASTART(Op, DAG);
3068   case ISD::FRAMEADDR:
3069     return lowerFRAMEADDR(Op, DAG);
3070   case ISD::RETURNADDR:
3071     return lowerRETURNADDR(Op, DAG);
3072   case ISD::SHL_PARTS:
3073     return lowerShiftLeftParts(Op, DAG);
3074   case ISD::SRA_PARTS:
3075     return lowerShiftRightParts(Op, DAG, true);
3076   case ISD::SRL_PARTS:
3077     return lowerShiftRightParts(Op, DAG, false);
3078   case ISD::BITCAST: {
3079     SDLoc DL(Op);
3080     EVT VT = Op.getValueType();
3081     SDValue Op0 = Op.getOperand(0);
3082     EVT Op0VT = Op0.getValueType();
3083     MVT XLenVT = Subtarget.getXLenVT();
3084     if (VT.isFixedLengthVector()) {
3085       // We can handle fixed length vector bitcasts with a simple replacement
3086       // in isel.
3087       if (Op0VT.isFixedLengthVector())
3088         return Op;
3089       // When bitcasting from scalar to fixed-length vector, insert the scalar
3090       // into a one-element vector of the result type, and perform a vector
3091       // bitcast.
3092       if (!Op0VT.isVector()) {
3093         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3094         if (!isTypeLegal(BVT))
3095           return SDValue();
3096         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3097                                               DAG.getUNDEF(BVT), Op0,
3098                                               DAG.getConstant(0, DL, XLenVT)));
3099       }
3100       return SDValue();
3101     }
3102     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3103     // thus: bitcast the vector to a one-element vector type whose element type
3104     // is the same as the result type, and extract the first element.
3105     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3106       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3107       if (!isTypeLegal(BVT))
3108         return SDValue();
3109       SDValue BVec = DAG.getBitcast(BVT, Op0);
3110       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3111                          DAG.getConstant(0, DL, XLenVT));
3112     }
3113     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3114       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3115       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3116       return FPConv;
3117     }
3118     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3119         Subtarget.hasStdExtF()) {
3120       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3121       SDValue FPConv =
3122           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3123       return FPConv;
3124     }
3125     return SDValue();
3126   }
3127   case ISD::INTRINSIC_WO_CHAIN:
3128     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3129   case ISD::INTRINSIC_W_CHAIN:
3130     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3131   case ISD::INTRINSIC_VOID:
3132     return LowerINTRINSIC_VOID(Op, DAG);
3133   case ISD::BSWAP:
3134   case ISD::BITREVERSE: {
3135     MVT VT = Op.getSimpleValueType();
3136     SDLoc DL(Op);
3137     if (Subtarget.hasStdExtZbp()) {
3138       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3139       // Start with the maximum immediate value which is the bitwidth - 1.
3140       unsigned Imm = VT.getSizeInBits() - 1;
3141       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3142       if (Op.getOpcode() == ISD::BSWAP)
3143         Imm &= ~0x7U;
3144       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3145                          DAG.getConstant(Imm, DL, VT));
3146     }
3147     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3148     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3149     // Expand bitreverse to a bswap(rev8) followed by brev8.
3150     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3151     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3152     // as brev8 by an isel pattern.
3153     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3154                        DAG.getConstant(7, DL, VT));
3155   }
3156   case ISD::FSHL:
3157   case ISD::FSHR: {
3158     MVT VT = Op.getSimpleValueType();
3159     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3160     SDLoc DL(Op);
3161     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3162     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3163     // accidentally setting the extra bit.
3164     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3165     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3166                                 DAG.getConstant(ShAmtWidth, DL, VT));
3167     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3168     // instruction use different orders. fshl will return its first operand for
3169     // shift of zero, fshr will return its second operand. fsl and fsr both
3170     // return rs1 so the ISD nodes need to have different operand orders.
3171     // Shift amount is in rs2.
3172     SDValue Op0 = Op.getOperand(0);
3173     SDValue Op1 = Op.getOperand(1);
3174     unsigned Opc = RISCVISD::FSL;
3175     if (Op.getOpcode() == ISD::FSHR) {
3176       std::swap(Op0, Op1);
3177       Opc = RISCVISD::FSR;
3178     }
3179     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3180   }
3181   case ISD::TRUNCATE: {
3182     SDLoc DL(Op);
3183     MVT VT = Op.getSimpleValueType();
3184     // Only custom-lower vector truncates
3185     if (!VT.isVector())
3186       return Op;
3187 
3188     // Truncates to mask types are handled differently
3189     if (VT.getVectorElementType() == MVT::i1)
3190       return lowerVectorMaskTrunc(Op, DAG);
3191 
3192     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3193     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3194     // truncate by one power of two at a time.
3195     MVT DstEltVT = VT.getVectorElementType();
3196 
3197     SDValue Src = Op.getOperand(0);
3198     MVT SrcVT = Src.getSimpleValueType();
3199     MVT SrcEltVT = SrcVT.getVectorElementType();
3200 
3201     assert(DstEltVT.bitsLT(SrcEltVT) &&
3202            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3203            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3204            "Unexpected vector truncate lowering");
3205 
3206     MVT ContainerVT = SrcVT;
3207     if (SrcVT.isFixedLengthVector()) {
3208       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3209       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3210     }
3211 
3212     SDValue Result = Src;
3213     SDValue Mask, VL;
3214     std::tie(Mask, VL) =
3215         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3216     LLVMContext &Context = *DAG.getContext();
3217     const ElementCount Count = ContainerVT.getVectorElementCount();
3218     do {
3219       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3220       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3221       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3222                            Mask, VL);
3223     } while (SrcEltVT != DstEltVT);
3224 
3225     if (SrcVT.isFixedLengthVector())
3226       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3227 
3228     return Result;
3229   }
3230   case ISD::ANY_EXTEND:
3231   case ISD::ZERO_EXTEND:
3232     if (Op.getOperand(0).getValueType().isVector() &&
3233         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3234       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3235     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3236   case ISD::SIGN_EXTEND:
3237     if (Op.getOperand(0).getValueType().isVector() &&
3238         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3239       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3240     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3241   case ISD::SPLAT_VECTOR_PARTS:
3242     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3243   case ISD::INSERT_VECTOR_ELT:
3244     return lowerINSERT_VECTOR_ELT(Op, DAG);
3245   case ISD::EXTRACT_VECTOR_ELT:
3246     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3247   case ISD::VSCALE: {
3248     MVT VT = Op.getSimpleValueType();
3249     SDLoc DL(Op);
3250     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3251     // We define our scalable vector types for lmul=1 to use a 64 bit known
3252     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3253     // vscale as VLENB / 8.
3254     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3255     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3256       report_fatal_error("Support for VLEN==32 is incomplete.");
3257     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3258       // We assume VLENB is a multiple of 8. We manually choose the best shift
3259       // here because SimplifyDemandedBits isn't always able to simplify it.
3260       uint64_t Val = Op.getConstantOperandVal(0);
3261       if (isPowerOf2_64(Val)) {
3262         uint64_t Log2 = Log2_64(Val);
3263         if (Log2 < 3)
3264           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3265                              DAG.getConstant(3 - Log2, DL, VT));
3266         if (Log2 > 3)
3267           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3268                              DAG.getConstant(Log2 - 3, DL, VT));
3269         return VLENB;
3270       }
3271       // If the multiplier is a multiple of 8, scale it down to avoid needing
3272       // to shift the VLENB value.
3273       if ((Val % 8) == 0)
3274         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3275                            DAG.getConstant(Val / 8, DL, VT));
3276     }
3277 
3278     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3279                                  DAG.getConstant(3, DL, VT));
3280     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3281   }
3282   case ISD::FPOWI: {
3283     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3284     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3285     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3286         Op.getOperand(1).getValueType() == MVT::i32) {
3287       SDLoc DL(Op);
3288       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3289       SDValue Powi =
3290           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3291       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3292                          DAG.getIntPtrConstant(0, DL));
3293     }
3294     return SDValue();
3295   }
3296   case ISD::FP_EXTEND: {
3297     // RVV can only do fp_extend to types double the size as the source. We
3298     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3299     // via f32.
3300     SDLoc DL(Op);
3301     MVT VT = Op.getSimpleValueType();
3302     SDValue Src = Op.getOperand(0);
3303     MVT SrcVT = Src.getSimpleValueType();
3304 
3305     // Prepare any fixed-length vector operands.
3306     MVT ContainerVT = VT;
3307     if (SrcVT.isFixedLengthVector()) {
3308       ContainerVT = getContainerForFixedLengthVector(VT);
3309       MVT SrcContainerVT =
3310           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3311       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3312     }
3313 
3314     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3315         SrcVT.getVectorElementType() != MVT::f16) {
3316       // For scalable vectors, we only need to close the gap between
3317       // vXf16->vXf64.
3318       if (!VT.isFixedLengthVector())
3319         return Op;
3320       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3321       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3322       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3323     }
3324 
3325     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3326     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3327     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3328         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3329 
3330     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3331                                            DL, DAG, Subtarget);
3332     if (VT.isFixedLengthVector())
3333       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3334     return Extend;
3335   }
3336   case ISD::FP_ROUND: {
3337     // RVV can only do fp_round to types half the size as the source. We
3338     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3339     // conversion instruction.
3340     SDLoc DL(Op);
3341     MVT VT = Op.getSimpleValueType();
3342     SDValue Src = Op.getOperand(0);
3343     MVT SrcVT = Src.getSimpleValueType();
3344 
3345     // Prepare any fixed-length vector operands.
3346     MVT ContainerVT = VT;
3347     if (VT.isFixedLengthVector()) {
3348       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3349       ContainerVT =
3350           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3351       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3352     }
3353 
3354     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3355         SrcVT.getVectorElementType() != MVT::f64) {
3356       // For scalable vectors, we only need to close the gap between
3357       // vXf64<->vXf16.
3358       if (!VT.isFixedLengthVector())
3359         return Op;
3360       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3361       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3362       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3363     }
3364 
3365     SDValue Mask, VL;
3366     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3367 
3368     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3369     SDValue IntermediateRound =
3370         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3371     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3372                                           DL, DAG, Subtarget);
3373 
3374     if (VT.isFixedLengthVector())
3375       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3376     return Round;
3377   }
3378   case ISD::FP_TO_SINT:
3379   case ISD::FP_TO_UINT:
3380   case ISD::SINT_TO_FP:
3381   case ISD::UINT_TO_FP: {
3382     // RVV can only do fp<->int conversions to types half/double the size as
3383     // the source. We custom-lower any conversions that do two hops into
3384     // sequences.
3385     MVT VT = Op.getSimpleValueType();
3386     if (!VT.isVector())
3387       return Op;
3388     SDLoc DL(Op);
3389     SDValue Src = Op.getOperand(0);
3390     MVT EltVT = VT.getVectorElementType();
3391     MVT SrcVT = Src.getSimpleValueType();
3392     MVT SrcEltVT = SrcVT.getVectorElementType();
3393     unsigned EltSize = EltVT.getSizeInBits();
3394     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3395     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3396            "Unexpected vector element types");
3397 
3398     bool IsInt2FP = SrcEltVT.isInteger();
3399     // Widening conversions
3400     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3401       if (IsInt2FP) {
3402         // Do a regular integer sign/zero extension then convert to float.
3403         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3404                                       VT.getVectorElementCount());
3405         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3406                                  ? ISD::ZERO_EXTEND
3407                                  : ISD::SIGN_EXTEND;
3408         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3409         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3410       }
3411       // FP2Int
3412       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3413       // Do one doubling fp_extend then complete the operation by converting
3414       // to int.
3415       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3416       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3417       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3418     }
3419 
3420     // Narrowing conversions
3421     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3422       if (IsInt2FP) {
3423         // One narrowing int_to_fp, then an fp_round.
3424         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3425         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3426         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3427         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3428       }
3429       // FP2Int
3430       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3431       // representable by the integer, the result is poison.
3432       MVT IVecVT =
3433           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3434                            VT.getVectorElementCount());
3435       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3436       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3437     }
3438 
3439     // Scalable vectors can exit here. Patterns will handle equally-sized
3440     // conversions halving/doubling ones.
3441     if (!VT.isFixedLengthVector())
3442       return Op;
3443 
3444     // For fixed-length vectors we lower to a custom "VL" node.
3445     unsigned RVVOpc = 0;
3446     switch (Op.getOpcode()) {
3447     default:
3448       llvm_unreachable("Impossible opcode");
3449     case ISD::FP_TO_SINT:
3450       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3451       break;
3452     case ISD::FP_TO_UINT:
3453       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3454       break;
3455     case ISD::SINT_TO_FP:
3456       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3457       break;
3458     case ISD::UINT_TO_FP:
3459       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3460       break;
3461     }
3462 
3463     MVT ContainerVT, SrcContainerVT;
3464     // Derive the reference container type from the larger vector type.
3465     if (SrcEltSize > EltSize) {
3466       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3467       ContainerVT =
3468           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3469     } else {
3470       ContainerVT = getContainerForFixedLengthVector(VT);
3471       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3472     }
3473 
3474     SDValue Mask, VL;
3475     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3476 
3477     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3478     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3479     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3480   }
3481   case ISD::FP_TO_SINT_SAT:
3482   case ISD::FP_TO_UINT_SAT:
3483     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3484   case ISD::FTRUNC:
3485   case ISD::FCEIL:
3486   case ISD::FFLOOR:
3487     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3488   case ISD::FROUND:
3489     return lowerFROUND(Op, DAG);
3490   case ISD::VECREDUCE_ADD:
3491   case ISD::VECREDUCE_UMAX:
3492   case ISD::VECREDUCE_SMAX:
3493   case ISD::VECREDUCE_UMIN:
3494   case ISD::VECREDUCE_SMIN:
3495     return lowerVECREDUCE(Op, DAG);
3496   case ISD::VECREDUCE_AND:
3497   case ISD::VECREDUCE_OR:
3498   case ISD::VECREDUCE_XOR:
3499     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3500       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3501     return lowerVECREDUCE(Op, DAG);
3502   case ISD::VECREDUCE_FADD:
3503   case ISD::VECREDUCE_SEQ_FADD:
3504   case ISD::VECREDUCE_FMIN:
3505   case ISD::VECREDUCE_FMAX:
3506     return lowerFPVECREDUCE(Op, DAG);
3507   case ISD::VP_REDUCE_ADD:
3508   case ISD::VP_REDUCE_UMAX:
3509   case ISD::VP_REDUCE_SMAX:
3510   case ISD::VP_REDUCE_UMIN:
3511   case ISD::VP_REDUCE_SMIN:
3512   case ISD::VP_REDUCE_FADD:
3513   case ISD::VP_REDUCE_SEQ_FADD:
3514   case ISD::VP_REDUCE_FMIN:
3515   case ISD::VP_REDUCE_FMAX:
3516     return lowerVPREDUCE(Op, DAG);
3517   case ISD::VP_REDUCE_AND:
3518   case ISD::VP_REDUCE_OR:
3519   case ISD::VP_REDUCE_XOR:
3520     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3521       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3522     return lowerVPREDUCE(Op, DAG);
3523   case ISD::INSERT_SUBVECTOR:
3524     return lowerINSERT_SUBVECTOR(Op, DAG);
3525   case ISD::EXTRACT_SUBVECTOR:
3526     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3527   case ISD::STEP_VECTOR:
3528     return lowerSTEP_VECTOR(Op, DAG);
3529   case ISD::VECTOR_REVERSE:
3530     return lowerVECTOR_REVERSE(Op, DAG);
3531   case ISD::VECTOR_SPLICE:
3532     return lowerVECTOR_SPLICE(Op, DAG);
3533   case ISD::BUILD_VECTOR:
3534     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3535   case ISD::SPLAT_VECTOR:
3536     if (Op.getValueType().getVectorElementType() == MVT::i1)
3537       return lowerVectorMaskSplat(Op, DAG);
3538     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3539   case ISD::VECTOR_SHUFFLE:
3540     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3541   case ISD::CONCAT_VECTORS: {
3542     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3543     // better than going through the stack, as the default expansion does.
3544     SDLoc DL(Op);
3545     MVT VT = Op.getSimpleValueType();
3546     unsigned NumOpElts =
3547         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3548     SDValue Vec = DAG.getUNDEF(VT);
3549     for (const auto &OpIdx : enumerate(Op->ops())) {
3550       SDValue SubVec = OpIdx.value();
3551       // Don't insert undef subvectors.
3552       if (SubVec.isUndef())
3553         continue;
3554       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3555                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3556     }
3557     return Vec;
3558   }
3559   case ISD::LOAD:
3560     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3561       return V;
3562     if (Op.getValueType().isFixedLengthVector())
3563       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3564     return Op;
3565   case ISD::STORE:
3566     if (auto V = expandUnalignedRVVStore(Op, DAG))
3567       return V;
3568     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3569       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3570     return Op;
3571   case ISD::MLOAD:
3572   case ISD::VP_LOAD:
3573     return lowerMaskedLoad(Op, DAG);
3574   case ISD::MSTORE:
3575   case ISD::VP_STORE:
3576     return lowerMaskedStore(Op, DAG);
3577   case ISD::SETCC:
3578     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3579   case ISD::ADD:
3580     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3581   case ISD::SUB:
3582     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3583   case ISD::MUL:
3584     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3585   case ISD::MULHS:
3586     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3587   case ISD::MULHU:
3588     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3589   case ISD::AND:
3590     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3591                                               RISCVISD::AND_VL);
3592   case ISD::OR:
3593     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3594                                               RISCVISD::OR_VL);
3595   case ISD::XOR:
3596     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3597                                               RISCVISD::XOR_VL);
3598   case ISD::SDIV:
3599     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3600   case ISD::SREM:
3601     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3602   case ISD::UDIV:
3603     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3604   case ISD::UREM:
3605     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3606   case ISD::SHL:
3607   case ISD::SRA:
3608   case ISD::SRL:
3609     if (Op.getSimpleValueType().isFixedLengthVector())
3610       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3611     // This can be called for an i32 shift amount that needs to be promoted.
3612     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3613            "Unexpected custom legalisation");
3614     return SDValue();
3615   case ISD::SADDSAT:
3616     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3617   case ISD::UADDSAT:
3618     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3619   case ISD::SSUBSAT:
3620     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3621   case ISD::USUBSAT:
3622     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3623   case ISD::FADD:
3624     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3625   case ISD::FSUB:
3626     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3627   case ISD::FMUL:
3628     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3629   case ISD::FDIV:
3630     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3631   case ISD::FNEG:
3632     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3633   case ISD::FABS:
3634     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3635   case ISD::FSQRT:
3636     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3637   case ISD::FMA:
3638     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3639   case ISD::SMIN:
3640     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3641   case ISD::SMAX:
3642     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3643   case ISD::UMIN:
3644     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3645   case ISD::UMAX:
3646     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3647   case ISD::FMINNUM:
3648     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3649   case ISD::FMAXNUM:
3650     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3651   case ISD::ABS:
3652     return lowerABS(Op, DAG);
3653   case ISD::CTLZ_ZERO_UNDEF:
3654   case ISD::CTTZ_ZERO_UNDEF:
3655     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3656   case ISD::VSELECT:
3657     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3658   case ISD::FCOPYSIGN:
3659     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3660   case ISD::MGATHER:
3661   case ISD::VP_GATHER:
3662     return lowerMaskedGather(Op, DAG);
3663   case ISD::MSCATTER:
3664   case ISD::VP_SCATTER:
3665     return lowerMaskedScatter(Op, DAG);
3666   case ISD::FLT_ROUNDS_:
3667     return lowerGET_ROUNDING(Op, DAG);
3668   case ISD::SET_ROUNDING:
3669     return lowerSET_ROUNDING(Op, DAG);
3670   case ISD::VP_SELECT:
3671     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3672   case ISD::VP_MERGE:
3673     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3674   case ISD::VP_ADD:
3675     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3676   case ISD::VP_SUB:
3677     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3678   case ISD::VP_MUL:
3679     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3680   case ISD::VP_SDIV:
3681     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3682   case ISD::VP_UDIV:
3683     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3684   case ISD::VP_SREM:
3685     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3686   case ISD::VP_UREM:
3687     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3688   case ISD::VP_AND:
3689     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3690   case ISD::VP_OR:
3691     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3692   case ISD::VP_XOR:
3693     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3694   case ISD::VP_ASHR:
3695     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3696   case ISD::VP_LSHR:
3697     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3698   case ISD::VP_SHL:
3699     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3700   case ISD::VP_FADD:
3701     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3702   case ISD::VP_FSUB:
3703     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3704   case ISD::VP_FMUL:
3705     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3706   case ISD::VP_FDIV:
3707     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3708   case ISD::VP_FNEG:
3709     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3710   case ISD::VP_FMA:
3711     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3712   }
3713 }
3714 
3715 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3716                              SelectionDAG &DAG, unsigned Flags) {
3717   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3718 }
3719 
3720 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3721                              SelectionDAG &DAG, unsigned Flags) {
3722   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3723                                    Flags);
3724 }
3725 
3726 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3727                              SelectionDAG &DAG, unsigned Flags) {
3728   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3729                                    N->getOffset(), Flags);
3730 }
3731 
3732 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3733                              SelectionDAG &DAG, unsigned Flags) {
3734   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3735 }
3736 
3737 template <class NodeTy>
3738 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3739                                      bool IsLocal) const {
3740   SDLoc DL(N);
3741   EVT Ty = getPointerTy(DAG.getDataLayout());
3742 
3743   if (isPositionIndependent()) {
3744     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3745     if (IsLocal)
3746       // Use PC-relative addressing to access the symbol. This generates the
3747       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3748       // %pcrel_lo(auipc)).
3749       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3750 
3751     // Use PC-relative addressing to access the GOT for this symbol, then load
3752     // the address from the GOT. This generates the pattern (PseudoLA sym),
3753     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3754     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3755   }
3756 
3757   switch (getTargetMachine().getCodeModel()) {
3758   default:
3759     report_fatal_error("Unsupported code model for lowering");
3760   case CodeModel::Small: {
3761     // Generate a sequence for accessing addresses within the first 2 GiB of
3762     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3763     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3764     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3765     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3766     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3767   }
3768   case CodeModel::Medium: {
3769     // Generate a sequence for accessing addresses within any 2GiB range within
3770     // the address space. This generates the pattern (PseudoLLA sym), which
3771     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3772     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3773     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3774   }
3775   }
3776 }
3777 
3778 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3779                                                 SelectionDAG &DAG) const {
3780   SDLoc DL(Op);
3781   EVT Ty = Op.getValueType();
3782   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3783   int64_t Offset = N->getOffset();
3784   MVT XLenVT = Subtarget.getXLenVT();
3785 
3786   const GlobalValue *GV = N->getGlobal();
3787   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3788   SDValue Addr = getAddr(N, DAG, IsLocal);
3789 
3790   // In order to maximise the opportunity for common subexpression elimination,
3791   // emit a separate ADD node for the global address offset instead of folding
3792   // it in the global address node. Later peephole optimisations may choose to
3793   // fold it back in when profitable.
3794   if (Offset != 0)
3795     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3796                        DAG.getConstant(Offset, DL, XLenVT));
3797   return Addr;
3798 }
3799 
3800 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3801                                                SelectionDAG &DAG) const {
3802   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3803 
3804   return getAddr(N, DAG);
3805 }
3806 
3807 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3808                                                SelectionDAG &DAG) const {
3809   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3810 
3811   return getAddr(N, DAG);
3812 }
3813 
3814 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3815                                             SelectionDAG &DAG) const {
3816   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3817 
3818   return getAddr(N, DAG);
3819 }
3820 
3821 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3822                                               SelectionDAG &DAG,
3823                                               bool UseGOT) const {
3824   SDLoc DL(N);
3825   EVT Ty = getPointerTy(DAG.getDataLayout());
3826   const GlobalValue *GV = N->getGlobal();
3827   MVT XLenVT = Subtarget.getXLenVT();
3828 
3829   if (UseGOT) {
3830     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3831     // load the address from the GOT and add the thread pointer. This generates
3832     // the pattern (PseudoLA_TLS_IE sym), which expands to
3833     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3834     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3835     SDValue Load =
3836         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3837 
3838     // Add the thread pointer.
3839     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3840     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3841   }
3842 
3843   // Generate a sequence for accessing the address relative to the thread
3844   // pointer, with the appropriate adjustment for the thread pointer offset.
3845   // This generates the pattern
3846   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3847   SDValue AddrHi =
3848       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3849   SDValue AddrAdd =
3850       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3851   SDValue AddrLo =
3852       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3853 
3854   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3855   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3856   SDValue MNAdd = SDValue(
3857       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3858       0);
3859   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3860 }
3861 
3862 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3863                                                SelectionDAG &DAG) const {
3864   SDLoc DL(N);
3865   EVT Ty = getPointerTy(DAG.getDataLayout());
3866   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3867   const GlobalValue *GV = N->getGlobal();
3868 
3869   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3870   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3871   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3872   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3873   SDValue Load =
3874       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3875 
3876   // Prepare argument list to generate call.
3877   ArgListTy Args;
3878   ArgListEntry Entry;
3879   Entry.Node = Load;
3880   Entry.Ty = CallTy;
3881   Args.push_back(Entry);
3882 
3883   // Setup call to __tls_get_addr.
3884   TargetLowering::CallLoweringInfo CLI(DAG);
3885   CLI.setDebugLoc(DL)
3886       .setChain(DAG.getEntryNode())
3887       .setLibCallee(CallingConv::C, CallTy,
3888                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3889                     std::move(Args));
3890 
3891   return LowerCallTo(CLI).first;
3892 }
3893 
3894 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3895                                                    SelectionDAG &DAG) const {
3896   SDLoc DL(Op);
3897   EVT Ty = Op.getValueType();
3898   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3899   int64_t Offset = N->getOffset();
3900   MVT XLenVT = Subtarget.getXLenVT();
3901 
3902   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3903 
3904   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3905       CallingConv::GHC)
3906     report_fatal_error("In GHC calling convention TLS is not supported");
3907 
3908   SDValue Addr;
3909   switch (Model) {
3910   case TLSModel::LocalExec:
3911     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3912     break;
3913   case TLSModel::InitialExec:
3914     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3915     break;
3916   case TLSModel::LocalDynamic:
3917   case TLSModel::GeneralDynamic:
3918     Addr = getDynamicTLSAddr(N, DAG);
3919     break;
3920   }
3921 
3922   // In order to maximise the opportunity for common subexpression elimination,
3923   // emit a separate ADD node for the global address offset instead of folding
3924   // it in the global address node. Later peephole optimisations may choose to
3925   // fold it back in when profitable.
3926   if (Offset != 0)
3927     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3928                        DAG.getConstant(Offset, DL, XLenVT));
3929   return Addr;
3930 }
3931 
3932 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3933   SDValue CondV = Op.getOperand(0);
3934   SDValue TrueV = Op.getOperand(1);
3935   SDValue FalseV = Op.getOperand(2);
3936   SDLoc DL(Op);
3937   MVT VT = Op.getSimpleValueType();
3938   MVT XLenVT = Subtarget.getXLenVT();
3939 
3940   // Lower vector SELECTs to VSELECTs by splatting the condition.
3941   if (VT.isVector()) {
3942     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3943     SDValue CondSplat = VT.isScalableVector()
3944                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3945                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3946     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3947   }
3948 
3949   // If the result type is XLenVT and CondV is the output of a SETCC node
3950   // which also operated on XLenVT inputs, then merge the SETCC node into the
3951   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3952   // compare+branch instructions. i.e.:
3953   // (select (setcc lhs, rhs, cc), truev, falsev)
3954   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3955   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3956       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3957     SDValue LHS = CondV.getOperand(0);
3958     SDValue RHS = CondV.getOperand(1);
3959     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3960     ISD::CondCode CCVal = CC->get();
3961 
3962     // Special case for a select of 2 constants that have a diffence of 1.
3963     // Normally this is done by DAGCombine, but if the select is introduced by
3964     // type legalization or op legalization, we miss it. Restricting to SETLT
3965     // case for now because that is what signed saturating add/sub need.
3966     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3967     // but we would probably want to swap the true/false values if the condition
3968     // is SETGE/SETLE to avoid an XORI.
3969     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3970         CCVal == ISD::SETLT) {
3971       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3972       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3973       if (TrueVal - 1 == FalseVal)
3974         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3975       if (TrueVal + 1 == FalseVal)
3976         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3977     }
3978 
3979     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3980 
3981     SDValue TargetCC = DAG.getCondCode(CCVal);
3982     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3983     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3984   }
3985 
3986   // Otherwise:
3987   // (select condv, truev, falsev)
3988   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3989   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3990   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3991 
3992   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3993 
3994   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3995 }
3996 
3997 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3998   SDValue CondV = Op.getOperand(1);
3999   SDLoc DL(Op);
4000   MVT XLenVT = Subtarget.getXLenVT();
4001 
4002   if (CondV.getOpcode() == ISD::SETCC &&
4003       CondV.getOperand(0).getValueType() == XLenVT) {
4004     SDValue LHS = CondV.getOperand(0);
4005     SDValue RHS = CondV.getOperand(1);
4006     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4007 
4008     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4009 
4010     SDValue TargetCC = DAG.getCondCode(CCVal);
4011     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4012                        LHS, RHS, TargetCC, Op.getOperand(2));
4013   }
4014 
4015   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4016                      CondV, DAG.getConstant(0, DL, XLenVT),
4017                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4018 }
4019 
4020 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4021   MachineFunction &MF = DAG.getMachineFunction();
4022   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4023 
4024   SDLoc DL(Op);
4025   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4026                                  getPointerTy(MF.getDataLayout()));
4027 
4028   // vastart just stores the address of the VarArgsFrameIndex slot into the
4029   // memory location argument.
4030   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4031   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4032                       MachinePointerInfo(SV));
4033 }
4034 
4035 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4036                                             SelectionDAG &DAG) const {
4037   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4038   MachineFunction &MF = DAG.getMachineFunction();
4039   MachineFrameInfo &MFI = MF.getFrameInfo();
4040   MFI.setFrameAddressIsTaken(true);
4041   Register FrameReg = RI.getFrameRegister(MF);
4042   int XLenInBytes = Subtarget.getXLen() / 8;
4043 
4044   EVT VT = Op.getValueType();
4045   SDLoc DL(Op);
4046   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4047   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4048   while (Depth--) {
4049     int Offset = -(XLenInBytes * 2);
4050     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4051                               DAG.getIntPtrConstant(Offset, DL));
4052     FrameAddr =
4053         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4054   }
4055   return FrameAddr;
4056 }
4057 
4058 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4059                                              SelectionDAG &DAG) const {
4060   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4061   MachineFunction &MF = DAG.getMachineFunction();
4062   MachineFrameInfo &MFI = MF.getFrameInfo();
4063   MFI.setReturnAddressIsTaken(true);
4064   MVT XLenVT = Subtarget.getXLenVT();
4065   int XLenInBytes = Subtarget.getXLen() / 8;
4066 
4067   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4068     return SDValue();
4069 
4070   EVT VT = Op.getValueType();
4071   SDLoc DL(Op);
4072   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4073   if (Depth) {
4074     int Off = -XLenInBytes;
4075     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4076     SDValue Offset = DAG.getConstant(Off, DL, VT);
4077     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4078                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4079                        MachinePointerInfo());
4080   }
4081 
4082   // Return the value of the return address register, marking it an implicit
4083   // live-in.
4084   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4085   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4086 }
4087 
4088 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4089                                                  SelectionDAG &DAG) const {
4090   SDLoc DL(Op);
4091   SDValue Lo = Op.getOperand(0);
4092   SDValue Hi = Op.getOperand(1);
4093   SDValue Shamt = Op.getOperand(2);
4094   EVT VT = Lo.getValueType();
4095 
4096   // if Shamt-XLEN < 0: // Shamt < XLEN
4097   //   Lo = Lo << Shamt
4098   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4099   // else:
4100   //   Lo = 0
4101   //   Hi = Lo << (Shamt-XLEN)
4102 
4103   SDValue Zero = DAG.getConstant(0, DL, VT);
4104   SDValue One = DAG.getConstant(1, DL, VT);
4105   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4106   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4107   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4108   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4109 
4110   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4111   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4112   SDValue ShiftRightLo =
4113       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4114   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4115   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4116   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4117 
4118   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4119 
4120   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4121   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4122 
4123   SDValue Parts[2] = {Lo, Hi};
4124   return DAG.getMergeValues(Parts, DL);
4125 }
4126 
4127 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4128                                                   bool IsSRA) const {
4129   SDLoc DL(Op);
4130   SDValue Lo = Op.getOperand(0);
4131   SDValue Hi = Op.getOperand(1);
4132   SDValue Shamt = Op.getOperand(2);
4133   EVT VT = Lo.getValueType();
4134 
4135   // SRA expansion:
4136   //   if Shamt-XLEN < 0: // Shamt < XLEN
4137   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4138   //     Hi = Hi >>s Shamt
4139   //   else:
4140   //     Lo = Hi >>s (Shamt-XLEN);
4141   //     Hi = Hi >>s (XLEN-1)
4142   //
4143   // SRL expansion:
4144   //   if Shamt-XLEN < 0: // Shamt < XLEN
4145   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4146   //     Hi = Hi >>u Shamt
4147   //   else:
4148   //     Lo = Hi >>u (Shamt-XLEN);
4149   //     Hi = 0;
4150 
4151   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4152 
4153   SDValue Zero = DAG.getConstant(0, DL, VT);
4154   SDValue One = DAG.getConstant(1, DL, VT);
4155   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4156   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4157   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4158   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4159 
4160   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4161   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4162   SDValue ShiftLeftHi =
4163       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4164   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4165   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4166   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4167   SDValue HiFalse =
4168       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4169 
4170   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4171 
4172   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4173   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4174 
4175   SDValue Parts[2] = {Lo, Hi};
4176   return DAG.getMergeValues(Parts, DL);
4177 }
4178 
4179 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4180 // legal equivalently-sized i8 type, so we can use that as a go-between.
4181 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4182                                                   SelectionDAG &DAG) const {
4183   SDLoc DL(Op);
4184   MVT VT = Op.getSimpleValueType();
4185   SDValue SplatVal = Op.getOperand(0);
4186   // All-zeros or all-ones splats are handled specially.
4187   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4188     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4189     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4190   }
4191   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4192     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4193     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4194   }
4195   MVT XLenVT = Subtarget.getXLenVT();
4196   assert(SplatVal.getValueType() == XLenVT &&
4197          "Unexpected type for i1 splat value");
4198   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4199   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4200                          DAG.getConstant(1, DL, XLenVT));
4201   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4202   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4203   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4204 }
4205 
4206 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4207 // illegal (currently only vXi64 RV32).
4208 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4209 // them to VMV_V_X_VL.
4210 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4211                                                      SelectionDAG &DAG) const {
4212   SDLoc DL(Op);
4213   MVT VecVT = Op.getSimpleValueType();
4214   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4215          "Unexpected SPLAT_VECTOR_PARTS lowering");
4216 
4217   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4218   SDValue Lo = Op.getOperand(0);
4219   SDValue Hi = Op.getOperand(1);
4220 
4221   if (VecVT.isFixedLengthVector()) {
4222     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4223     SDLoc DL(Op);
4224     SDValue Mask, VL;
4225     std::tie(Mask, VL) =
4226         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4227 
4228     SDValue Res =
4229         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4230     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4231   }
4232 
4233   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4234     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4235     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4236     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4237     // node in order to try and match RVV vector/scalar instructions.
4238     if ((LoC >> 31) == HiC)
4239       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4240                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4241   }
4242 
4243   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4244   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4245       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4246       Hi.getConstantOperandVal(1) == 31)
4247     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4248                        DAG.getRegister(RISCV::X0, MVT::i32));
4249 
4250   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4251   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4252                      DAG.getUNDEF(VecVT), Lo, Hi,
4253                      DAG.getRegister(RISCV::X0, MVT::i32));
4254 }
4255 
4256 // Custom-lower extensions from mask vectors by using a vselect either with 1
4257 // for zero/any-extension or -1 for sign-extension:
4258 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4259 // Note that any-extension is lowered identically to zero-extension.
4260 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4261                                                 int64_t ExtTrueVal) const {
4262   SDLoc DL(Op);
4263   MVT VecVT = Op.getSimpleValueType();
4264   SDValue Src = Op.getOperand(0);
4265   // Only custom-lower extensions from mask types
4266   assert(Src.getValueType().isVector() &&
4267          Src.getValueType().getVectorElementType() == MVT::i1);
4268 
4269   MVT XLenVT = Subtarget.getXLenVT();
4270   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4271   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4272 
4273   if (VecVT.isScalableVector()) {
4274     // Be careful not to introduce illegal scalar types at this stage, and be
4275     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4276     // illegal and must be expanded. Since we know that the constants are
4277     // sign-extended 32-bit values, we use VMV_V_X_VL directly.
4278     bool IsRV32E64 =
4279         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4280 
4281     if (!IsRV32E64) {
4282       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4283       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4284     } else {
4285       SplatZero =
4286           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4287                       SplatZero, DAG.getRegister(RISCV::X0, XLenVT));
4288       SplatTrueVal =
4289           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4290                       SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT));
4291     }
4292 
4293     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4294   }
4295 
4296   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4297   MVT I1ContainerVT =
4298       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4299 
4300   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4301 
4302   SDValue Mask, VL;
4303   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4304 
4305   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4306                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4307   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4308                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4309   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4310                                SplatTrueVal, SplatZero, VL);
4311 
4312   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4313 }
4314 
4315 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4316     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4317   MVT ExtVT = Op.getSimpleValueType();
4318   // Only custom-lower extensions from fixed-length vector types.
4319   if (!ExtVT.isFixedLengthVector())
4320     return Op;
4321   MVT VT = Op.getOperand(0).getSimpleValueType();
4322   // Grab the canonical container type for the extended type. Infer the smaller
4323   // type from that to ensure the same number of vector elements, as we know
4324   // the LMUL will be sufficient to hold the smaller type.
4325   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4326   // Get the extended container type manually to ensure the same number of
4327   // vector elements between source and dest.
4328   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4329                                      ContainerExtVT.getVectorElementCount());
4330 
4331   SDValue Op1 =
4332       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4333 
4334   SDLoc DL(Op);
4335   SDValue Mask, VL;
4336   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4337 
4338   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4339 
4340   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4341 }
4342 
4343 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4344 // setcc operation:
4345 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4346 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4347                                                   SelectionDAG &DAG) const {
4348   SDLoc DL(Op);
4349   EVT MaskVT = Op.getValueType();
4350   // Only expect to custom-lower truncations to mask types
4351   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4352          "Unexpected type for vector mask lowering");
4353   SDValue Src = Op.getOperand(0);
4354   MVT VecVT = Src.getSimpleValueType();
4355 
4356   // If this is a fixed vector, we need to convert it to a scalable vector.
4357   MVT ContainerVT = VecVT;
4358   if (VecVT.isFixedLengthVector()) {
4359     ContainerVT = getContainerForFixedLengthVector(VecVT);
4360     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4361   }
4362 
4363   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4364   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4365 
4366   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4367                          DAG.getUNDEF(ContainerVT), SplatOne);
4368   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4369                           DAG.getUNDEF(ContainerVT), SplatZero);
4370 
4371   if (VecVT.isScalableVector()) {
4372     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4373     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4374   }
4375 
4376   SDValue Mask, VL;
4377   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4378 
4379   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4380   SDValue Trunc =
4381       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4382   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4383                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4384   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4385 }
4386 
4387 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4388 // first position of a vector, and that vector is slid up to the insert index.
4389 // By limiting the active vector length to index+1 and merging with the
4390 // original vector (with an undisturbed tail policy for elements >= VL), we
4391 // achieve the desired result of leaving all elements untouched except the one
4392 // at VL-1, which is replaced with the desired value.
4393 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4394                                                     SelectionDAG &DAG) const {
4395   SDLoc DL(Op);
4396   MVT VecVT = Op.getSimpleValueType();
4397   SDValue Vec = Op.getOperand(0);
4398   SDValue Val = Op.getOperand(1);
4399   SDValue Idx = Op.getOperand(2);
4400 
4401   if (VecVT.getVectorElementType() == MVT::i1) {
4402     // FIXME: For now we just promote to an i8 vector and insert into that,
4403     // but this is probably not optimal.
4404     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4405     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4406     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4407     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4408   }
4409 
4410   MVT ContainerVT = VecVT;
4411   // If the operand is a fixed-length vector, convert to a scalable one.
4412   if (VecVT.isFixedLengthVector()) {
4413     ContainerVT = getContainerForFixedLengthVector(VecVT);
4414     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4415   }
4416 
4417   MVT XLenVT = Subtarget.getXLenVT();
4418 
4419   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4420   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4421   // Even i64-element vectors on RV32 can be lowered without scalar
4422   // legalization if the most-significant 32 bits of the value are not affected
4423   // by the sign-extension of the lower 32 bits.
4424   // TODO: We could also catch sign extensions of a 32-bit value.
4425   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4426     const auto *CVal = cast<ConstantSDNode>(Val);
4427     if (isInt<32>(CVal->getSExtValue())) {
4428       IsLegalInsert = true;
4429       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4430     }
4431   }
4432 
4433   SDValue Mask, VL;
4434   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4435 
4436   SDValue ValInVec;
4437 
4438   if (IsLegalInsert) {
4439     unsigned Opc =
4440         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4441     if (isNullConstant(Idx)) {
4442       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4443       if (!VecVT.isFixedLengthVector())
4444         return Vec;
4445       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4446     }
4447     ValInVec =
4448         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4449   } else {
4450     // On RV32, i64-element vectors must be specially handled to place the
4451     // value at element 0, by using two vslide1up instructions in sequence on
4452     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4453     // this.
4454     SDValue One = DAG.getConstant(1, DL, XLenVT);
4455     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4456     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4457     MVT I32ContainerVT =
4458         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4459     SDValue I32Mask =
4460         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4461     // Limit the active VL to two.
4462     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4463     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4464     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4465     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4466                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4467     // First slide in the hi value, then the lo in underneath it.
4468     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4469                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4470                            I32Mask, InsertI64VL);
4471     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4472                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4473                            I32Mask, InsertI64VL);
4474     // Bitcast back to the right container type.
4475     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4476   }
4477 
4478   // Now that the value is in a vector, slide it into position.
4479   SDValue InsertVL =
4480       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4481   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4482                                 ValInVec, Idx, Mask, InsertVL);
4483   if (!VecVT.isFixedLengthVector())
4484     return Slideup;
4485   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4486 }
4487 
4488 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4489 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4490 // types this is done using VMV_X_S to allow us to glean information about the
4491 // sign bits of the result.
4492 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4493                                                      SelectionDAG &DAG) const {
4494   SDLoc DL(Op);
4495   SDValue Idx = Op.getOperand(1);
4496   SDValue Vec = Op.getOperand(0);
4497   EVT EltVT = Op.getValueType();
4498   MVT VecVT = Vec.getSimpleValueType();
4499   MVT XLenVT = Subtarget.getXLenVT();
4500 
4501   if (VecVT.getVectorElementType() == MVT::i1) {
4502     if (VecVT.isFixedLengthVector()) {
4503       unsigned NumElts = VecVT.getVectorNumElements();
4504       if (NumElts >= 8) {
4505         MVT WideEltVT;
4506         unsigned WidenVecLen;
4507         SDValue ExtractElementIdx;
4508         SDValue ExtractBitIdx;
4509         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4510         MVT LargestEltVT = MVT::getIntegerVT(
4511             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4512         if (NumElts <= LargestEltVT.getSizeInBits()) {
4513           assert(isPowerOf2_32(NumElts) &&
4514                  "the number of elements should be power of 2");
4515           WideEltVT = MVT::getIntegerVT(NumElts);
4516           WidenVecLen = 1;
4517           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4518           ExtractBitIdx = Idx;
4519         } else {
4520           WideEltVT = LargestEltVT;
4521           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4522           // extract element index = index / element width
4523           ExtractElementIdx = DAG.getNode(
4524               ISD::SRL, DL, XLenVT, Idx,
4525               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4526           // mask bit index = index % element width
4527           ExtractBitIdx = DAG.getNode(
4528               ISD::AND, DL, XLenVT, Idx,
4529               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4530         }
4531         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4532         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4533         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4534                                          Vec, ExtractElementIdx);
4535         // Extract the bit from GPR.
4536         SDValue ShiftRight =
4537             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4538         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4539                            DAG.getConstant(1, DL, XLenVT));
4540       }
4541     }
4542     // Otherwise, promote to an i8 vector and extract from that.
4543     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4544     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4545     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4546   }
4547 
4548   // If this is a fixed vector, we need to convert it to a scalable vector.
4549   MVT ContainerVT = VecVT;
4550   if (VecVT.isFixedLengthVector()) {
4551     ContainerVT = getContainerForFixedLengthVector(VecVT);
4552     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4553   }
4554 
4555   // If the index is 0, the vector is already in the right position.
4556   if (!isNullConstant(Idx)) {
4557     // Use a VL of 1 to avoid processing more elements than we need.
4558     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4559     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4560     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4561     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4562                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4563   }
4564 
4565   if (!EltVT.isInteger()) {
4566     // Floating-point extracts are handled in TableGen.
4567     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4568                        DAG.getConstant(0, DL, XLenVT));
4569   }
4570 
4571   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4572   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4573 }
4574 
4575 // Some RVV intrinsics may claim that they want an integer operand to be
4576 // promoted or expanded.
4577 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4578                                            const RISCVSubtarget &Subtarget) {
4579   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4580           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4581          "Unexpected opcode");
4582 
4583   if (!Subtarget.hasVInstructions())
4584     return SDValue();
4585 
4586   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4587   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4588   SDLoc DL(Op);
4589 
4590   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4591       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4592   if (!II || !II->hasScalarOperand())
4593     return SDValue();
4594 
4595   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4596   assert(SplatOp < Op.getNumOperands());
4597 
4598   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4599   SDValue &ScalarOp = Operands[SplatOp];
4600   MVT OpVT = ScalarOp.getSimpleValueType();
4601   MVT XLenVT = Subtarget.getXLenVT();
4602 
4603   // If this isn't a scalar, or its type is XLenVT we're done.
4604   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4605     return SDValue();
4606 
4607   // Simplest case is that the operand needs to be promoted to XLenVT.
4608   if (OpVT.bitsLT(XLenVT)) {
4609     // If the operand is a constant, sign extend to increase our chances
4610     // of being able to use a .vi instruction. ANY_EXTEND would become a
4611     // a zero extend and the simm5 check in isel would fail.
4612     // FIXME: Should we ignore the upper bits in isel instead?
4613     unsigned ExtOpc =
4614         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4615     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4616     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4617   }
4618 
4619   // Use the previous operand to get the vXi64 VT. The result might be a mask
4620   // VT for compares. Using the previous operand assumes that the previous
4621   // operand will never have a smaller element size than a scalar operand and
4622   // that a widening operation never uses SEW=64.
4623   // NOTE: If this fails the below assert, we can probably just find the
4624   // element count from any operand or result and use it to construct the VT.
4625   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4626   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4627 
4628   // The more complex case is when the scalar is larger than XLenVT.
4629   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4630          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4631 
4632   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4633   // on the instruction to sign-extend since SEW>XLEN.
4634   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4635     if (isInt<32>(CVal->getSExtValue())) {
4636       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4637       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4638     }
4639   }
4640 
4641   switch (IntNo) {
4642   case Intrinsic::riscv_vslide1up:
4643   case Intrinsic::riscv_vslide1down:
4644   case Intrinsic::riscv_vslide1up_mask:
4645   case Intrinsic::riscv_vslide1down_mask: {
4646     // We need to special case these when the scalar is larger than XLen.
4647     unsigned NumOps = Op.getNumOperands();
4648     bool IsMasked = NumOps == 7;
4649 
4650     // Convert the vector source to the equivalent nxvXi32 vector.
4651     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4652     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4653 
4654     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4655                                    DAG.getConstant(0, DL, XLenVT));
4656     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4657                                    DAG.getConstant(1, DL, XLenVT));
4658 
4659     // Double the VL since we halved SEW.
4660     SDValue VL = getVLOperand(Op);
4661     SDValue I32VL =
4662         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4663 
4664     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4665     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4666 
4667     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4668     // instructions.
4669     SDValue Passthru;
4670     if (IsMasked)
4671       Passthru = DAG.getUNDEF(I32VT);
4672     else
4673       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4674 
4675     if (IntNo == Intrinsic::riscv_vslide1up ||
4676         IntNo == Intrinsic::riscv_vslide1up_mask) {
4677       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4678                         ScalarHi, I32Mask, I32VL);
4679       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4680                         ScalarLo, I32Mask, I32VL);
4681     } else {
4682       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4683                         ScalarLo, I32Mask, I32VL);
4684       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4685                         ScalarHi, I32Mask, I32VL);
4686     }
4687 
4688     // Convert back to nxvXi64.
4689     Vec = DAG.getBitcast(VT, Vec);
4690 
4691     if (!IsMasked)
4692       return Vec;
4693     // Apply mask after the operation.
4694     SDValue Mask = Operands[NumOps - 3];
4695     SDValue MaskedOff = Operands[1];
4696     // Assume Policy operand is the last operand.
4697     uint64_t Policy =
4698         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4699     // We don't need to select maskedoff if it's undef.
4700     if (MaskedOff.isUndef())
4701       return Vec;
4702     // TAMU
4703     if (Policy == RISCVII::TAIL_AGNOSTIC)
4704       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4705                          VL);
4706     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4707     // It's fine because vmerge does not care mask policy.
4708     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4709   }
4710   }
4711 
4712   // We need to convert the scalar to a splat vector.
4713   // FIXME: Can we implicitly truncate the scalar if it is known to
4714   // be sign extended?
4715   SDValue VL = getVLOperand(Op);
4716   assert(VL.getValueType() == XLenVT);
4717   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4718   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4719 }
4720 
4721 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4722                                                      SelectionDAG &DAG) const {
4723   unsigned IntNo = Op.getConstantOperandVal(0);
4724   SDLoc DL(Op);
4725   MVT XLenVT = Subtarget.getXLenVT();
4726 
4727   switch (IntNo) {
4728   default:
4729     break; // Don't custom lower most intrinsics.
4730   case Intrinsic::thread_pointer: {
4731     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4732     return DAG.getRegister(RISCV::X4, PtrVT);
4733   }
4734   case Intrinsic::riscv_orc_b:
4735   case Intrinsic::riscv_brev8: {
4736     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4737     unsigned Opc =
4738         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4739     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4740                        DAG.getConstant(7, DL, XLenVT));
4741   }
4742   case Intrinsic::riscv_grev:
4743   case Intrinsic::riscv_gorc: {
4744     unsigned Opc =
4745         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4746     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4747   }
4748   case Intrinsic::riscv_zip:
4749   case Intrinsic::riscv_unzip: {
4750     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4751     // For i32 the immdiate is 15. For i64 the immediate is 31.
4752     unsigned Opc =
4753         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4754     unsigned BitWidth = Op.getValueSizeInBits();
4755     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4756     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4757                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4758   }
4759   case Intrinsic::riscv_shfl:
4760   case Intrinsic::riscv_unshfl: {
4761     unsigned Opc =
4762         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4763     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4764   }
4765   case Intrinsic::riscv_bcompress:
4766   case Intrinsic::riscv_bdecompress: {
4767     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4768                                                        : RISCVISD::BDECOMPRESS;
4769     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4770   }
4771   case Intrinsic::riscv_bfp:
4772     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4773                        Op.getOperand(2));
4774   case Intrinsic::riscv_fsl:
4775     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4776                        Op.getOperand(2), Op.getOperand(3));
4777   case Intrinsic::riscv_fsr:
4778     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4779                        Op.getOperand(2), Op.getOperand(3));
4780   case Intrinsic::riscv_vmv_x_s:
4781     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4782     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4783                        Op.getOperand(1));
4784   case Intrinsic::riscv_vmv_v_x:
4785     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4786                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4787                             Subtarget);
4788   case Intrinsic::riscv_vfmv_v_f:
4789     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4790                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4791   case Intrinsic::riscv_vmv_s_x: {
4792     SDValue Scalar = Op.getOperand(2);
4793 
4794     if (Scalar.getValueType().bitsLE(XLenVT)) {
4795       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4796       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4797                          Op.getOperand(1), Scalar, Op.getOperand(3));
4798     }
4799 
4800     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4801 
4802     // This is an i64 value that lives in two scalar registers. We have to
4803     // insert this in a convoluted way. First we build vXi64 splat containing
4804     // the/ two values that we assemble using some bit math. Next we'll use
4805     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4806     // to merge element 0 from our splat into the source vector.
4807     // FIXME: This is probably not the best way to do this, but it is
4808     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4809     // point.
4810     //   sw lo, (a0)
4811     //   sw hi, 4(a0)
4812     //   vlse vX, (a0)
4813     //
4814     //   vid.v      vVid
4815     //   vmseq.vx   mMask, vVid, 0
4816     //   vmerge.vvm vDest, vSrc, vVal, mMask
4817     MVT VT = Op.getSimpleValueType();
4818     SDValue Vec = Op.getOperand(1);
4819     SDValue VL = getVLOperand(Op);
4820 
4821     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4822     if (Op.getOperand(1).isUndef())
4823       return SplattedVal;
4824     SDValue SplattedIdx =
4825         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4826                     DAG.getConstant(0, DL, MVT::i32), VL);
4827 
4828     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4829     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4830     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4831     SDValue SelectCond =
4832         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4833                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4834     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4835                        Vec, VL);
4836   }
4837   }
4838 
4839   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4840 }
4841 
4842 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4843                                                     SelectionDAG &DAG) const {
4844   unsigned IntNo = Op.getConstantOperandVal(1);
4845   switch (IntNo) {
4846   default:
4847     break;
4848   case Intrinsic::riscv_masked_strided_load: {
4849     SDLoc DL(Op);
4850     MVT XLenVT = Subtarget.getXLenVT();
4851 
4852     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4853     // the selection of the masked intrinsics doesn't do this for us.
4854     SDValue Mask = Op.getOperand(5);
4855     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4856 
4857     MVT VT = Op->getSimpleValueType(0);
4858     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4859 
4860     SDValue PassThru = Op.getOperand(2);
4861     if (!IsUnmasked) {
4862       MVT MaskVT =
4863           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4864       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4865       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4866     }
4867 
4868     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4869 
4870     SDValue IntID = DAG.getTargetConstant(
4871         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4872         XLenVT);
4873 
4874     auto *Load = cast<MemIntrinsicSDNode>(Op);
4875     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4876     if (IsUnmasked)
4877       Ops.push_back(DAG.getUNDEF(ContainerVT));
4878     else
4879       Ops.push_back(PassThru);
4880     Ops.push_back(Op.getOperand(3)); // Ptr
4881     Ops.push_back(Op.getOperand(4)); // Stride
4882     if (!IsUnmasked)
4883       Ops.push_back(Mask);
4884     Ops.push_back(VL);
4885     if (!IsUnmasked) {
4886       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4887       Ops.push_back(Policy);
4888     }
4889 
4890     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4891     SDValue Result =
4892         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4893                                 Load->getMemoryVT(), Load->getMemOperand());
4894     SDValue Chain = Result.getValue(1);
4895     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4896     return DAG.getMergeValues({Result, Chain}, DL);
4897   }
4898   case Intrinsic::riscv_seg2_load:
4899   case Intrinsic::riscv_seg3_load:
4900   case Intrinsic::riscv_seg4_load:
4901   case Intrinsic::riscv_seg5_load:
4902   case Intrinsic::riscv_seg6_load:
4903   case Intrinsic::riscv_seg7_load:
4904   case Intrinsic::riscv_seg8_load: {
4905     SDLoc DL(Op);
4906     static const Intrinsic::ID VlsegInts[7] = {
4907         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4908         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4909         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4910         Intrinsic::riscv_vlseg8};
4911     unsigned NF = Op->getNumValues() - 1;
4912     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4913     MVT XLenVT = Subtarget.getXLenVT();
4914     MVT VT = Op->getSimpleValueType(0);
4915     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4916 
4917     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4918     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4919     auto *Load = cast<MemIntrinsicSDNode>(Op);
4920     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4921     ContainerVTs.push_back(MVT::Other);
4922     SDVTList VTs = DAG.getVTList(ContainerVTs);
4923     SDValue Result =
4924         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4925                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4926                                 Load->getMemoryVT(), Load->getMemOperand());
4927     SmallVector<SDValue, 9> Results;
4928     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4929       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4930                                                   DAG, Subtarget));
4931     Results.push_back(Result.getValue(NF));
4932     return DAG.getMergeValues(Results, DL);
4933   }
4934   }
4935 
4936   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4937 }
4938 
4939 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4940                                                  SelectionDAG &DAG) const {
4941   unsigned IntNo = Op.getConstantOperandVal(1);
4942   switch (IntNo) {
4943   default:
4944     break;
4945   case Intrinsic::riscv_masked_strided_store: {
4946     SDLoc DL(Op);
4947     MVT XLenVT = Subtarget.getXLenVT();
4948 
4949     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4950     // the selection of the masked intrinsics doesn't do this for us.
4951     SDValue Mask = Op.getOperand(5);
4952     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4953 
4954     SDValue Val = Op.getOperand(2);
4955     MVT VT = Val.getSimpleValueType();
4956     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4957 
4958     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4959     if (!IsUnmasked) {
4960       MVT MaskVT =
4961           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4962       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4963     }
4964 
4965     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4966 
4967     SDValue IntID = DAG.getTargetConstant(
4968         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4969         XLenVT);
4970 
4971     auto *Store = cast<MemIntrinsicSDNode>(Op);
4972     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4973     Ops.push_back(Val);
4974     Ops.push_back(Op.getOperand(3)); // Ptr
4975     Ops.push_back(Op.getOperand(4)); // Stride
4976     if (!IsUnmasked)
4977       Ops.push_back(Mask);
4978     Ops.push_back(VL);
4979 
4980     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4981                                    Ops, Store->getMemoryVT(),
4982                                    Store->getMemOperand());
4983   }
4984   }
4985 
4986   return SDValue();
4987 }
4988 
4989 static MVT getLMUL1VT(MVT VT) {
4990   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4991          "Unexpected vector MVT");
4992   return MVT::getScalableVectorVT(
4993       VT.getVectorElementType(),
4994       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4995 }
4996 
4997 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4998   switch (ISDOpcode) {
4999   default:
5000     llvm_unreachable("Unhandled reduction");
5001   case ISD::VECREDUCE_ADD:
5002     return RISCVISD::VECREDUCE_ADD_VL;
5003   case ISD::VECREDUCE_UMAX:
5004     return RISCVISD::VECREDUCE_UMAX_VL;
5005   case ISD::VECREDUCE_SMAX:
5006     return RISCVISD::VECREDUCE_SMAX_VL;
5007   case ISD::VECREDUCE_UMIN:
5008     return RISCVISD::VECREDUCE_UMIN_VL;
5009   case ISD::VECREDUCE_SMIN:
5010     return RISCVISD::VECREDUCE_SMIN_VL;
5011   case ISD::VECREDUCE_AND:
5012     return RISCVISD::VECREDUCE_AND_VL;
5013   case ISD::VECREDUCE_OR:
5014     return RISCVISD::VECREDUCE_OR_VL;
5015   case ISD::VECREDUCE_XOR:
5016     return RISCVISD::VECREDUCE_XOR_VL;
5017   }
5018 }
5019 
5020 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5021                                                          SelectionDAG &DAG,
5022                                                          bool IsVP) const {
5023   SDLoc DL(Op);
5024   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5025   MVT VecVT = Vec.getSimpleValueType();
5026   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5027           Op.getOpcode() == ISD::VECREDUCE_OR ||
5028           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5029           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5030           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5031           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5032          "Unexpected reduction lowering");
5033 
5034   MVT XLenVT = Subtarget.getXLenVT();
5035   assert(Op.getValueType() == XLenVT &&
5036          "Expected reduction output to be legalized to XLenVT");
5037 
5038   MVT ContainerVT = VecVT;
5039   if (VecVT.isFixedLengthVector()) {
5040     ContainerVT = getContainerForFixedLengthVector(VecVT);
5041     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5042   }
5043 
5044   SDValue Mask, VL;
5045   if (IsVP) {
5046     Mask = Op.getOperand(2);
5047     VL = Op.getOperand(3);
5048   } else {
5049     std::tie(Mask, VL) =
5050         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5051   }
5052 
5053   unsigned BaseOpc;
5054   ISD::CondCode CC;
5055   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5056 
5057   switch (Op.getOpcode()) {
5058   default:
5059     llvm_unreachable("Unhandled reduction");
5060   case ISD::VECREDUCE_AND:
5061   case ISD::VP_REDUCE_AND: {
5062     // vcpop ~x == 0
5063     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5064     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5065     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5066     CC = ISD::SETEQ;
5067     BaseOpc = ISD::AND;
5068     break;
5069   }
5070   case ISD::VECREDUCE_OR:
5071   case ISD::VP_REDUCE_OR:
5072     // vcpop x != 0
5073     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5074     CC = ISD::SETNE;
5075     BaseOpc = ISD::OR;
5076     break;
5077   case ISD::VECREDUCE_XOR:
5078   case ISD::VP_REDUCE_XOR: {
5079     // ((vcpop x) & 1) != 0
5080     SDValue One = DAG.getConstant(1, DL, XLenVT);
5081     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5082     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5083     CC = ISD::SETNE;
5084     BaseOpc = ISD::XOR;
5085     break;
5086   }
5087   }
5088 
5089   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5090 
5091   if (!IsVP)
5092     return SetCC;
5093 
5094   // Now include the start value in the operation.
5095   // Note that we must return the start value when no elements are operated
5096   // upon. The vcpop instructions we've emitted in each case above will return
5097   // 0 for an inactive vector, and so we've already received the neutral value:
5098   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5099   // can simply include the start value.
5100   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5101 }
5102 
5103 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5104                                             SelectionDAG &DAG) const {
5105   SDLoc DL(Op);
5106   SDValue Vec = Op.getOperand(0);
5107   EVT VecEVT = Vec.getValueType();
5108 
5109   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5110 
5111   // Due to ordering in legalize types we may have a vector type that needs to
5112   // be split. Do that manually so we can get down to a legal type.
5113   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5114          TargetLowering::TypeSplitVector) {
5115     SDValue Lo, Hi;
5116     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5117     VecEVT = Lo.getValueType();
5118     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5119   }
5120 
5121   // TODO: The type may need to be widened rather than split. Or widened before
5122   // it can be split.
5123   if (!isTypeLegal(VecEVT))
5124     return SDValue();
5125 
5126   MVT VecVT = VecEVT.getSimpleVT();
5127   MVT VecEltVT = VecVT.getVectorElementType();
5128   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5129 
5130   MVT ContainerVT = VecVT;
5131   if (VecVT.isFixedLengthVector()) {
5132     ContainerVT = getContainerForFixedLengthVector(VecVT);
5133     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5134   }
5135 
5136   MVT M1VT = getLMUL1VT(ContainerVT);
5137   MVT XLenVT = Subtarget.getXLenVT();
5138 
5139   SDValue Mask, VL;
5140   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5141 
5142   SDValue NeutralElem =
5143       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5144   SDValue IdentitySplat =
5145       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5146                        M1VT, DL, DAG, Subtarget);
5147   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5148                                   IdentitySplat, Mask, VL);
5149   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5150                              DAG.getConstant(0, DL, XLenVT));
5151   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5152 }
5153 
5154 // Given a reduction op, this function returns the matching reduction opcode,
5155 // the vector SDValue and the scalar SDValue required to lower this to a
5156 // RISCVISD node.
5157 static std::tuple<unsigned, SDValue, SDValue>
5158 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5159   SDLoc DL(Op);
5160   auto Flags = Op->getFlags();
5161   unsigned Opcode = Op.getOpcode();
5162   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5163   switch (Opcode) {
5164   default:
5165     llvm_unreachable("Unhandled reduction");
5166   case ISD::VECREDUCE_FADD: {
5167     // Use positive zero if we can. It is cheaper to materialize.
5168     SDValue Zero =
5169         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5170     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5171   }
5172   case ISD::VECREDUCE_SEQ_FADD:
5173     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5174                            Op.getOperand(0));
5175   case ISD::VECREDUCE_FMIN:
5176     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5177                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5178   case ISD::VECREDUCE_FMAX:
5179     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5180                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5181   }
5182 }
5183 
5184 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5185                                               SelectionDAG &DAG) const {
5186   SDLoc DL(Op);
5187   MVT VecEltVT = Op.getSimpleValueType();
5188 
5189   unsigned RVVOpcode;
5190   SDValue VectorVal, ScalarVal;
5191   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5192       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5193   MVT VecVT = VectorVal.getSimpleValueType();
5194 
5195   MVT ContainerVT = VecVT;
5196   if (VecVT.isFixedLengthVector()) {
5197     ContainerVT = getContainerForFixedLengthVector(VecVT);
5198     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5199   }
5200 
5201   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5202   MVT XLenVT = Subtarget.getXLenVT();
5203 
5204   SDValue Mask, VL;
5205   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5206 
5207   SDValue ScalarSplat =
5208       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5209                        M1VT, DL, DAG, Subtarget);
5210   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5211                                   VectorVal, ScalarSplat, Mask, VL);
5212   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5213                      DAG.getConstant(0, DL, XLenVT));
5214 }
5215 
5216 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5217   switch (ISDOpcode) {
5218   default:
5219     llvm_unreachable("Unhandled reduction");
5220   case ISD::VP_REDUCE_ADD:
5221     return RISCVISD::VECREDUCE_ADD_VL;
5222   case ISD::VP_REDUCE_UMAX:
5223     return RISCVISD::VECREDUCE_UMAX_VL;
5224   case ISD::VP_REDUCE_SMAX:
5225     return RISCVISD::VECREDUCE_SMAX_VL;
5226   case ISD::VP_REDUCE_UMIN:
5227     return RISCVISD::VECREDUCE_UMIN_VL;
5228   case ISD::VP_REDUCE_SMIN:
5229     return RISCVISD::VECREDUCE_SMIN_VL;
5230   case ISD::VP_REDUCE_AND:
5231     return RISCVISD::VECREDUCE_AND_VL;
5232   case ISD::VP_REDUCE_OR:
5233     return RISCVISD::VECREDUCE_OR_VL;
5234   case ISD::VP_REDUCE_XOR:
5235     return RISCVISD::VECREDUCE_XOR_VL;
5236   case ISD::VP_REDUCE_FADD:
5237     return RISCVISD::VECREDUCE_FADD_VL;
5238   case ISD::VP_REDUCE_SEQ_FADD:
5239     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5240   case ISD::VP_REDUCE_FMAX:
5241     return RISCVISD::VECREDUCE_FMAX_VL;
5242   case ISD::VP_REDUCE_FMIN:
5243     return RISCVISD::VECREDUCE_FMIN_VL;
5244   }
5245 }
5246 
5247 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5248                                            SelectionDAG &DAG) const {
5249   SDLoc DL(Op);
5250   SDValue Vec = Op.getOperand(1);
5251   EVT VecEVT = Vec.getValueType();
5252 
5253   // TODO: The type may need to be widened rather than split. Or widened before
5254   // it can be split.
5255   if (!isTypeLegal(VecEVT))
5256     return SDValue();
5257 
5258   MVT VecVT = VecEVT.getSimpleVT();
5259   MVT VecEltVT = VecVT.getVectorElementType();
5260   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5261 
5262   MVT ContainerVT = VecVT;
5263   if (VecVT.isFixedLengthVector()) {
5264     ContainerVT = getContainerForFixedLengthVector(VecVT);
5265     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5266   }
5267 
5268   SDValue VL = Op.getOperand(3);
5269   SDValue Mask = Op.getOperand(2);
5270 
5271   MVT M1VT = getLMUL1VT(ContainerVT);
5272   MVT XLenVT = Subtarget.getXLenVT();
5273   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5274 
5275   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5276                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5277                                         DL, DAG, Subtarget);
5278   SDValue Reduction =
5279       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5280   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5281                              DAG.getConstant(0, DL, XLenVT));
5282   if (!VecVT.isInteger())
5283     return Elt0;
5284   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5285 }
5286 
5287 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5288                                                    SelectionDAG &DAG) const {
5289   SDValue Vec = Op.getOperand(0);
5290   SDValue SubVec = Op.getOperand(1);
5291   MVT VecVT = Vec.getSimpleValueType();
5292   MVT SubVecVT = SubVec.getSimpleValueType();
5293 
5294   SDLoc DL(Op);
5295   MVT XLenVT = Subtarget.getXLenVT();
5296   unsigned OrigIdx = Op.getConstantOperandVal(2);
5297   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5298 
5299   // We don't have the ability to slide mask vectors up indexed by their i1
5300   // elements; the smallest we can do is i8. Often we are able to bitcast to
5301   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5302   // into a scalable one, we might not necessarily have enough scalable
5303   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5304   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5305       (OrigIdx != 0 || !Vec.isUndef())) {
5306     if (VecVT.getVectorMinNumElements() >= 8 &&
5307         SubVecVT.getVectorMinNumElements() >= 8) {
5308       assert(OrigIdx % 8 == 0 && "Invalid index");
5309       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5310              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5311              "Unexpected mask vector lowering");
5312       OrigIdx /= 8;
5313       SubVecVT =
5314           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5315                            SubVecVT.isScalableVector());
5316       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5317                                VecVT.isScalableVector());
5318       Vec = DAG.getBitcast(VecVT, Vec);
5319       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5320     } else {
5321       // We can't slide this mask vector up indexed by its i1 elements.
5322       // This poses a problem when we wish to insert a scalable vector which
5323       // can't be re-expressed as a larger type. Just choose the slow path and
5324       // extend to a larger type, then truncate back down.
5325       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5326       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5327       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5328       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5329       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5330                         Op.getOperand(2));
5331       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5332       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5333     }
5334   }
5335 
5336   // If the subvector vector is a fixed-length type, we cannot use subregister
5337   // manipulation to simplify the codegen; we don't know which register of a
5338   // LMUL group contains the specific subvector as we only know the minimum
5339   // register size. Therefore we must slide the vector group up the full
5340   // amount.
5341   if (SubVecVT.isFixedLengthVector()) {
5342     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5343       return Op;
5344     MVT ContainerVT = VecVT;
5345     if (VecVT.isFixedLengthVector()) {
5346       ContainerVT = getContainerForFixedLengthVector(VecVT);
5347       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5348     }
5349     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5350                          DAG.getUNDEF(ContainerVT), SubVec,
5351                          DAG.getConstant(0, DL, XLenVT));
5352     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5353       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5354       return DAG.getBitcast(Op.getValueType(), SubVec);
5355     }
5356     SDValue Mask =
5357         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5358     // Set the vector length to only the number of elements we care about. Note
5359     // that for slideup this includes the offset.
5360     SDValue VL =
5361         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5362     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5363     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5364                                   SubVec, SlideupAmt, Mask, VL);
5365     if (VecVT.isFixedLengthVector())
5366       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5367     return DAG.getBitcast(Op.getValueType(), Slideup);
5368   }
5369 
5370   unsigned SubRegIdx, RemIdx;
5371   std::tie(SubRegIdx, RemIdx) =
5372       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5373           VecVT, SubVecVT, OrigIdx, TRI);
5374 
5375   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5376   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5377                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5378                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5379 
5380   // 1. If the Idx has been completely eliminated and this subvector's size is
5381   // a vector register or a multiple thereof, or the surrounding elements are
5382   // undef, then this is a subvector insert which naturally aligns to a vector
5383   // register. These can easily be handled using subregister manipulation.
5384   // 2. If the subvector is smaller than a vector register, then the insertion
5385   // must preserve the undisturbed elements of the register. We do this by
5386   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5387   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5388   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5389   // LMUL=1 type back into the larger vector (resolving to another subregister
5390   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5391   // to avoid allocating a large register group to hold our subvector.
5392   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5393     return Op;
5394 
5395   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5396   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5397   // (in our case undisturbed). This means we can set up a subvector insertion
5398   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5399   // size of the subvector.
5400   MVT InterSubVT = VecVT;
5401   SDValue AlignedExtract = Vec;
5402   unsigned AlignedIdx = OrigIdx - RemIdx;
5403   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5404     InterSubVT = getLMUL1VT(VecVT);
5405     // Extract a subvector equal to the nearest full vector register type. This
5406     // should resolve to a EXTRACT_SUBREG instruction.
5407     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5408                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5409   }
5410 
5411   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5412   // For scalable vectors this must be further multiplied by vscale.
5413   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5414 
5415   SDValue Mask, VL;
5416   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5417 
5418   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5419   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5420   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5421   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5422 
5423   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5424                        DAG.getUNDEF(InterSubVT), SubVec,
5425                        DAG.getConstant(0, DL, XLenVT));
5426 
5427   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5428                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5429 
5430   // If required, insert this subvector back into the correct vector register.
5431   // This should resolve to an INSERT_SUBREG instruction.
5432   if (VecVT.bitsGT(InterSubVT))
5433     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5434                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5435 
5436   // We might have bitcast from a mask type: cast back to the original type if
5437   // required.
5438   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5439 }
5440 
5441 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5442                                                     SelectionDAG &DAG) const {
5443   SDValue Vec = Op.getOperand(0);
5444   MVT SubVecVT = Op.getSimpleValueType();
5445   MVT VecVT = Vec.getSimpleValueType();
5446 
5447   SDLoc DL(Op);
5448   MVT XLenVT = Subtarget.getXLenVT();
5449   unsigned OrigIdx = Op.getConstantOperandVal(1);
5450   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5451 
5452   // We don't have the ability to slide mask vectors down indexed by their i1
5453   // elements; the smallest we can do is i8. Often we are able to bitcast to
5454   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5455   // from a scalable one, we might not necessarily have enough scalable
5456   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5457   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5458     if (VecVT.getVectorMinNumElements() >= 8 &&
5459         SubVecVT.getVectorMinNumElements() >= 8) {
5460       assert(OrigIdx % 8 == 0 && "Invalid index");
5461       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5462              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5463              "Unexpected mask vector lowering");
5464       OrigIdx /= 8;
5465       SubVecVT =
5466           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5467                            SubVecVT.isScalableVector());
5468       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5469                                VecVT.isScalableVector());
5470       Vec = DAG.getBitcast(VecVT, Vec);
5471     } else {
5472       // We can't slide this mask vector down, indexed by its i1 elements.
5473       // This poses a problem when we wish to extract a scalable vector which
5474       // can't be re-expressed as a larger type. Just choose the slow path and
5475       // extend to a larger type, then truncate back down.
5476       // TODO: We could probably improve this when extracting certain fixed
5477       // from fixed, where we can extract as i8 and shift the correct element
5478       // right to reach the desired subvector?
5479       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5480       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5481       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5482       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5483                         Op.getOperand(1));
5484       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5485       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5486     }
5487   }
5488 
5489   // If the subvector vector is a fixed-length type, we cannot use subregister
5490   // manipulation to simplify the codegen; we don't know which register of a
5491   // LMUL group contains the specific subvector as we only know the minimum
5492   // register size. Therefore we must slide the vector group down the full
5493   // amount.
5494   if (SubVecVT.isFixedLengthVector()) {
5495     // With an index of 0 this is a cast-like subvector, which can be performed
5496     // with subregister operations.
5497     if (OrigIdx == 0)
5498       return Op;
5499     MVT ContainerVT = VecVT;
5500     if (VecVT.isFixedLengthVector()) {
5501       ContainerVT = getContainerForFixedLengthVector(VecVT);
5502       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5503     }
5504     SDValue Mask =
5505         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5506     // Set the vector length to only the number of elements we care about. This
5507     // avoids sliding down elements we're going to discard straight away.
5508     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5509     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5510     SDValue Slidedown =
5511         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5512                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5513     // Now we can use a cast-like subvector extract to get the result.
5514     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5515                             DAG.getConstant(0, DL, XLenVT));
5516     return DAG.getBitcast(Op.getValueType(), Slidedown);
5517   }
5518 
5519   unsigned SubRegIdx, RemIdx;
5520   std::tie(SubRegIdx, RemIdx) =
5521       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5522           VecVT, SubVecVT, OrigIdx, TRI);
5523 
5524   // If the Idx has been completely eliminated then this is a subvector extract
5525   // which naturally aligns to a vector register. These can easily be handled
5526   // using subregister manipulation.
5527   if (RemIdx == 0)
5528     return Op;
5529 
5530   // Else we must shift our vector register directly to extract the subvector.
5531   // Do this using VSLIDEDOWN.
5532 
5533   // If the vector type is an LMUL-group type, extract a subvector equal to the
5534   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5535   // instruction.
5536   MVT InterSubVT = VecVT;
5537   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5538     InterSubVT = getLMUL1VT(VecVT);
5539     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5540                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5541   }
5542 
5543   // Slide this vector register down by the desired number of elements in order
5544   // to place the desired subvector starting at element 0.
5545   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5546   // For scalable vectors this must be further multiplied by vscale.
5547   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5548 
5549   SDValue Mask, VL;
5550   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5551   SDValue Slidedown =
5552       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5553                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5554 
5555   // Now the vector is in the right position, extract our final subvector. This
5556   // should resolve to a COPY.
5557   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5558                           DAG.getConstant(0, DL, XLenVT));
5559 
5560   // We might have bitcast from a mask type: cast back to the original type if
5561   // required.
5562   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5563 }
5564 
5565 // Lower step_vector to the vid instruction. Any non-identity step value must
5566 // be accounted for my manual expansion.
5567 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5568                                               SelectionDAG &DAG) const {
5569   SDLoc DL(Op);
5570   MVT VT = Op.getSimpleValueType();
5571   MVT XLenVT = Subtarget.getXLenVT();
5572   SDValue Mask, VL;
5573   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5574   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5575   uint64_t StepValImm = Op.getConstantOperandVal(0);
5576   if (StepValImm != 1) {
5577     if (isPowerOf2_64(StepValImm)) {
5578       SDValue StepVal =
5579           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5580                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5581       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5582     } else {
5583       SDValue StepVal = lowerScalarSplat(
5584           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5585           VL, VT, DL, DAG, Subtarget);
5586       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5587     }
5588   }
5589   return StepVec;
5590 }
5591 
5592 // Implement vector_reverse using vrgather.vv with indices determined by
5593 // subtracting the id of each element from (VLMAX-1). This will convert
5594 // the indices like so:
5595 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5596 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5597 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5598                                                  SelectionDAG &DAG) const {
5599   SDLoc DL(Op);
5600   MVT VecVT = Op.getSimpleValueType();
5601   unsigned EltSize = VecVT.getScalarSizeInBits();
5602   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5603 
5604   unsigned MaxVLMAX = 0;
5605   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5606   if (VectorBitsMax != 0)
5607     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5608 
5609   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5610   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5611 
5612   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5613   // to use vrgatherei16.vv.
5614   // TODO: It's also possible to use vrgatherei16.vv for other types to
5615   // decrease register width for the index calculation.
5616   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5617     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5618     // Reverse each half, then reassemble them in reverse order.
5619     // NOTE: It's also possible that after splitting that VLMAX no longer
5620     // requires vrgatherei16.vv.
5621     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5622       SDValue Lo, Hi;
5623       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5624       EVT LoVT, HiVT;
5625       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5626       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5627       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5628       // Reassemble the low and high pieces reversed.
5629       // FIXME: This is a CONCAT_VECTORS.
5630       SDValue Res =
5631           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5632                       DAG.getIntPtrConstant(0, DL));
5633       return DAG.getNode(
5634           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5635           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5636     }
5637 
5638     // Just promote the int type to i16 which will double the LMUL.
5639     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5640     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5641   }
5642 
5643   MVT XLenVT = Subtarget.getXLenVT();
5644   SDValue Mask, VL;
5645   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5646 
5647   // Calculate VLMAX-1 for the desired SEW.
5648   unsigned MinElts = VecVT.getVectorMinNumElements();
5649   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5650                               DAG.getConstant(MinElts, DL, XLenVT));
5651   SDValue VLMinus1 =
5652       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5653 
5654   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5655   bool IsRV32E64 =
5656       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5657   SDValue SplatVL;
5658   if (!IsRV32E64)
5659     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5660   else
5661     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5662                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5663 
5664   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5665   SDValue Indices =
5666       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5667 
5668   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5669 }
5670 
5671 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5672                                                 SelectionDAG &DAG) const {
5673   SDLoc DL(Op);
5674   SDValue V1 = Op.getOperand(0);
5675   SDValue V2 = Op.getOperand(1);
5676   MVT XLenVT = Subtarget.getXLenVT();
5677   MVT VecVT = Op.getSimpleValueType();
5678 
5679   unsigned MinElts = VecVT.getVectorMinNumElements();
5680   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5681                               DAG.getConstant(MinElts, DL, XLenVT));
5682 
5683   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5684   SDValue DownOffset, UpOffset;
5685   if (ImmValue >= 0) {
5686     // The operand is a TargetConstant, we need to rebuild it as a regular
5687     // constant.
5688     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5689     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5690   } else {
5691     // The operand is a TargetConstant, we need to rebuild it as a regular
5692     // constant rather than negating the original operand.
5693     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5694     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5695   }
5696 
5697   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5698   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5699 
5700   SDValue SlideDown =
5701       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5702                   DownOffset, TrueMask, UpOffset);
5703   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5704                      TrueMask,
5705                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5706 }
5707 
5708 SDValue
5709 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5710                                                      SelectionDAG &DAG) const {
5711   SDLoc DL(Op);
5712   auto *Load = cast<LoadSDNode>(Op);
5713 
5714   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5715                                         Load->getMemoryVT(),
5716                                         *Load->getMemOperand()) &&
5717          "Expecting a correctly-aligned load");
5718 
5719   MVT VT = Op.getSimpleValueType();
5720   MVT XLenVT = Subtarget.getXLenVT();
5721   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5722 
5723   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5724 
5725   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5726   SDValue IntID = DAG.getTargetConstant(
5727       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5728   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5729   if (!IsMaskOp)
5730     Ops.push_back(DAG.getUNDEF(ContainerVT));
5731   Ops.push_back(Load->getBasePtr());
5732   Ops.push_back(VL);
5733   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5734   SDValue NewLoad =
5735       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5736                               Load->getMemoryVT(), Load->getMemOperand());
5737 
5738   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5739   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5740 }
5741 
5742 SDValue
5743 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5744                                                       SelectionDAG &DAG) const {
5745   SDLoc DL(Op);
5746   auto *Store = cast<StoreSDNode>(Op);
5747 
5748   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5749                                         Store->getMemoryVT(),
5750                                         *Store->getMemOperand()) &&
5751          "Expecting a correctly-aligned store");
5752 
5753   SDValue StoreVal = Store->getValue();
5754   MVT VT = StoreVal.getSimpleValueType();
5755   MVT XLenVT = Subtarget.getXLenVT();
5756 
5757   // If the size less than a byte, we need to pad with zeros to make a byte.
5758   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5759     VT = MVT::v8i1;
5760     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5761                            DAG.getConstant(0, DL, VT), StoreVal,
5762                            DAG.getIntPtrConstant(0, DL));
5763   }
5764 
5765   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5766 
5767   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5768 
5769   SDValue NewValue =
5770       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5771 
5772   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5773   SDValue IntID = DAG.getTargetConstant(
5774       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5775   return DAG.getMemIntrinsicNode(
5776       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5777       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5778       Store->getMemoryVT(), Store->getMemOperand());
5779 }
5780 
5781 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5782                                              SelectionDAG &DAG) const {
5783   SDLoc DL(Op);
5784   MVT VT = Op.getSimpleValueType();
5785 
5786   const auto *MemSD = cast<MemSDNode>(Op);
5787   EVT MemVT = MemSD->getMemoryVT();
5788   MachineMemOperand *MMO = MemSD->getMemOperand();
5789   SDValue Chain = MemSD->getChain();
5790   SDValue BasePtr = MemSD->getBasePtr();
5791 
5792   SDValue Mask, PassThru, VL;
5793   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5794     Mask = VPLoad->getMask();
5795     PassThru = DAG.getUNDEF(VT);
5796     VL = VPLoad->getVectorLength();
5797   } else {
5798     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5799     Mask = MLoad->getMask();
5800     PassThru = MLoad->getPassThru();
5801   }
5802 
5803   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5804 
5805   MVT XLenVT = Subtarget.getXLenVT();
5806 
5807   MVT ContainerVT = VT;
5808   if (VT.isFixedLengthVector()) {
5809     ContainerVT = getContainerForFixedLengthVector(VT);
5810     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5811     if (!IsUnmasked) {
5812       MVT MaskVT =
5813           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5814       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5815     }
5816   }
5817 
5818   if (!VL)
5819     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5820 
5821   unsigned IntID =
5822       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5823   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5824   if (IsUnmasked)
5825     Ops.push_back(DAG.getUNDEF(ContainerVT));
5826   else
5827     Ops.push_back(PassThru);
5828   Ops.push_back(BasePtr);
5829   if (!IsUnmasked)
5830     Ops.push_back(Mask);
5831   Ops.push_back(VL);
5832   if (!IsUnmasked)
5833     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5834 
5835   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5836 
5837   SDValue Result =
5838       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5839   Chain = Result.getValue(1);
5840 
5841   if (VT.isFixedLengthVector())
5842     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5843 
5844   return DAG.getMergeValues({Result, Chain}, DL);
5845 }
5846 
5847 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5848                                               SelectionDAG &DAG) const {
5849   SDLoc DL(Op);
5850 
5851   const auto *MemSD = cast<MemSDNode>(Op);
5852   EVT MemVT = MemSD->getMemoryVT();
5853   MachineMemOperand *MMO = MemSD->getMemOperand();
5854   SDValue Chain = MemSD->getChain();
5855   SDValue BasePtr = MemSD->getBasePtr();
5856   SDValue Val, Mask, VL;
5857 
5858   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5859     Val = VPStore->getValue();
5860     Mask = VPStore->getMask();
5861     VL = VPStore->getVectorLength();
5862   } else {
5863     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5864     Val = MStore->getValue();
5865     Mask = MStore->getMask();
5866   }
5867 
5868   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5869 
5870   MVT VT = Val.getSimpleValueType();
5871   MVT XLenVT = Subtarget.getXLenVT();
5872 
5873   MVT ContainerVT = VT;
5874   if (VT.isFixedLengthVector()) {
5875     ContainerVT = getContainerForFixedLengthVector(VT);
5876 
5877     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5878     if (!IsUnmasked) {
5879       MVT MaskVT =
5880           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5881       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5882     }
5883   }
5884 
5885   if (!VL)
5886     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5887 
5888   unsigned IntID =
5889       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5890   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5891   Ops.push_back(Val);
5892   Ops.push_back(BasePtr);
5893   if (!IsUnmasked)
5894     Ops.push_back(Mask);
5895   Ops.push_back(VL);
5896 
5897   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5898                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5899 }
5900 
5901 SDValue
5902 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5903                                                       SelectionDAG &DAG) const {
5904   MVT InVT = Op.getOperand(0).getSimpleValueType();
5905   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5906 
5907   MVT VT = Op.getSimpleValueType();
5908 
5909   SDValue Op1 =
5910       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5911   SDValue Op2 =
5912       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5913 
5914   SDLoc DL(Op);
5915   SDValue VL =
5916       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5917 
5918   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5919   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5920 
5921   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5922                             Op.getOperand(2), Mask, VL);
5923 
5924   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5925 }
5926 
5927 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5928     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5929   MVT VT = Op.getSimpleValueType();
5930 
5931   if (VT.getVectorElementType() == MVT::i1)
5932     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5933 
5934   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5935 }
5936 
5937 SDValue
5938 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5939                                                       SelectionDAG &DAG) const {
5940   unsigned Opc;
5941   switch (Op.getOpcode()) {
5942   default: llvm_unreachable("Unexpected opcode!");
5943   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5944   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5945   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5946   }
5947 
5948   return lowerToScalableOp(Op, DAG, Opc);
5949 }
5950 
5951 // Lower vector ABS to smax(X, sub(0, X)).
5952 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5953   SDLoc DL(Op);
5954   MVT VT = Op.getSimpleValueType();
5955   SDValue X = Op.getOperand(0);
5956 
5957   assert(VT.isFixedLengthVector() && "Unexpected type");
5958 
5959   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5960   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5961 
5962   SDValue Mask, VL;
5963   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5964 
5965   SDValue SplatZero = DAG.getNode(
5966       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5967       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5968   SDValue NegX =
5969       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5970   SDValue Max =
5971       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5972 
5973   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5974 }
5975 
5976 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5977     SDValue Op, SelectionDAG &DAG) const {
5978   SDLoc DL(Op);
5979   MVT VT = Op.getSimpleValueType();
5980   SDValue Mag = Op.getOperand(0);
5981   SDValue Sign = Op.getOperand(1);
5982   assert(Mag.getValueType() == Sign.getValueType() &&
5983          "Can only handle COPYSIGN with matching types.");
5984 
5985   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5986   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5987   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5988 
5989   SDValue Mask, VL;
5990   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5991 
5992   SDValue CopySign =
5993       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5994 
5995   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5996 }
5997 
5998 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5999     SDValue Op, SelectionDAG &DAG) const {
6000   MVT VT = Op.getSimpleValueType();
6001   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6002 
6003   MVT I1ContainerVT =
6004       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6005 
6006   SDValue CC =
6007       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6008   SDValue Op1 =
6009       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6010   SDValue Op2 =
6011       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6012 
6013   SDLoc DL(Op);
6014   SDValue Mask, VL;
6015   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6016 
6017   SDValue Select =
6018       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6019 
6020   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6021 }
6022 
6023 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6024                                                unsigned NewOpc,
6025                                                bool HasMask) const {
6026   MVT VT = Op.getSimpleValueType();
6027   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6028 
6029   // Create list of operands by converting existing ones to scalable types.
6030   SmallVector<SDValue, 6> Ops;
6031   for (const SDValue &V : Op->op_values()) {
6032     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6033 
6034     // Pass through non-vector operands.
6035     if (!V.getValueType().isVector()) {
6036       Ops.push_back(V);
6037       continue;
6038     }
6039 
6040     // "cast" fixed length vector to a scalable vector.
6041     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6042            "Only fixed length vectors are supported!");
6043     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6044   }
6045 
6046   SDLoc DL(Op);
6047   SDValue Mask, VL;
6048   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6049   if (HasMask)
6050     Ops.push_back(Mask);
6051   Ops.push_back(VL);
6052 
6053   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6054   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6055 }
6056 
6057 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6058 // * Operands of each node are assumed to be in the same order.
6059 // * The EVL operand is promoted from i32 to i64 on RV64.
6060 // * Fixed-length vectors are converted to their scalable-vector container
6061 //   types.
6062 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6063                                        unsigned RISCVISDOpc) const {
6064   SDLoc DL(Op);
6065   MVT VT = Op.getSimpleValueType();
6066   SmallVector<SDValue, 4> Ops;
6067 
6068   for (const auto &OpIdx : enumerate(Op->ops())) {
6069     SDValue V = OpIdx.value();
6070     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6071     // Pass through operands which aren't fixed-length vectors.
6072     if (!V.getValueType().isFixedLengthVector()) {
6073       Ops.push_back(V);
6074       continue;
6075     }
6076     // "cast" fixed length vector to a scalable vector.
6077     MVT OpVT = V.getSimpleValueType();
6078     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6079     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6080            "Only fixed length vectors are supported!");
6081     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6082   }
6083 
6084   if (!VT.isFixedLengthVector())
6085     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6086 
6087   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6088 
6089   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6090 
6091   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6092 }
6093 
6094 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6095                                             unsigned MaskOpc,
6096                                             unsigned VecOpc) const {
6097   MVT VT = Op.getSimpleValueType();
6098   if (VT.getVectorElementType() != MVT::i1)
6099     return lowerVPOp(Op, DAG, VecOpc);
6100 
6101   // It is safe to drop mask parameter as masked-off elements are undef.
6102   SDValue Op1 = Op->getOperand(0);
6103   SDValue Op2 = Op->getOperand(1);
6104   SDValue VL = Op->getOperand(3);
6105 
6106   MVT ContainerVT = VT;
6107   const bool IsFixed = VT.isFixedLengthVector();
6108   if (IsFixed) {
6109     ContainerVT = getContainerForFixedLengthVector(VT);
6110     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6111     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6112   }
6113 
6114   SDLoc DL(Op);
6115   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6116   if (!IsFixed)
6117     return Val;
6118   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6119 }
6120 
6121 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6122 // matched to a RVV indexed load. The RVV indexed load instructions only
6123 // support the "unsigned unscaled" addressing mode; indices are implicitly
6124 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6125 // signed or scaled indexing is extended to the XLEN value type and scaled
6126 // accordingly.
6127 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6128                                                SelectionDAG &DAG) const {
6129   SDLoc DL(Op);
6130   MVT VT = Op.getSimpleValueType();
6131 
6132   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6133   EVT MemVT = MemSD->getMemoryVT();
6134   MachineMemOperand *MMO = MemSD->getMemOperand();
6135   SDValue Chain = MemSD->getChain();
6136   SDValue BasePtr = MemSD->getBasePtr();
6137 
6138   ISD::LoadExtType LoadExtType;
6139   SDValue Index, Mask, PassThru, VL;
6140 
6141   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6142     Index = VPGN->getIndex();
6143     Mask = VPGN->getMask();
6144     PassThru = DAG.getUNDEF(VT);
6145     VL = VPGN->getVectorLength();
6146     // VP doesn't support extending loads.
6147     LoadExtType = ISD::NON_EXTLOAD;
6148   } else {
6149     // Else it must be a MGATHER.
6150     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6151     Index = MGN->getIndex();
6152     Mask = MGN->getMask();
6153     PassThru = MGN->getPassThru();
6154     LoadExtType = MGN->getExtensionType();
6155   }
6156 
6157   MVT IndexVT = Index.getSimpleValueType();
6158   MVT XLenVT = Subtarget.getXLenVT();
6159 
6160   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6161          "Unexpected VTs!");
6162   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6163   // Targets have to explicitly opt-in for extending vector loads.
6164   assert(LoadExtType == ISD::NON_EXTLOAD &&
6165          "Unexpected extending MGATHER/VP_GATHER");
6166   (void)LoadExtType;
6167 
6168   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6169   // the selection of the masked intrinsics doesn't do this for us.
6170   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6171 
6172   MVT ContainerVT = VT;
6173   if (VT.isFixedLengthVector()) {
6174     // We need to use the larger of the result and index type to determine the
6175     // scalable type to use so we don't increase LMUL for any operand/result.
6176     if (VT.bitsGE(IndexVT)) {
6177       ContainerVT = getContainerForFixedLengthVector(VT);
6178       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6179                                  ContainerVT.getVectorElementCount());
6180     } else {
6181       IndexVT = getContainerForFixedLengthVector(IndexVT);
6182       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6183                                      IndexVT.getVectorElementCount());
6184     }
6185 
6186     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6187 
6188     if (!IsUnmasked) {
6189       MVT MaskVT =
6190           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6191       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6192       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6193     }
6194   }
6195 
6196   if (!VL)
6197     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6198 
6199   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6200     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6201     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6202                                    VL);
6203     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6204                         TrueMask, VL);
6205   }
6206 
6207   unsigned IntID =
6208       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6209   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6210   if (IsUnmasked)
6211     Ops.push_back(DAG.getUNDEF(ContainerVT));
6212   else
6213     Ops.push_back(PassThru);
6214   Ops.push_back(BasePtr);
6215   Ops.push_back(Index);
6216   if (!IsUnmasked)
6217     Ops.push_back(Mask);
6218   Ops.push_back(VL);
6219   if (!IsUnmasked)
6220     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6221 
6222   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6223   SDValue Result =
6224       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6225   Chain = Result.getValue(1);
6226 
6227   if (VT.isFixedLengthVector())
6228     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6229 
6230   return DAG.getMergeValues({Result, Chain}, DL);
6231 }
6232 
6233 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6234 // matched to a RVV indexed store. The RVV indexed store instructions only
6235 // support the "unsigned unscaled" addressing mode; indices are implicitly
6236 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6237 // signed or scaled indexing is extended to the XLEN value type and scaled
6238 // accordingly.
6239 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6240                                                 SelectionDAG &DAG) const {
6241   SDLoc DL(Op);
6242   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6243   EVT MemVT = MemSD->getMemoryVT();
6244   MachineMemOperand *MMO = MemSD->getMemOperand();
6245   SDValue Chain = MemSD->getChain();
6246   SDValue BasePtr = MemSD->getBasePtr();
6247 
6248   bool IsTruncatingStore = false;
6249   SDValue Index, Mask, Val, VL;
6250 
6251   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6252     Index = VPSN->getIndex();
6253     Mask = VPSN->getMask();
6254     Val = VPSN->getValue();
6255     VL = VPSN->getVectorLength();
6256     // VP doesn't support truncating stores.
6257     IsTruncatingStore = false;
6258   } else {
6259     // Else it must be a MSCATTER.
6260     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6261     Index = MSN->getIndex();
6262     Mask = MSN->getMask();
6263     Val = MSN->getValue();
6264     IsTruncatingStore = MSN->isTruncatingStore();
6265   }
6266 
6267   MVT VT = Val.getSimpleValueType();
6268   MVT IndexVT = Index.getSimpleValueType();
6269   MVT XLenVT = Subtarget.getXLenVT();
6270 
6271   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6272          "Unexpected VTs!");
6273   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6274   // Targets have to explicitly opt-in for extending vector loads and
6275   // truncating vector stores.
6276   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6277   (void)IsTruncatingStore;
6278 
6279   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6280   // the selection of the masked intrinsics doesn't do this for us.
6281   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6282 
6283   MVT ContainerVT = VT;
6284   if (VT.isFixedLengthVector()) {
6285     // We need to use the larger of the value and index type to determine the
6286     // scalable type to use so we don't increase LMUL for any operand/result.
6287     if (VT.bitsGE(IndexVT)) {
6288       ContainerVT = getContainerForFixedLengthVector(VT);
6289       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6290                                  ContainerVT.getVectorElementCount());
6291     } else {
6292       IndexVT = getContainerForFixedLengthVector(IndexVT);
6293       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6294                                      IndexVT.getVectorElementCount());
6295     }
6296 
6297     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6298     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6299 
6300     if (!IsUnmasked) {
6301       MVT MaskVT =
6302           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6303       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6304     }
6305   }
6306 
6307   if (!VL)
6308     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6309 
6310   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6311     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6312     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6313                                    VL);
6314     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6315                         TrueMask, VL);
6316   }
6317 
6318   unsigned IntID =
6319       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6320   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6321   Ops.push_back(Val);
6322   Ops.push_back(BasePtr);
6323   Ops.push_back(Index);
6324   if (!IsUnmasked)
6325     Ops.push_back(Mask);
6326   Ops.push_back(VL);
6327 
6328   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6329                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6330 }
6331 
6332 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6333                                                SelectionDAG &DAG) const {
6334   const MVT XLenVT = Subtarget.getXLenVT();
6335   SDLoc DL(Op);
6336   SDValue Chain = Op->getOperand(0);
6337   SDValue SysRegNo = DAG.getTargetConstant(
6338       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6339   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6340   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6341 
6342   // Encoding used for rounding mode in RISCV differs from that used in
6343   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6344   // table, which consists of a sequence of 4-bit fields, each representing
6345   // corresponding FLT_ROUNDS mode.
6346   static const int Table =
6347       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6348       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6349       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6350       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6351       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6352 
6353   SDValue Shift =
6354       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6355   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6356                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6357   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6358                                DAG.getConstant(7, DL, XLenVT));
6359 
6360   return DAG.getMergeValues({Masked, Chain}, DL);
6361 }
6362 
6363 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6364                                                SelectionDAG &DAG) const {
6365   const MVT XLenVT = Subtarget.getXLenVT();
6366   SDLoc DL(Op);
6367   SDValue Chain = Op->getOperand(0);
6368   SDValue RMValue = Op->getOperand(1);
6369   SDValue SysRegNo = DAG.getTargetConstant(
6370       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6371 
6372   // Encoding used for rounding mode in RISCV differs from that used in
6373   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6374   // a table, which consists of a sequence of 4-bit fields, each representing
6375   // corresponding RISCV mode.
6376   static const unsigned Table =
6377       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6378       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6379       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6380       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6381       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6382 
6383   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6384                               DAG.getConstant(2, DL, XLenVT));
6385   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6386                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6387   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6388                         DAG.getConstant(0x7, DL, XLenVT));
6389   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6390                      RMValue);
6391 }
6392 
6393 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6394   switch (IntNo) {
6395   default:
6396     llvm_unreachable("Unexpected Intrinsic");
6397   case Intrinsic::riscv_grev:
6398     return RISCVISD::GREVW;
6399   case Intrinsic::riscv_gorc:
6400     return RISCVISD::GORCW;
6401   case Intrinsic::riscv_bcompress:
6402     return RISCVISD::BCOMPRESSW;
6403   case Intrinsic::riscv_bdecompress:
6404     return RISCVISD::BDECOMPRESSW;
6405   case Intrinsic::riscv_bfp:
6406     return RISCVISD::BFPW;
6407   case Intrinsic::riscv_fsl:
6408     return RISCVISD::FSLW;
6409   case Intrinsic::riscv_fsr:
6410     return RISCVISD::FSRW;
6411   }
6412 }
6413 
6414 // Converts the given intrinsic to a i64 operation with any extension.
6415 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6416                                          unsigned IntNo) {
6417   SDLoc DL(N);
6418   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6419   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6420   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6421   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6422   // ReplaceNodeResults requires we maintain the same type for the return value.
6423   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6424 }
6425 
6426 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6427 // form of the given Opcode.
6428 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6429   switch (Opcode) {
6430   default:
6431     llvm_unreachable("Unexpected opcode");
6432   case ISD::SHL:
6433     return RISCVISD::SLLW;
6434   case ISD::SRA:
6435     return RISCVISD::SRAW;
6436   case ISD::SRL:
6437     return RISCVISD::SRLW;
6438   case ISD::SDIV:
6439     return RISCVISD::DIVW;
6440   case ISD::UDIV:
6441     return RISCVISD::DIVUW;
6442   case ISD::UREM:
6443     return RISCVISD::REMUW;
6444   case ISD::ROTL:
6445     return RISCVISD::ROLW;
6446   case ISD::ROTR:
6447     return RISCVISD::RORW;
6448   case RISCVISD::GREV:
6449     return RISCVISD::GREVW;
6450   case RISCVISD::GORC:
6451     return RISCVISD::GORCW;
6452   }
6453 }
6454 
6455 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6456 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6457 // otherwise be promoted to i64, making it difficult to select the
6458 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6459 // type i8/i16/i32 is lost.
6460 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6461                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6462   SDLoc DL(N);
6463   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6464   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6465   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6466   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6467   // ReplaceNodeResults requires we maintain the same type for the return value.
6468   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6469 }
6470 
6471 // Converts the given 32-bit operation to a i64 operation with signed extension
6472 // semantic to reduce the signed extension instructions.
6473 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6474   SDLoc DL(N);
6475   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6476   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6477   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6478   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6479                                DAG.getValueType(MVT::i32));
6480   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6481 }
6482 
6483 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6484                                              SmallVectorImpl<SDValue> &Results,
6485                                              SelectionDAG &DAG) const {
6486   SDLoc DL(N);
6487   switch (N->getOpcode()) {
6488   default:
6489     llvm_unreachable("Don't know how to custom type legalize this operation!");
6490   case ISD::STRICT_FP_TO_SINT:
6491   case ISD::STRICT_FP_TO_UINT:
6492   case ISD::FP_TO_SINT:
6493   case ISD::FP_TO_UINT: {
6494     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6495            "Unexpected custom legalisation");
6496     bool IsStrict = N->isStrictFPOpcode();
6497     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6498                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6499     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6500     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6501         TargetLowering::TypeSoftenFloat) {
6502       if (!isTypeLegal(Op0.getValueType()))
6503         return;
6504       if (IsStrict) {
6505         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6506                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6507         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6508         SDValue Res = DAG.getNode(
6509             Opc, DL, VTs, N->getOperand(0), Op0,
6510             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6511         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6512         Results.push_back(Res.getValue(1));
6513         return;
6514       }
6515       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6516       SDValue Res =
6517           DAG.getNode(Opc, DL, MVT::i64, Op0,
6518                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6519       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6520       return;
6521     }
6522     // If the FP type needs to be softened, emit a library call using the 'si'
6523     // version. If we left it to default legalization we'd end up with 'di'. If
6524     // the FP type doesn't need to be softened just let generic type
6525     // legalization promote the result type.
6526     RTLIB::Libcall LC;
6527     if (IsSigned)
6528       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6529     else
6530       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6531     MakeLibCallOptions CallOptions;
6532     EVT OpVT = Op0.getValueType();
6533     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6534     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6535     SDValue Result;
6536     std::tie(Result, Chain) =
6537         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6538     Results.push_back(Result);
6539     if (IsStrict)
6540       Results.push_back(Chain);
6541     break;
6542   }
6543   case ISD::READCYCLECOUNTER: {
6544     assert(!Subtarget.is64Bit() &&
6545            "READCYCLECOUNTER only has custom type legalization on riscv32");
6546 
6547     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6548     SDValue RCW =
6549         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6550 
6551     Results.push_back(
6552         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6553     Results.push_back(RCW.getValue(2));
6554     break;
6555   }
6556   case ISD::MUL: {
6557     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6558     unsigned XLen = Subtarget.getXLen();
6559     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6560     if (Size > XLen) {
6561       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6562       SDValue LHS = N->getOperand(0);
6563       SDValue RHS = N->getOperand(1);
6564       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6565 
6566       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6567       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6568       // We need exactly one side to be unsigned.
6569       if (LHSIsU == RHSIsU)
6570         return;
6571 
6572       auto MakeMULPair = [&](SDValue S, SDValue U) {
6573         MVT XLenVT = Subtarget.getXLenVT();
6574         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6575         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6576         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6577         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6578         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6579       };
6580 
6581       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6582       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6583 
6584       // The other operand should be signed, but still prefer MULH when
6585       // possible.
6586       if (RHSIsU && LHSIsS && !RHSIsS)
6587         Results.push_back(MakeMULPair(LHS, RHS));
6588       else if (LHSIsU && RHSIsS && !LHSIsS)
6589         Results.push_back(MakeMULPair(RHS, LHS));
6590 
6591       return;
6592     }
6593     LLVM_FALLTHROUGH;
6594   }
6595   case ISD::ADD:
6596   case ISD::SUB:
6597     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6598            "Unexpected custom legalisation");
6599     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6600     break;
6601   case ISD::SHL:
6602   case ISD::SRA:
6603   case ISD::SRL:
6604     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6605            "Unexpected custom legalisation");
6606     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6607       Results.push_back(customLegalizeToWOp(N, DAG));
6608       break;
6609     }
6610 
6611     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6612     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6613     // shift amount.
6614     if (N->getOpcode() == ISD::SHL) {
6615       SDLoc DL(N);
6616       SDValue NewOp0 =
6617           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6618       SDValue NewOp1 =
6619           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6620       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6621       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6622                                    DAG.getValueType(MVT::i32));
6623       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6624     }
6625 
6626     break;
6627   case ISD::ROTL:
6628   case ISD::ROTR:
6629     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6630            "Unexpected custom legalisation");
6631     Results.push_back(customLegalizeToWOp(N, DAG));
6632     break;
6633   case ISD::CTTZ:
6634   case ISD::CTTZ_ZERO_UNDEF:
6635   case ISD::CTLZ:
6636   case ISD::CTLZ_ZERO_UNDEF: {
6637     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6638            "Unexpected custom legalisation");
6639 
6640     SDValue NewOp0 =
6641         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6642     bool IsCTZ =
6643         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6644     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6645     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6646     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6647     return;
6648   }
6649   case ISD::SDIV:
6650   case ISD::UDIV:
6651   case ISD::UREM: {
6652     MVT VT = N->getSimpleValueType(0);
6653     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6654            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6655            "Unexpected custom legalisation");
6656     // Don't promote division/remainder by constant since we should expand those
6657     // to multiply by magic constant.
6658     // FIXME: What if the expansion is disabled for minsize.
6659     if (N->getOperand(1).getOpcode() == ISD::Constant)
6660       return;
6661 
6662     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6663     // the upper 32 bits. For other types we need to sign or zero extend
6664     // based on the opcode.
6665     unsigned ExtOpc = ISD::ANY_EXTEND;
6666     if (VT != MVT::i32)
6667       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6668                                            : ISD::ZERO_EXTEND;
6669 
6670     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6671     break;
6672   }
6673   case ISD::UADDO:
6674   case ISD::USUBO: {
6675     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6676            "Unexpected custom legalisation");
6677     bool IsAdd = N->getOpcode() == ISD::UADDO;
6678     // Create an ADDW or SUBW.
6679     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6680     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6681     SDValue Res =
6682         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6683     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6684                       DAG.getValueType(MVT::i32));
6685 
6686     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6687     // Since the inputs are sign extended from i32, this is equivalent to
6688     // comparing the lower 32 bits.
6689     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6690     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6691                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6692 
6693     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6694     Results.push_back(Overflow);
6695     return;
6696   }
6697   case ISD::UADDSAT:
6698   case ISD::USUBSAT: {
6699     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6700            "Unexpected custom legalisation");
6701     if (Subtarget.hasStdExtZbb()) {
6702       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6703       // sign extend allows overflow of the lower 32 bits to be detected on
6704       // the promoted size.
6705       SDValue LHS =
6706           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6707       SDValue RHS =
6708           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6709       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6710       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6711       return;
6712     }
6713 
6714     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6715     // promotion for UADDO/USUBO.
6716     Results.push_back(expandAddSubSat(N, DAG));
6717     return;
6718   }
6719   case ISD::ABS: {
6720     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6721            "Unexpected custom legalisation");
6722           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6723 
6724     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6725 
6726     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6727 
6728     // Freeze the source so we can increase it's use count.
6729     Src = DAG.getFreeze(Src);
6730 
6731     // Copy sign bit to all bits using the sraiw pattern.
6732     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6733                                    DAG.getValueType(MVT::i32));
6734     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6735                            DAG.getConstant(31, DL, MVT::i64));
6736 
6737     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6738     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6739 
6740     // NOTE: The result is only required to be anyextended, but sext is
6741     // consistent with type legalization of sub.
6742     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6743                          DAG.getValueType(MVT::i32));
6744     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6745     return;
6746   }
6747   case ISD::BITCAST: {
6748     EVT VT = N->getValueType(0);
6749     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6750     SDValue Op0 = N->getOperand(0);
6751     EVT Op0VT = Op0.getValueType();
6752     MVT XLenVT = Subtarget.getXLenVT();
6753     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6754       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6755       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6756     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6757                Subtarget.hasStdExtF()) {
6758       SDValue FPConv =
6759           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6760       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6761     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6762                isTypeLegal(Op0VT)) {
6763       // Custom-legalize bitcasts from fixed-length vector types to illegal
6764       // scalar types in order to improve codegen. Bitcast the vector to a
6765       // one-element vector type whose element type is the same as the result
6766       // type, and extract the first element.
6767       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6768       if (isTypeLegal(BVT)) {
6769         SDValue BVec = DAG.getBitcast(BVT, Op0);
6770         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6771                                       DAG.getConstant(0, DL, XLenVT)));
6772       }
6773     }
6774     break;
6775   }
6776   case RISCVISD::GREV:
6777   case RISCVISD::GORC: {
6778     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6779            "Unexpected custom legalisation");
6780     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6781     // This is similar to customLegalizeToWOp, except that we pass the second
6782     // operand (a TargetConstant) straight through: it is already of type
6783     // XLenVT.
6784     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6785     SDValue NewOp0 =
6786         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6787     SDValue NewOp1 =
6788         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6789     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6790     // ReplaceNodeResults requires we maintain the same type for the return
6791     // value.
6792     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6793     break;
6794   }
6795   case RISCVISD::SHFL: {
6796     // There is no SHFLIW instruction, but we can just promote the operation.
6797     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6798            "Unexpected custom legalisation");
6799     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6800     SDValue NewOp0 =
6801         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6802     SDValue NewOp1 =
6803         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6804     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6805     // ReplaceNodeResults requires we maintain the same type for the return
6806     // value.
6807     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6808     break;
6809   }
6810   case ISD::BSWAP:
6811   case ISD::BITREVERSE: {
6812     MVT VT = N->getSimpleValueType(0);
6813     MVT XLenVT = Subtarget.getXLenVT();
6814     assert((VT == MVT::i8 || VT == MVT::i16 ||
6815             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6816            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6817     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6818     unsigned Imm = VT.getSizeInBits() - 1;
6819     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6820     if (N->getOpcode() == ISD::BSWAP)
6821       Imm &= ~0x7U;
6822     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6823     SDValue GREVI =
6824         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6825     // ReplaceNodeResults requires we maintain the same type for the return
6826     // value.
6827     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6828     break;
6829   }
6830   case ISD::FSHL:
6831   case ISD::FSHR: {
6832     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6833            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6834     SDValue NewOp0 =
6835         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6836     SDValue NewOp1 =
6837         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6838     SDValue NewShAmt =
6839         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6840     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6841     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6842     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6843                            DAG.getConstant(0x1f, DL, MVT::i64));
6844     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6845     // instruction use different orders. fshl will return its first operand for
6846     // shift of zero, fshr will return its second operand. fsl and fsr both
6847     // return rs1 so the ISD nodes need to have different operand orders.
6848     // Shift amount is in rs2.
6849     unsigned Opc = RISCVISD::FSLW;
6850     if (N->getOpcode() == ISD::FSHR) {
6851       std::swap(NewOp0, NewOp1);
6852       Opc = RISCVISD::FSRW;
6853     }
6854     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6855     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6856     break;
6857   }
6858   case ISD::EXTRACT_VECTOR_ELT: {
6859     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6860     // type is illegal (currently only vXi64 RV32).
6861     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6862     // transferred to the destination register. We issue two of these from the
6863     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6864     // first element.
6865     SDValue Vec = N->getOperand(0);
6866     SDValue Idx = N->getOperand(1);
6867 
6868     // The vector type hasn't been legalized yet so we can't issue target
6869     // specific nodes if it needs legalization.
6870     // FIXME: We would manually legalize if it's important.
6871     if (!isTypeLegal(Vec.getValueType()))
6872       return;
6873 
6874     MVT VecVT = Vec.getSimpleValueType();
6875 
6876     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6877            VecVT.getVectorElementType() == MVT::i64 &&
6878            "Unexpected EXTRACT_VECTOR_ELT legalization");
6879 
6880     // If this is a fixed vector, we need to convert it to a scalable vector.
6881     MVT ContainerVT = VecVT;
6882     if (VecVT.isFixedLengthVector()) {
6883       ContainerVT = getContainerForFixedLengthVector(VecVT);
6884       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6885     }
6886 
6887     MVT XLenVT = Subtarget.getXLenVT();
6888 
6889     // Use a VL of 1 to avoid processing more elements than we need.
6890     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6891     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6892     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6893 
6894     // Unless the index is known to be 0, we must slide the vector down to get
6895     // the desired element into index 0.
6896     if (!isNullConstant(Idx)) {
6897       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6898                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6899     }
6900 
6901     // Extract the lower XLEN bits of the correct vector element.
6902     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6903 
6904     // To extract the upper XLEN bits of the vector element, shift the first
6905     // element right by 32 bits and re-extract the lower XLEN bits.
6906     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6907                                      DAG.getUNDEF(ContainerVT),
6908                                      DAG.getConstant(32, DL, XLenVT), VL);
6909     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6910                                  ThirtyTwoV, Mask, VL);
6911 
6912     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6913 
6914     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6915     break;
6916   }
6917   case ISD::INTRINSIC_WO_CHAIN: {
6918     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6919     switch (IntNo) {
6920     default:
6921       llvm_unreachable(
6922           "Don't know how to custom type legalize this intrinsic!");
6923     case Intrinsic::riscv_grev:
6924     case Intrinsic::riscv_gorc:
6925     case Intrinsic::riscv_bcompress:
6926     case Intrinsic::riscv_bdecompress:
6927     case Intrinsic::riscv_bfp: {
6928       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6929              "Unexpected custom legalisation");
6930       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6931       break;
6932     }
6933     case Intrinsic::riscv_fsl:
6934     case Intrinsic::riscv_fsr: {
6935       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6936              "Unexpected custom legalisation");
6937       SDValue NewOp1 =
6938           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6939       SDValue NewOp2 =
6940           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6941       SDValue NewOp3 =
6942           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6943       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6944       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6945       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6946       break;
6947     }
6948     case Intrinsic::riscv_orc_b: {
6949       // Lower to the GORCI encoding for orc.b with the operand extended.
6950       SDValue NewOp =
6951           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6952       // If Zbp is enabled, use GORCIW which will sign extend the result.
6953       unsigned Opc =
6954           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6955       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6956                                 DAG.getConstant(7, DL, MVT::i64));
6957       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6958       return;
6959     }
6960     case Intrinsic::riscv_shfl:
6961     case Intrinsic::riscv_unshfl: {
6962       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6963              "Unexpected custom legalisation");
6964       SDValue NewOp1 =
6965           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6966       SDValue NewOp2 =
6967           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6968       unsigned Opc =
6969           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6970       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6971       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6972       // will be shuffled the same way as the lower 32 bit half, but the two
6973       // halves won't cross.
6974       if (isa<ConstantSDNode>(NewOp2)) {
6975         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6976                              DAG.getConstant(0xf, DL, MVT::i64));
6977         Opc =
6978             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6979       }
6980       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6981       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6982       break;
6983     }
6984     case Intrinsic::riscv_vmv_x_s: {
6985       EVT VT = N->getValueType(0);
6986       MVT XLenVT = Subtarget.getXLenVT();
6987       if (VT.bitsLT(XLenVT)) {
6988         // Simple case just extract using vmv.x.s and truncate.
6989         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6990                                       Subtarget.getXLenVT(), N->getOperand(1));
6991         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6992         return;
6993       }
6994 
6995       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6996              "Unexpected custom legalization");
6997 
6998       // We need to do the move in two steps.
6999       SDValue Vec = N->getOperand(1);
7000       MVT VecVT = Vec.getSimpleValueType();
7001 
7002       // First extract the lower XLEN bits of the element.
7003       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7004 
7005       // To extract the upper XLEN bits of the vector element, shift the first
7006       // element right by 32 bits and re-extract the lower XLEN bits.
7007       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7008       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7009       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7010       SDValue ThirtyTwoV =
7011           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7012                       DAG.getConstant(32, DL, XLenVT), VL);
7013       SDValue LShr32 =
7014           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7015       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7016 
7017       Results.push_back(
7018           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7019       break;
7020     }
7021     }
7022     break;
7023   }
7024   case ISD::VECREDUCE_ADD:
7025   case ISD::VECREDUCE_AND:
7026   case ISD::VECREDUCE_OR:
7027   case ISD::VECREDUCE_XOR:
7028   case ISD::VECREDUCE_SMAX:
7029   case ISD::VECREDUCE_UMAX:
7030   case ISD::VECREDUCE_SMIN:
7031   case ISD::VECREDUCE_UMIN:
7032     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7033       Results.push_back(V);
7034     break;
7035   case ISD::VP_REDUCE_ADD:
7036   case ISD::VP_REDUCE_AND:
7037   case ISD::VP_REDUCE_OR:
7038   case ISD::VP_REDUCE_XOR:
7039   case ISD::VP_REDUCE_SMAX:
7040   case ISD::VP_REDUCE_UMAX:
7041   case ISD::VP_REDUCE_SMIN:
7042   case ISD::VP_REDUCE_UMIN:
7043     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7044       Results.push_back(V);
7045     break;
7046   case ISD::FLT_ROUNDS_: {
7047     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7048     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7049     Results.push_back(Res.getValue(0));
7050     Results.push_back(Res.getValue(1));
7051     break;
7052   }
7053   }
7054 }
7055 
7056 // A structure to hold one of the bit-manipulation patterns below. Together, a
7057 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7058 //   (or (and (shl x, 1), 0xAAAAAAAA),
7059 //       (and (srl x, 1), 0x55555555))
7060 struct RISCVBitmanipPat {
7061   SDValue Op;
7062   unsigned ShAmt;
7063   bool IsSHL;
7064 
7065   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7066     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7067   }
7068 };
7069 
7070 // Matches patterns of the form
7071 //   (and (shl x, C2), (C1 << C2))
7072 //   (and (srl x, C2), C1)
7073 //   (shl (and x, C1), C2)
7074 //   (srl (and x, (C1 << C2)), C2)
7075 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7076 // The expected masks for each shift amount are specified in BitmanipMasks where
7077 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7078 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7079 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7080 // XLen is 64.
7081 static Optional<RISCVBitmanipPat>
7082 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7083   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7084          "Unexpected number of masks");
7085   Optional<uint64_t> Mask;
7086   // Optionally consume a mask around the shift operation.
7087   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7088     Mask = Op.getConstantOperandVal(1);
7089     Op = Op.getOperand(0);
7090   }
7091   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7092     return None;
7093   bool IsSHL = Op.getOpcode() == ISD::SHL;
7094 
7095   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7096     return None;
7097   uint64_t ShAmt = Op.getConstantOperandVal(1);
7098 
7099   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7100   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7101     return None;
7102   // If we don't have enough masks for 64 bit, then we must be trying to
7103   // match SHFL so we're only allowed to shift 1/4 of the width.
7104   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7105     return None;
7106 
7107   SDValue Src = Op.getOperand(0);
7108 
7109   // The expected mask is shifted left when the AND is found around SHL
7110   // patterns.
7111   //   ((x >> 1) & 0x55555555)
7112   //   ((x << 1) & 0xAAAAAAAA)
7113   bool SHLExpMask = IsSHL;
7114 
7115   if (!Mask) {
7116     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7117     // the mask is all ones: consume that now.
7118     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7119       Mask = Src.getConstantOperandVal(1);
7120       Src = Src.getOperand(0);
7121       // The expected mask is now in fact shifted left for SRL, so reverse the
7122       // decision.
7123       //   ((x & 0xAAAAAAAA) >> 1)
7124       //   ((x & 0x55555555) << 1)
7125       SHLExpMask = !SHLExpMask;
7126     } else {
7127       // Use a default shifted mask of all-ones if there's no AND, truncated
7128       // down to the expected width. This simplifies the logic later on.
7129       Mask = maskTrailingOnes<uint64_t>(Width);
7130       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7131     }
7132   }
7133 
7134   unsigned MaskIdx = Log2_32(ShAmt);
7135   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7136 
7137   if (SHLExpMask)
7138     ExpMask <<= ShAmt;
7139 
7140   if (Mask != ExpMask)
7141     return None;
7142 
7143   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7144 }
7145 
7146 // Matches any of the following bit-manipulation patterns:
7147 //   (and (shl x, 1), (0x55555555 << 1))
7148 //   (and (srl x, 1), 0x55555555)
7149 //   (shl (and x, 0x55555555), 1)
7150 //   (srl (and x, (0x55555555 << 1)), 1)
7151 // where the shift amount and mask may vary thus:
7152 //   [1]  = 0x55555555 / 0xAAAAAAAA
7153 //   [2]  = 0x33333333 / 0xCCCCCCCC
7154 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7155 //   [8]  = 0x00FF00FF / 0xFF00FF00
7156 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7157 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7158 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7159   // These are the unshifted masks which we use to match bit-manipulation
7160   // patterns. They may be shifted left in certain circumstances.
7161   static const uint64_t BitmanipMasks[] = {
7162       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7163       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7164 
7165   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7166 }
7167 
7168 // Match the following pattern as a GREVI(W) operation
7169 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7170 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7171                                const RISCVSubtarget &Subtarget) {
7172   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7173   EVT VT = Op.getValueType();
7174 
7175   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7176     auto LHS = matchGREVIPat(Op.getOperand(0));
7177     auto RHS = matchGREVIPat(Op.getOperand(1));
7178     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7179       SDLoc DL(Op);
7180       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7181                          DAG.getConstant(LHS->ShAmt, DL, VT));
7182     }
7183   }
7184   return SDValue();
7185 }
7186 
7187 // Matches any the following pattern as a GORCI(W) operation
7188 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7189 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7190 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7191 // Note that with the variant of 3.,
7192 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7193 // the inner pattern will first be matched as GREVI and then the outer
7194 // pattern will be matched to GORC via the first rule above.
7195 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7196 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7197                                const RISCVSubtarget &Subtarget) {
7198   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7199   EVT VT = Op.getValueType();
7200 
7201   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7202     SDLoc DL(Op);
7203     SDValue Op0 = Op.getOperand(0);
7204     SDValue Op1 = Op.getOperand(1);
7205 
7206     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7207       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7208           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7209           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7210         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7211       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7212       if ((Reverse.getOpcode() == ISD::ROTL ||
7213            Reverse.getOpcode() == ISD::ROTR) &&
7214           Reverse.getOperand(0) == X &&
7215           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7216         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7217         if (RotAmt == (VT.getSizeInBits() / 2))
7218           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7219                              DAG.getConstant(RotAmt, DL, VT));
7220       }
7221       return SDValue();
7222     };
7223 
7224     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7225     if (SDValue V = MatchOROfReverse(Op0, Op1))
7226       return V;
7227     if (SDValue V = MatchOROfReverse(Op1, Op0))
7228       return V;
7229 
7230     // OR is commutable so canonicalize its OR operand to the left
7231     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7232       std::swap(Op0, Op1);
7233     if (Op0.getOpcode() != ISD::OR)
7234       return SDValue();
7235     SDValue OrOp0 = Op0.getOperand(0);
7236     SDValue OrOp1 = Op0.getOperand(1);
7237     auto LHS = matchGREVIPat(OrOp0);
7238     // OR is commutable so swap the operands and try again: x might have been
7239     // on the left
7240     if (!LHS) {
7241       std::swap(OrOp0, OrOp1);
7242       LHS = matchGREVIPat(OrOp0);
7243     }
7244     auto RHS = matchGREVIPat(Op1);
7245     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7246       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7247                          DAG.getConstant(LHS->ShAmt, DL, VT));
7248     }
7249   }
7250   return SDValue();
7251 }
7252 
7253 // Matches any of the following bit-manipulation patterns:
7254 //   (and (shl x, 1), (0x22222222 << 1))
7255 //   (and (srl x, 1), 0x22222222)
7256 //   (shl (and x, 0x22222222), 1)
7257 //   (srl (and x, (0x22222222 << 1)), 1)
7258 // where the shift amount and mask may vary thus:
7259 //   [1]  = 0x22222222 / 0x44444444
7260 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7261 //   [4]  = 0x00F000F0 / 0x0F000F00
7262 //   [8]  = 0x0000FF00 / 0x00FF0000
7263 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7264 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7265   // These are the unshifted masks which we use to match bit-manipulation
7266   // patterns. They may be shifted left in certain circumstances.
7267   static const uint64_t BitmanipMasks[] = {
7268       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7269       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7270 
7271   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7272 }
7273 
7274 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7275 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7276                                const RISCVSubtarget &Subtarget) {
7277   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7278   EVT VT = Op.getValueType();
7279 
7280   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7281     return SDValue();
7282 
7283   SDValue Op0 = Op.getOperand(0);
7284   SDValue Op1 = Op.getOperand(1);
7285 
7286   // Or is commutable so canonicalize the second OR to the LHS.
7287   if (Op0.getOpcode() != ISD::OR)
7288     std::swap(Op0, Op1);
7289   if (Op0.getOpcode() != ISD::OR)
7290     return SDValue();
7291 
7292   // We found an inner OR, so our operands are the operands of the inner OR
7293   // and the other operand of the outer OR.
7294   SDValue A = Op0.getOperand(0);
7295   SDValue B = Op0.getOperand(1);
7296   SDValue C = Op1;
7297 
7298   auto Match1 = matchSHFLPat(A);
7299   auto Match2 = matchSHFLPat(B);
7300 
7301   // If neither matched, we failed.
7302   if (!Match1 && !Match2)
7303     return SDValue();
7304 
7305   // We had at least one match. if one failed, try the remaining C operand.
7306   if (!Match1) {
7307     std::swap(A, C);
7308     Match1 = matchSHFLPat(A);
7309     if (!Match1)
7310       return SDValue();
7311   } else if (!Match2) {
7312     std::swap(B, C);
7313     Match2 = matchSHFLPat(B);
7314     if (!Match2)
7315       return SDValue();
7316   }
7317   assert(Match1 && Match2);
7318 
7319   // Make sure our matches pair up.
7320   if (!Match1->formsPairWith(*Match2))
7321     return SDValue();
7322 
7323   // All the remains is to make sure C is an AND with the same input, that masks
7324   // out the bits that are being shuffled.
7325   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7326       C.getOperand(0) != Match1->Op)
7327     return SDValue();
7328 
7329   uint64_t Mask = C.getConstantOperandVal(1);
7330 
7331   static const uint64_t BitmanipMasks[] = {
7332       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7333       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7334   };
7335 
7336   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7337   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7338   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7339 
7340   if (Mask != ExpMask)
7341     return SDValue();
7342 
7343   SDLoc DL(Op);
7344   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7345                      DAG.getConstant(Match1->ShAmt, DL, VT));
7346 }
7347 
7348 // Optimize (add (shl x, c0), (shl y, c1)) ->
7349 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7350 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7351                                   const RISCVSubtarget &Subtarget) {
7352   // Perform this optimization only in the zba extension.
7353   if (!Subtarget.hasStdExtZba())
7354     return SDValue();
7355 
7356   // Skip for vector types and larger types.
7357   EVT VT = N->getValueType(0);
7358   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7359     return SDValue();
7360 
7361   // The two operand nodes must be SHL and have no other use.
7362   SDValue N0 = N->getOperand(0);
7363   SDValue N1 = N->getOperand(1);
7364   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7365       !N0->hasOneUse() || !N1->hasOneUse())
7366     return SDValue();
7367 
7368   // Check c0 and c1.
7369   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7370   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7371   if (!N0C || !N1C)
7372     return SDValue();
7373   int64_t C0 = N0C->getSExtValue();
7374   int64_t C1 = N1C->getSExtValue();
7375   if (C0 <= 0 || C1 <= 0)
7376     return SDValue();
7377 
7378   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7379   int64_t Bits = std::min(C0, C1);
7380   int64_t Diff = std::abs(C0 - C1);
7381   if (Diff != 1 && Diff != 2 && Diff != 3)
7382     return SDValue();
7383 
7384   // Build nodes.
7385   SDLoc DL(N);
7386   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7387   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7388   SDValue NA0 =
7389       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7390   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7391   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7392 }
7393 
7394 // Combine
7395 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) for RV32
7396 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) for RV32
7397 // ROTR ((GREV x, 56), 32) -> (GREVI x, 24) for RV64
7398 // ROTL ((GREV x, 56), 32) -> (GREVI x, 24) for RV64
7399 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64
7400 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64
7401 // The grev patterns represents BSWAP.
7402 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7403 // off the grev.
7404 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7405                                           const RISCVSubtarget &Subtarget) {
7406   bool IsWInstruction =
7407       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7408   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7409           IsWInstruction) &&
7410          "Unexpected opcode!");
7411   SDValue Src = N->getOperand(0);
7412   EVT VT = N->getValueType(0);
7413   SDLoc DL(N);
7414 
7415   if (!Subtarget.hasStdExtZbp())
7416     return SDValue();
7417 
7418   unsigned GrevOpc = IsWInstruction ? RISCVISD::GREVW : RISCVISD::GREV;
7419   if (Src.getOpcode() != GrevOpc)
7420     return SDValue();
7421 
7422   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7423       !isa<ConstantSDNode>(Src.getOperand(1)))
7424     return SDValue();
7425 
7426   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7427   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7428 
7429   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7430   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7431   unsigned ShAmt1 = N->getConstantOperandVal(1);
7432   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7433   if (BitWidth < 16 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7434     return SDValue();
7435 
7436   Src = Src.getOperand(0);
7437 
7438   // Toggle bit the MSB of the shift.
7439   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7440   if (CombinedShAmt == 0)
7441     return Src;
7442 
7443   return DAG.getNode(
7444       GrevOpc, DL, VT, Src,
7445       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7446 }
7447 
7448 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7449 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7450 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7451 // not undo itself, but they are redundant.
7452 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7453   SDValue Src = N->getOperand(0);
7454 
7455   if (Src.getOpcode() != N->getOpcode())
7456     return SDValue();
7457 
7458   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7459       !isa<ConstantSDNode>(Src.getOperand(1)))
7460     return SDValue();
7461 
7462   unsigned ShAmt1 = N->getConstantOperandVal(1);
7463   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7464   Src = Src.getOperand(0);
7465 
7466   unsigned CombinedShAmt;
7467   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7468     CombinedShAmt = ShAmt1 | ShAmt2;
7469   else
7470     CombinedShAmt = ShAmt1 ^ ShAmt2;
7471 
7472   if (CombinedShAmt == 0)
7473     return Src;
7474 
7475   SDLoc DL(N);
7476   return DAG.getNode(
7477       N->getOpcode(), DL, N->getValueType(0), Src,
7478       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7479 }
7480 
7481 // Combine a constant select operand into its use:
7482 //
7483 // (and (select cond, -1, c), x)
7484 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7485 // (or  (select cond, 0, c), x)
7486 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7487 // (xor (select cond, 0, c), x)
7488 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7489 // (add (select cond, 0, c), x)
7490 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7491 // (sub x, (select cond, 0, c))
7492 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7493 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7494                                    SelectionDAG &DAG, bool AllOnes) {
7495   EVT VT = N->getValueType(0);
7496 
7497   // Skip vectors.
7498   if (VT.isVector())
7499     return SDValue();
7500 
7501   if ((Slct.getOpcode() != ISD::SELECT &&
7502        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7503       !Slct.hasOneUse())
7504     return SDValue();
7505 
7506   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7507     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7508   };
7509 
7510   bool SwapSelectOps;
7511   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7512   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7513   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7514   SDValue NonConstantVal;
7515   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7516     SwapSelectOps = false;
7517     NonConstantVal = FalseVal;
7518   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7519     SwapSelectOps = true;
7520     NonConstantVal = TrueVal;
7521   } else
7522     return SDValue();
7523 
7524   // Slct is now know to be the desired identity constant when CC is true.
7525   TrueVal = OtherOp;
7526   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7527   // Unless SwapSelectOps says the condition should be false.
7528   if (SwapSelectOps)
7529     std::swap(TrueVal, FalseVal);
7530 
7531   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7532     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7533                        {Slct.getOperand(0), Slct.getOperand(1),
7534                         Slct.getOperand(2), TrueVal, FalseVal});
7535 
7536   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7537                      {Slct.getOperand(0), TrueVal, FalseVal});
7538 }
7539 
7540 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7541 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7542                                               bool AllOnes) {
7543   SDValue N0 = N->getOperand(0);
7544   SDValue N1 = N->getOperand(1);
7545   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7546     return Result;
7547   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7548     return Result;
7549   return SDValue();
7550 }
7551 
7552 // Transform (add (mul x, c0), c1) ->
7553 //           (add (mul (add x, c1/c0), c0), c1%c0).
7554 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7555 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7556 // to an infinite loop in DAGCombine if transformed.
7557 // Or transform (add (mul x, c0), c1) ->
7558 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7559 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7560 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7561 // lead to an infinite loop in DAGCombine if transformed.
7562 // Or transform (add (mul x, c0), c1) ->
7563 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7564 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7565 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7566 // lead to an infinite loop in DAGCombine if transformed.
7567 // Or transform (add (mul x, c0), c1) ->
7568 //              (mul (add x, c1/c0), c0).
7569 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7570 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7571                                      const RISCVSubtarget &Subtarget) {
7572   // Skip for vector types and larger types.
7573   EVT VT = N->getValueType(0);
7574   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7575     return SDValue();
7576   // The first operand node must be a MUL and has no other use.
7577   SDValue N0 = N->getOperand(0);
7578   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7579     return SDValue();
7580   // Check if c0 and c1 match above conditions.
7581   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7582   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7583   if (!N0C || !N1C)
7584     return SDValue();
7585   // If N0C has multiple uses it's possible one of the cases in
7586   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7587   // in an infinite loop.
7588   if (!N0C->hasOneUse())
7589     return SDValue();
7590   int64_t C0 = N0C->getSExtValue();
7591   int64_t C1 = N1C->getSExtValue();
7592   int64_t CA, CB;
7593   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7594     return SDValue();
7595   // Search for proper CA (non-zero) and CB that both are simm12.
7596   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7597       !isInt<12>(C0 * (C1 / C0))) {
7598     CA = C1 / C0;
7599     CB = C1 % C0;
7600   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7601              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7602     CA = C1 / C0 + 1;
7603     CB = C1 % C0 - C0;
7604   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7605              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7606     CA = C1 / C0 - 1;
7607     CB = C1 % C0 + C0;
7608   } else
7609     return SDValue();
7610   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7611   SDLoc DL(N);
7612   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7613                              DAG.getConstant(CA, DL, VT));
7614   SDValue New1 =
7615       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7616   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7617 }
7618 
7619 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7620                                  const RISCVSubtarget &Subtarget) {
7621   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7622     return V;
7623   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7624     return V;
7625   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7626   //      (select lhs, rhs, cc, x, (add x, y))
7627   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7628 }
7629 
7630 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7631   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7632   //      (select lhs, rhs, cc, x, (sub x, y))
7633   SDValue N0 = N->getOperand(0);
7634   SDValue N1 = N->getOperand(1);
7635   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7636 }
7637 
7638 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7639   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7640   //      (select lhs, rhs, cc, x, (and x, y))
7641   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7642 }
7643 
7644 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7645                                 const RISCVSubtarget &Subtarget) {
7646   if (Subtarget.hasStdExtZbp()) {
7647     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7648       return GREV;
7649     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7650       return GORC;
7651     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7652       return SHFL;
7653   }
7654 
7655   // fold (or (select cond, 0, y), x) ->
7656   //      (select cond, x, (or x, y))
7657   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7658 }
7659 
7660 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7661   // fold (xor (select cond, 0, y), x) ->
7662   //      (select cond, x, (xor x, y))
7663   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7664 }
7665 
7666 static SDValue
7667 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7668                                 const RISCVSubtarget &Subtarget) {
7669   SDValue Src = N->getOperand(0);
7670   EVT VT = N->getValueType(0);
7671 
7672   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7673   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7674       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7675     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7676                        Src.getOperand(0));
7677 
7678   // Fold (i64 (sext_inreg (abs X), i32)) ->
7679   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7680   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7681   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7682   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7683   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7684   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7685   // may get combined into an earlier operation so we need to use
7686   // ComputeNumSignBits.
7687   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7688   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7689   // we can't assume that X has 33 sign bits. We must check.
7690   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7691       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7692       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7693       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7694     SDLoc DL(N);
7695     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7696     SDValue Neg =
7697         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7698     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7699                       DAG.getValueType(MVT::i32));
7700     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7701   }
7702 
7703   return SDValue();
7704 }
7705 
7706 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7707 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7708 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7709                                              bool Commute = false) {
7710   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7711           N->getOpcode() == RISCVISD::SUB_VL) &&
7712          "Unexpected opcode");
7713   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7714   SDValue Op0 = N->getOperand(0);
7715   SDValue Op1 = N->getOperand(1);
7716   if (Commute)
7717     std::swap(Op0, Op1);
7718 
7719   MVT VT = N->getSimpleValueType(0);
7720 
7721   // Determine the narrow size for a widening add/sub.
7722   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7723   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7724                                   VT.getVectorElementCount());
7725 
7726   SDValue Mask = N->getOperand(2);
7727   SDValue VL = N->getOperand(3);
7728 
7729   SDLoc DL(N);
7730 
7731   // If the RHS is a sext or zext, we can form a widening op.
7732   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7733        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7734       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7735     unsigned ExtOpc = Op1.getOpcode();
7736     Op1 = Op1.getOperand(0);
7737     // Re-introduce narrower extends if needed.
7738     if (Op1.getValueType() != NarrowVT)
7739       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7740 
7741     unsigned WOpc;
7742     if (ExtOpc == RISCVISD::VSEXT_VL)
7743       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7744     else
7745       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7746 
7747     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7748   }
7749 
7750   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7751   // sext/zext?
7752 
7753   return SDValue();
7754 }
7755 
7756 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7757 // vwsub(u).vv/vx.
7758 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7759   SDValue Op0 = N->getOperand(0);
7760   SDValue Op1 = N->getOperand(1);
7761   SDValue Mask = N->getOperand(2);
7762   SDValue VL = N->getOperand(3);
7763 
7764   MVT VT = N->getSimpleValueType(0);
7765   MVT NarrowVT = Op1.getSimpleValueType();
7766   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7767 
7768   unsigned VOpc;
7769   switch (N->getOpcode()) {
7770   default: llvm_unreachable("Unexpected opcode");
7771   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7772   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7773   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7774   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7775   }
7776 
7777   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7778                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7779 
7780   SDLoc DL(N);
7781 
7782   // If the LHS is a sext or zext, we can narrow this op to the same size as
7783   // the RHS.
7784   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7785        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7786       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7787     unsigned ExtOpc = Op0.getOpcode();
7788     Op0 = Op0.getOperand(0);
7789     // Re-introduce narrower extends if needed.
7790     if (Op0.getValueType() != NarrowVT)
7791       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7792     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7793   }
7794 
7795   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7796                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7797 
7798   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7799   // to commute and use a vwadd(u).vx instead.
7800   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7801       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7802     Op0 = Op0.getOperand(1);
7803 
7804     // See if have enough sign bits or zero bits in the scalar to use a
7805     // widening add/sub by splatting to smaller element size.
7806     unsigned EltBits = VT.getScalarSizeInBits();
7807     unsigned ScalarBits = Op0.getValueSizeInBits();
7808     // Make sure we're getting all element bits from the scalar register.
7809     // FIXME: Support implicit sign extension of vmv.v.x?
7810     if (ScalarBits < EltBits)
7811       return SDValue();
7812 
7813     if (IsSigned) {
7814       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7815         return SDValue();
7816     } else {
7817       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7818       if (!DAG.MaskedValueIsZero(Op0, Mask))
7819         return SDValue();
7820     }
7821 
7822     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7823                       DAG.getUNDEF(NarrowVT), Op0, VL);
7824     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7825   }
7826 
7827   return SDValue();
7828 }
7829 
7830 // Try to form VWMUL, VWMULU or VWMULSU.
7831 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7832 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7833                                        bool Commute) {
7834   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7835   SDValue Op0 = N->getOperand(0);
7836   SDValue Op1 = N->getOperand(1);
7837   if (Commute)
7838     std::swap(Op0, Op1);
7839 
7840   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7841   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7842   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7843   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7844     return SDValue();
7845 
7846   SDValue Mask = N->getOperand(2);
7847   SDValue VL = N->getOperand(3);
7848 
7849   // Make sure the mask and VL match.
7850   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7851     return SDValue();
7852 
7853   MVT VT = N->getSimpleValueType(0);
7854 
7855   // Determine the narrow size for a widening multiply.
7856   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7857   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7858                                   VT.getVectorElementCount());
7859 
7860   SDLoc DL(N);
7861 
7862   // See if the other operand is the same opcode.
7863   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7864     if (!Op1.hasOneUse())
7865       return SDValue();
7866 
7867     // Make sure the mask and VL match.
7868     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7869       return SDValue();
7870 
7871     Op1 = Op1.getOperand(0);
7872   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7873     // The operand is a splat of a scalar.
7874 
7875     // The pasthru must be undef for tail agnostic
7876     if (!Op1.getOperand(0).isUndef())
7877       return SDValue();
7878     // The VL must be the same.
7879     if (Op1.getOperand(2) != VL)
7880       return SDValue();
7881 
7882     // Get the scalar value.
7883     Op1 = Op1.getOperand(1);
7884 
7885     // See if have enough sign bits or zero bits in the scalar to use a
7886     // widening multiply by splatting to smaller element size.
7887     unsigned EltBits = VT.getScalarSizeInBits();
7888     unsigned ScalarBits = Op1.getValueSizeInBits();
7889     // Make sure we're getting all element bits from the scalar register.
7890     // FIXME: Support implicit sign extension of vmv.v.x?
7891     if (ScalarBits < EltBits)
7892       return SDValue();
7893 
7894     // If the LHS is a sign extend, try to use vwmul.
7895     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
7896       // Can use vwmul.
7897     } else {
7898       // Otherwise try to use vwmulu or vwmulsu.
7899       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7900       if (DAG.MaskedValueIsZero(Op1, Mask))
7901         IsVWMULSU = IsSignExt;
7902       else
7903         return SDValue();
7904     }
7905 
7906     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7907                       DAG.getUNDEF(NarrowVT), Op1, VL);
7908   } else
7909     return SDValue();
7910 
7911   Op0 = Op0.getOperand(0);
7912 
7913   // Re-introduce narrower extends if needed.
7914   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7915   if (Op0.getValueType() != NarrowVT)
7916     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7917   // vwmulsu requires second operand to be zero extended.
7918   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7919   if (Op1.getValueType() != NarrowVT)
7920     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7921 
7922   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7923   if (!IsVWMULSU)
7924     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7925   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7926 }
7927 
7928 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7929   switch (Op.getOpcode()) {
7930   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7931   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7932   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7933   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7934   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7935   }
7936 
7937   return RISCVFPRndMode::Invalid;
7938 }
7939 
7940 // Fold
7941 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7942 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7943 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7944 //   (fp_to_int (fceil X))      -> fcvt X, rup
7945 //   (fp_to_int (fround X))     -> fcvt X, rmm
7946 static SDValue performFP_TO_INTCombine(SDNode *N,
7947                                        TargetLowering::DAGCombinerInfo &DCI,
7948                                        const RISCVSubtarget &Subtarget) {
7949   SelectionDAG &DAG = DCI.DAG;
7950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7951   MVT XLenVT = Subtarget.getXLenVT();
7952 
7953   // Only handle XLen or i32 types. Other types narrower than XLen will
7954   // eventually be legalized to XLenVT.
7955   EVT VT = N->getValueType(0);
7956   if (VT != MVT::i32 && VT != XLenVT)
7957     return SDValue();
7958 
7959   SDValue Src = N->getOperand(0);
7960 
7961   // Ensure the FP type is also legal.
7962   if (!TLI.isTypeLegal(Src.getValueType()))
7963     return SDValue();
7964 
7965   // Don't do this for f16 with Zfhmin and not Zfh.
7966   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7967     return SDValue();
7968 
7969   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7970   if (FRM == RISCVFPRndMode::Invalid)
7971     return SDValue();
7972 
7973   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7974 
7975   unsigned Opc;
7976   if (VT == XLenVT)
7977     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7978   else
7979     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7980 
7981   SDLoc DL(N);
7982   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7983                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7984   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7985 }
7986 
7987 // Fold
7988 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7989 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7990 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7991 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7992 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7993 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7994                                        TargetLowering::DAGCombinerInfo &DCI,
7995                                        const RISCVSubtarget &Subtarget) {
7996   SelectionDAG &DAG = DCI.DAG;
7997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7998   MVT XLenVT = Subtarget.getXLenVT();
7999 
8000   // Only handle XLen types. Other types narrower than XLen will eventually be
8001   // legalized to XLenVT.
8002   EVT DstVT = N->getValueType(0);
8003   if (DstVT != XLenVT)
8004     return SDValue();
8005 
8006   SDValue Src = N->getOperand(0);
8007 
8008   // Ensure the FP type is also legal.
8009   if (!TLI.isTypeLegal(Src.getValueType()))
8010     return SDValue();
8011 
8012   // Don't do this for f16 with Zfhmin and not Zfh.
8013   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8014     return SDValue();
8015 
8016   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8017 
8018   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8019   if (FRM == RISCVFPRndMode::Invalid)
8020     return SDValue();
8021 
8022   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8023 
8024   unsigned Opc;
8025   if (SatVT == DstVT)
8026     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8027   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8028     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8029   else
8030     return SDValue();
8031   // FIXME: Support other SatVTs by clamping before or after the conversion.
8032 
8033   Src = Src.getOperand(0);
8034 
8035   SDLoc DL(N);
8036   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8037                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8038 
8039   // RISCV FP-to-int conversions saturate to the destination register size, but
8040   // don't produce 0 for nan.
8041   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8042   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8043 }
8044 
8045 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8046                                                DAGCombinerInfo &DCI) const {
8047   SelectionDAG &DAG = DCI.DAG;
8048 
8049   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8050   // bits are demanded. N will be added to the Worklist if it was not deleted.
8051   // Caller should return SDValue(N, 0) if this returns true.
8052   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8053     SDValue Op = N->getOperand(OpNo);
8054     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8055     if (!SimplifyDemandedBits(Op, Mask, DCI))
8056       return false;
8057 
8058     if (N->getOpcode() != ISD::DELETED_NODE)
8059       DCI.AddToWorklist(N);
8060     return true;
8061   };
8062 
8063   switch (N->getOpcode()) {
8064   default:
8065     break;
8066   case RISCVISD::SplitF64: {
8067     SDValue Op0 = N->getOperand(0);
8068     // If the input to SplitF64 is just BuildPairF64 then the operation is
8069     // redundant. Instead, use BuildPairF64's operands directly.
8070     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8071       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8072 
8073     if (Op0->isUndef()) {
8074       SDValue Lo = DAG.getUNDEF(MVT::i32);
8075       SDValue Hi = DAG.getUNDEF(MVT::i32);
8076       return DCI.CombineTo(N, Lo, Hi);
8077     }
8078 
8079     SDLoc DL(N);
8080 
8081     // It's cheaper to materialise two 32-bit integers than to load a double
8082     // from the constant pool and transfer it to integer registers through the
8083     // stack.
8084     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8085       APInt V = C->getValueAPF().bitcastToAPInt();
8086       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8087       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8088       return DCI.CombineTo(N, Lo, Hi);
8089     }
8090 
8091     // This is a target-specific version of a DAGCombine performed in
8092     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8093     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8094     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8095     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8096         !Op0.getNode()->hasOneUse())
8097       break;
8098     SDValue NewSplitF64 =
8099         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8100                     Op0.getOperand(0));
8101     SDValue Lo = NewSplitF64.getValue(0);
8102     SDValue Hi = NewSplitF64.getValue(1);
8103     APInt SignBit = APInt::getSignMask(32);
8104     if (Op0.getOpcode() == ISD::FNEG) {
8105       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8106                                   DAG.getConstant(SignBit, DL, MVT::i32));
8107       return DCI.CombineTo(N, Lo, NewHi);
8108     }
8109     assert(Op0.getOpcode() == ISD::FABS);
8110     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8111                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8112     return DCI.CombineTo(N, Lo, NewHi);
8113   }
8114   case RISCVISD::SLLW:
8115   case RISCVISD::SRAW:
8116   case RISCVISD::SRLW: {
8117     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8118     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8119         SimplifyDemandedLowBitsHelper(1, 5))
8120       return SDValue(N, 0);
8121 
8122     break;
8123   }
8124   case ISD::ROTR:
8125   case ISD::ROTL:
8126   case RISCVISD::RORW:
8127   case RISCVISD::ROLW: {
8128     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8129       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8130       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8131           SimplifyDemandedLowBitsHelper(1, 5))
8132         return SDValue(N, 0);
8133     }
8134 
8135     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8136   }
8137   case RISCVISD::CLZW:
8138   case RISCVISD::CTZW: {
8139     // Only the lower 32 bits of the first operand are read
8140     if (SimplifyDemandedLowBitsHelper(0, 32))
8141       return SDValue(N, 0);
8142     break;
8143   }
8144   case RISCVISD::GREV:
8145   case RISCVISD::GORC: {
8146     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8147     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8148     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8149     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8150       return SDValue(N, 0);
8151 
8152     return combineGREVI_GORCI(N, DAG);
8153   }
8154   case RISCVISD::GREVW:
8155   case RISCVISD::GORCW: {
8156     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8157     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8158         SimplifyDemandedLowBitsHelper(1, 5))
8159       return SDValue(N, 0);
8160 
8161     return combineGREVI_GORCI(N, DAG);
8162   }
8163   case RISCVISD::SHFL:
8164   case RISCVISD::UNSHFL: {
8165     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8166     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8167     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8168     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8169       return SDValue(N, 0);
8170 
8171     break;
8172   }
8173   case RISCVISD::SHFLW:
8174   case RISCVISD::UNSHFLW: {
8175     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8176     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8177         SimplifyDemandedLowBitsHelper(1, 4))
8178       return SDValue(N, 0);
8179 
8180     break;
8181   }
8182   case RISCVISD::BCOMPRESSW:
8183   case RISCVISD::BDECOMPRESSW: {
8184     // Only the lower 32 bits of LHS and RHS are read.
8185     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8186         SimplifyDemandedLowBitsHelper(1, 32))
8187       return SDValue(N, 0);
8188 
8189     break;
8190   }
8191   case RISCVISD::FSR:
8192   case RISCVISD::FSL:
8193   case RISCVISD::FSRW:
8194   case RISCVISD::FSLW: {
8195     bool IsWInstruction =
8196         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8197     unsigned BitWidth =
8198         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8199     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8200     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8201     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8202       return SDValue(N, 0);
8203 
8204     break;
8205   }
8206   case RISCVISD::FMV_X_ANYEXTH:
8207   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8208     SDLoc DL(N);
8209     SDValue Op0 = N->getOperand(0);
8210     MVT VT = N->getSimpleValueType(0);
8211     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8212     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8213     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8214     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8215          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8216         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8217          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8218       assert(Op0.getOperand(0).getValueType() == VT &&
8219              "Unexpected value type!");
8220       return Op0.getOperand(0);
8221     }
8222 
8223     // This is a target-specific version of a DAGCombine performed in
8224     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8225     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8226     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8227     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8228         !Op0.getNode()->hasOneUse())
8229       break;
8230     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8231     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8232     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8233     if (Op0.getOpcode() == ISD::FNEG)
8234       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8235                          DAG.getConstant(SignBit, DL, VT));
8236 
8237     assert(Op0.getOpcode() == ISD::FABS);
8238     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8239                        DAG.getConstant(~SignBit, DL, VT));
8240   }
8241   case ISD::ADD:
8242     return performADDCombine(N, DAG, Subtarget);
8243   case ISD::SUB:
8244     return performSUBCombine(N, DAG);
8245   case ISD::AND:
8246     return performANDCombine(N, DAG);
8247   case ISD::OR:
8248     return performORCombine(N, DAG, Subtarget);
8249   case ISD::XOR:
8250     return performXORCombine(N, DAG);
8251   case ISD::SIGN_EXTEND_INREG:
8252     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8253   case ISD::ZERO_EXTEND:
8254     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8255     // type legalization. This is safe because fp_to_uint produces poison if
8256     // it overflows.
8257     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8258       SDValue Src = N->getOperand(0);
8259       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8260           isTypeLegal(Src.getOperand(0).getValueType()))
8261         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8262                            Src.getOperand(0));
8263       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8264           isTypeLegal(Src.getOperand(1).getValueType())) {
8265         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8266         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8267                                   Src.getOperand(0), Src.getOperand(1));
8268         DCI.CombineTo(N, Res);
8269         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8270         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8271         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8272       }
8273     }
8274     return SDValue();
8275   case RISCVISD::SELECT_CC: {
8276     // Transform
8277     SDValue LHS = N->getOperand(0);
8278     SDValue RHS = N->getOperand(1);
8279     SDValue TrueV = N->getOperand(3);
8280     SDValue FalseV = N->getOperand(4);
8281 
8282     // If the True and False values are the same, we don't need a select_cc.
8283     if (TrueV == FalseV)
8284       return TrueV;
8285 
8286     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8287     if (!ISD::isIntEqualitySetCC(CCVal))
8288       break;
8289 
8290     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8291     //      (select_cc X, Y, lt, trueV, falseV)
8292     // Sometimes the setcc is introduced after select_cc has been formed.
8293     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8294         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8295       // If we're looking for eq 0 instead of ne 0, we need to invert the
8296       // condition.
8297       bool Invert = CCVal == ISD::SETEQ;
8298       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8299       if (Invert)
8300         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8301 
8302       SDLoc DL(N);
8303       RHS = LHS.getOperand(1);
8304       LHS = LHS.getOperand(0);
8305       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8306 
8307       SDValue TargetCC = DAG.getCondCode(CCVal);
8308       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8309                          {LHS, RHS, TargetCC, TrueV, FalseV});
8310     }
8311 
8312     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8313     //      (select_cc X, Y, eq/ne, trueV, falseV)
8314     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8315       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8316                          {LHS.getOperand(0), LHS.getOperand(1),
8317                           N->getOperand(2), TrueV, FalseV});
8318     // (select_cc X, 1, setne, trueV, falseV) ->
8319     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8320     // This can occur when legalizing some floating point comparisons.
8321     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8322     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8323       SDLoc DL(N);
8324       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8325       SDValue TargetCC = DAG.getCondCode(CCVal);
8326       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8327       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8328                          {LHS, RHS, TargetCC, TrueV, FalseV});
8329     }
8330 
8331     break;
8332   }
8333   case RISCVISD::BR_CC: {
8334     SDValue LHS = N->getOperand(1);
8335     SDValue RHS = N->getOperand(2);
8336     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8337     if (!ISD::isIntEqualitySetCC(CCVal))
8338       break;
8339 
8340     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8341     //      (br_cc X, Y, lt, dest)
8342     // Sometimes the setcc is introduced after br_cc has been formed.
8343     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8344         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8345       // If we're looking for eq 0 instead of ne 0, we need to invert the
8346       // condition.
8347       bool Invert = CCVal == ISD::SETEQ;
8348       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8349       if (Invert)
8350         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8351 
8352       SDLoc DL(N);
8353       RHS = LHS.getOperand(1);
8354       LHS = LHS.getOperand(0);
8355       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8356 
8357       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8358                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8359                          N->getOperand(4));
8360     }
8361 
8362     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8363     //      (br_cc X, Y, eq/ne, trueV, falseV)
8364     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8365       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8366                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8367                          N->getOperand(3), N->getOperand(4));
8368 
8369     // (br_cc X, 1, setne, br_cc) ->
8370     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8371     // This can occur when legalizing some floating point comparisons.
8372     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8373     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8374       SDLoc DL(N);
8375       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8376       SDValue TargetCC = DAG.getCondCode(CCVal);
8377       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8378       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8379                          N->getOperand(0), LHS, RHS, TargetCC,
8380                          N->getOperand(4));
8381     }
8382     break;
8383   }
8384   case ISD::FP_TO_SINT:
8385   case ISD::FP_TO_UINT:
8386     return performFP_TO_INTCombine(N, DCI, Subtarget);
8387   case ISD::FP_TO_SINT_SAT:
8388   case ISD::FP_TO_UINT_SAT:
8389     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8390   case ISD::FCOPYSIGN: {
8391     EVT VT = N->getValueType(0);
8392     if (!VT.isVector())
8393       break;
8394     // There is a form of VFSGNJ which injects the negated sign of its second
8395     // operand. Try and bubble any FNEG up after the extend/round to produce
8396     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8397     // TRUNC=1.
8398     SDValue In2 = N->getOperand(1);
8399     // Avoid cases where the extend/round has multiple uses, as duplicating
8400     // those is typically more expensive than removing a fneg.
8401     if (!In2.hasOneUse())
8402       break;
8403     if (In2.getOpcode() != ISD::FP_EXTEND &&
8404         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8405       break;
8406     In2 = In2.getOperand(0);
8407     if (In2.getOpcode() != ISD::FNEG)
8408       break;
8409     SDLoc DL(N);
8410     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8411     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8412                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8413   }
8414   case ISD::MGATHER:
8415   case ISD::MSCATTER:
8416   case ISD::VP_GATHER:
8417   case ISD::VP_SCATTER: {
8418     if (!DCI.isBeforeLegalize())
8419       break;
8420     SDValue Index, ScaleOp;
8421     bool IsIndexScaled = false;
8422     bool IsIndexSigned = false;
8423     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8424       Index = VPGSN->getIndex();
8425       ScaleOp = VPGSN->getScale();
8426       IsIndexScaled = VPGSN->isIndexScaled();
8427       IsIndexSigned = VPGSN->isIndexSigned();
8428     } else {
8429       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8430       Index = MGSN->getIndex();
8431       ScaleOp = MGSN->getScale();
8432       IsIndexScaled = MGSN->isIndexScaled();
8433       IsIndexSigned = MGSN->isIndexSigned();
8434     }
8435     EVT IndexVT = Index.getValueType();
8436     MVT XLenVT = Subtarget.getXLenVT();
8437     // RISCV indexed loads only support the "unsigned unscaled" addressing
8438     // mode, so anything else must be manually legalized.
8439     bool NeedsIdxLegalization =
8440         IsIndexScaled ||
8441         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8442     if (!NeedsIdxLegalization)
8443       break;
8444 
8445     SDLoc DL(N);
8446 
8447     // Any index legalization should first promote to XLenVT, so we don't lose
8448     // bits when scaling. This may create an illegal index type so we let
8449     // LLVM's legalization take care of the splitting.
8450     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8451     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8452       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8453       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8454                           DL, IndexVT, Index);
8455     }
8456 
8457     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8458     if (IsIndexScaled && Scale != 1) {
8459       // Manually scale the indices by the element size.
8460       // TODO: Sanitize the scale operand here?
8461       // TODO: For VP nodes, should we use VP_SHL here?
8462       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8463       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8464       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8465     }
8466 
8467     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8468     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8469       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8470                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8471                               VPGN->getScale(), VPGN->getMask(),
8472                               VPGN->getVectorLength()},
8473                              VPGN->getMemOperand(), NewIndexTy);
8474     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8475       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8476                               {VPSN->getChain(), VPSN->getValue(),
8477                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8478                                VPSN->getMask(), VPSN->getVectorLength()},
8479                               VPSN->getMemOperand(), NewIndexTy);
8480     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8481       return DAG.getMaskedGather(
8482           N->getVTList(), MGN->getMemoryVT(), DL,
8483           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8484            MGN->getBasePtr(), Index, MGN->getScale()},
8485           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8486     const auto *MSN = cast<MaskedScatterSDNode>(N);
8487     return DAG.getMaskedScatter(
8488         N->getVTList(), MSN->getMemoryVT(), DL,
8489         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8490          Index, MSN->getScale()},
8491         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8492   }
8493   case RISCVISD::SRA_VL:
8494   case RISCVISD::SRL_VL:
8495   case RISCVISD::SHL_VL: {
8496     SDValue ShAmt = N->getOperand(1);
8497     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8498       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8499       SDLoc DL(N);
8500       SDValue VL = N->getOperand(3);
8501       EVT VT = N->getValueType(0);
8502       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8503                           ShAmt.getOperand(1), VL);
8504       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8505                          N->getOperand(2), N->getOperand(3));
8506     }
8507     break;
8508   }
8509   case ISD::SRA:
8510   case ISD::SRL:
8511   case ISD::SHL: {
8512     SDValue ShAmt = N->getOperand(1);
8513     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8514       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8515       SDLoc DL(N);
8516       EVT VT = N->getValueType(0);
8517       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8518                           ShAmt.getOperand(1),
8519                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8520       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8521     }
8522     break;
8523   }
8524   case RISCVISD::ADD_VL:
8525     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8526       return V;
8527     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8528   case RISCVISD::SUB_VL:
8529     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8530   case RISCVISD::VWADD_W_VL:
8531   case RISCVISD::VWADDU_W_VL:
8532   case RISCVISD::VWSUB_W_VL:
8533   case RISCVISD::VWSUBU_W_VL:
8534     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8535   case RISCVISD::MUL_VL:
8536     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8537       return V;
8538     // Mul is commutative.
8539     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8540   case ISD::STORE: {
8541     auto *Store = cast<StoreSDNode>(N);
8542     SDValue Val = Store->getValue();
8543     // Combine store of vmv.x.s to vse with VL of 1.
8544     // FIXME: Support FP.
8545     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8546       SDValue Src = Val.getOperand(0);
8547       EVT VecVT = Src.getValueType();
8548       EVT MemVT = Store->getMemoryVT();
8549       // The memory VT and the element type must match.
8550       if (VecVT.getVectorElementType() == MemVT) {
8551         SDLoc DL(N);
8552         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8553         return DAG.getStoreVP(
8554             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8555             DAG.getConstant(1, DL, MaskVT),
8556             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8557             Store->getMemOperand(), Store->getAddressingMode(),
8558             Store->isTruncatingStore(), /*IsCompress*/ false);
8559       }
8560     }
8561 
8562     break;
8563   }
8564   case ISD::SPLAT_VECTOR: {
8565     EVT VT = N->getValueType(0);
8566     // Only perform this combine on legal MVT types.
8567     if (!isTypeLegal(VT))
8568       break;
8569     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8570                                          DAG, Subtarget))
8571       return Gather;
8572     break;
8573   }
8574   case RISCVISD::VMV_V_X_VL: {
8575     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8576     // scalar input.
8577     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8578     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8579     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8580       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8581         return SDValue(N, 0);
8582 
8583     break;
8584   }
8585   case ISD::INTRINSIC_WO_CHAIN: {
8586     unsigned IntNo = N->getConstantOperandVal(0);
8587     switch (IntNo) {
8588       // By default we do not combine any intrinsic.
8589     default:
8590       return SDValue();
8591     case Intrinsic::riscv_vcpop:
8592     case Intrinsic::riscv_vcpop_mask:
8593     case Intrinsic::riscv_vfirst:
8594     case Intrinsic::riscv_vfirst_mask: {
8595       SDValue VL = N->getOperand(2);
8596       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8597           IntNo == Intrinsic::riscv_vfirst_mask)
8598         VL = N->getOperand(3);
8599       if (!isNullConstant(VL))
8600         return SDValue();
8601       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8602       SDLoc DL(N);
8603       EVT VT = N->getValueType(0);
8604       if (IntNo == Intrinsic::riscv_vfirst ||
8605           IntNo == Intrinsic::riscv_vfirst_mask)
8606         return DAG.getConstant(-1, DL, VT);
8607       return DAG.getConstant(0, DL, VT);
8608     }
8609     }
8610   }
8611   }
8612 
8613   return SDValue();
8614 }
8615 
8616 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8617     const SDNode *N, CombineLevel Level) const {
8618   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8619   // materialised in fewer instructions than `(OP _, c1)`:
8620   //
8621   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8622   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8623   SDValue N0 = N->getOperand(0);
8624   EVT Ty = N0.getValueType();
8625   if (Ty.isScalarInteger() &&
8626       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8627     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8628     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8629     if (C1 && C2) {
8630       const APInt &C1Int = C1->getAPIntValue();
8631       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8632 
8633       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8634       // and the combine should happen, to potentially allow further combines
8635       // later.
8636       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8637           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8638         return true;
8639 
8640       // We can materialise `c1` in an add immediate, so it's "free", and the
8641       // combine should be prevented.
8642       if (C1Int.getMinSignedBits() <= 64 &&
8643           isLegalAddImmediate(C1Int.getSExtValue()))
8644         return false;
8645 
8646       // Neither constant will fit into an immediate, so find materialisation
8647       // costs.
8648       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8649                                               Subtarget.getFeatureBits(),
8650                                               /*CompressionCost*/true);
8651       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8652           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8653           /*CompressionCost*/true);
8654 
8655       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8656       // combine should be prevented.
8657       if (C1Cost < ShiftedC1Cost)
8658         return false;
8659     }
8660   }
8661   return true;
8662 }
8663 
8664 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8665     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8666     TargetLoweringOpt &TLO) const {
8667   // Delay this optimization as late as possible.
8668   if (!TLO.LegalOps)
8669     return false;
8670 
8671   EVT VT = Op.getValueType();
8672   if (VT.isVector())
8673     return false;
8674 
8675   // Only handle AND for now.
8676   if (Op.getOpcode() != ISD::AND)
8677     return false;
8678 
8679   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8680   if (!C)
8681     return false;
8682 
8683   const APInt &Mask = C->getAPIntValue();
8684 
8685   // Clear all non-demanded bits initially.
8686   APInt ShrunkMask = Mask & DemandedBits;
8687 
8688   // Try to make a smaller immediate by setting undemanded bits.
8689 
8690   APInt ExpandedMask = Mask | ~DemandedBits;
8691 
8692   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8693     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8694   };
8695   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8696     if (NewMask == Mask)
8697       return true;
8698     SDLoc DL(Op);
8699     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8700     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8701     return TLO.CombineTo(Op, NewOp);
8702   };
8703 
8704   // If the shrunk mask fits in sign extended 12 bits, let the target
8705   // independent code apply it.
8706   if (ShrunkMask.isSignedIntN(12))
8707     return false;
8708 
8709   // Preserve (and X, 0xffff) when zext.h is supported.
8710   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8711     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8712     if (IsLegalMask(NewMask))
8713       return UseMask(NewMask);
8714   }
8715 
8716   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8717   if (VT == MVT::i64) {
8718     APInt NewMask = APInt(64, 0xffffffff);
8719     if (IsLegalMask(NewMask))
8720       return UseMask(NewMask);
8721   }
8722 
8723   // For the remaining optimizations, we need to be able to make a negative
8724   // number through a combination of mask and undemanded bits.
8725   if (!ExpandedMask.isNegative())
8726     return false;
8727 
8728   // What is the fewest number of bits we need to represent the negative number.
8729   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8730 
8731   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8732   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8733   APInt NewMask = ShrunkMask;
8734   if (MinSignedBits <= 12)
8735     NewMask.setBitsFrom(11);
8736   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8737     NewMask.setBitsFrom(31);
8738   else
8739     return false;
8740 
8741   // Check that our new mask is a subset of the demanded mask.
8742   assert(IsLegalMask(NewMask));
8743   return UseMask(NewMask);
8744 }
8745 
8746 static void computeGREV(APInt &Src, unsigned ShAmt) {
8747   ShAmt &= Src.getBitWidth() - 1;
8748   uint64_t x = Src.getZExtValue();
8749   if (ShAmt & 1)
8750     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8751   if (ShAmt & 2)
8752     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8753   if (ShAmt & 4)
8754     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8755   if (ShAmt & 8)
8756     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8757   if (ShAmt & 16)
8758     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8759   if (ShAmt & 32)
8760     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8761   Src = x;
8762 }
8763 
8764 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8765                                                         KnownBits &Known,
8766                                                         const APInt &DemandedElts,
8767                                                         const SelectionDAG &DAG,
8768                                                         unsigned Depth) const {
8769   unsigned BitWidth = Known.getBitWidth();
8770   unsigned Opc = Op.getOpcode();
8771   assert((Opc >= ISD::BUILTIN_OP_END ||
8772           Opc == ISD::INTRINSIC_WO_CHAIN ||
8773           Opc == ISD::INTRINSIC_W_CHAIN ||
8774           Opc == ISD::INTRINSIC_VOID) &&
8775          "Should use MaskedValueIsZero if you don't know whether Op"
8776          " is a target node!");
8777 
8778   Known.resetAll();
8779   switch (Opc) {
8780   default: break;
8781   case RISCVISD::SELECT_CC: {
8782     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8783     // If we don't know any bits, early out.
8784     if (Known.isUnknown())
8785       break;
8786     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8787 
8788     // Only known if known in both the LHS and RHS.
8789     Known = KnownBits::commonBits(Known, Known2);
8790     break;
8791   }
8792   case RISCVISD::REMUW: {
8793     KnownBits Known2;
8794     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8795     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8796     // We only care about the lower 32 bits.
8797     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8798     // Restore the original width by sign extending.
8799     Known = Known.sext(BitWidth);
8800     break;
8801   }
8802   case RISCVISD::DIVUW: {
8803     KnownBits Known2;
8804     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8805     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8806     // We only care about the lower 32 bits.
8807     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8808     // Restore the original width by sign extending.
8809     Known = Known.sext(BitWidth);
8810     break;
8811   }
8812   case RISCVISD::CTZW: {
8813     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8814     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8815     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8816     Known.Zero.setBitsFrom(LowBits);
8817     break;
8818   }
8819   case RISCVISD::CLZW: {
8820     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8821     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8822     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8823     Known.Zero.setBitsFrom(LowBits);
8824     break;
8825   }
8826   case RISCVISD::GREV:
8827   case RISCVISD::GREVW: {
8828     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8829       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8830       if (Opc == RISCVISD::GREVW)
8831         Known = Known.trunc(32);
8832       unsigned ShAmt = C->getZExtValue();
8833       computeGREV(Known.Zero, ShAmt);
8834       computeGREV(Known.One, ShAmt);
8835       if (Opc == RISCVISD::GREVW)
8836         Known = Known.sext(BitWidth);
8837     }
8838     break;
8839   }
8840   case RISCVISD::READ_VLENB: {
8841     // If we know the minimum VLen from Zvl extensions, we can use that to
8842     // determine the trailing zeros of VLENB.
8843     // FIXME: Limit to 128 bit vectors until we have more testing.
8844     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8845     if (MinVLenB > 0)
8846       Known.Zero.setLowBits(Log2_32(MinVLenB));
8847     // We assume VLENB is no more than 65536 / 8 bytes.
8848     Known.Zero.setBitsFrom(14);
8849     break;
8850   }
8851   case ISD::INTRINSIC_W_CHAIN:
8852   case ISD::INTRINSIC_WO_CHAIN: {
8853     unsigned IntNo =
8854         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8855     switch (IntNo) {
8856     default:
8857       // We can't do anything for most intrinsics.
8858       break;
8859     case Intrinsic::riscv_vsetvli:
8860     case Intrinsic::riscv_vsetvlimax:
8861     case Intrinsic::riscv_vsetvli_opt:
8862     case Intrinsic::riscv_vsetvlimax_opt:
8863       // Assume that VL output is positive and would fit in an int32_t.
8864       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8865       if (BitWidth >= 32)
8866         Known.Zero.setBitsFrom(31);
8867       break;
8868     }
8869     break;
8870   }
8871   }
8872 }
8873 
8874 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8875     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8876     unsigned Depth) const {
8877   switch (Op.getOpcode()) {
8878   default:
8879     break;
8880   case RISCVISD::SELECT_CC: {
8881     unsigned Tmp =
8882         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8883     if (Tmp == 1) return 1;  // Early out.
8884     unsigned Tmp2 =
8885         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8886     return std::min(Tmp, Tmp2);
8887   }
8888   case RISCVISD::SLLW:
8889   case RISCVISD::SRAW:
8890   case RISCVISD::SRLW:
8891   case RISCVISD::DIVW:
8892   case RISCVISD::DIVUW:
8893   case RISCVISD::REMUW:
8894   case RISCVISD::ROLW:
8895   case RISCVISD::RORW:
8896   case RISCVISD::GREVW:
8897   case RISCVISD::GORCW:
8898   case RISCVISD::FSLW:
8899   case RISCVISD::FSRW:
8900   case RISCVISD::SHFLW:
8901   case RISCVISD::UNSHFLW:
8902   case RISCVISD::BCOMPRESSW:
8903   case RISCVISD::BDECOMPRESSW:
8904   case RISCVISD::BFPW:
8905   case RISCVISD::FCVT_W_RV64:
8906   case RISCVISD::FCVT_WU_RV64:
8907   case RISCVISD::STRICT_FCVT_W_RV64:
8908   case RISCVISD::STRICT_FCVT_WU_RV64:
8909     // TODO: As the result is sign-extended, this is conservatively correct. A
8910     // more precise answer could be calculated for SRAW depending on known
8911     // bits in the shift amount.
8912     return 33;
8913   case RISCVISD::SHFL:
8914   case RISCVISD::UNSHFL: {
8915     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8916     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8917     // will stay within the upper 32 bits. If there were more than 32 sign bits
8918     // before there will be at least 33 sign bits after.
8919     if (Op.getValueType() == MVT::i64 &&
8920         isa<ConstantSDNode>(Op.getOperand(1)) &&
8921         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8922       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8923       if (Tmp > 32)
8924         return 33;
8925     }
8926     break;
8927   }
8928   case RISCVISD::VMV_X_S: {
8929     // The number of sign bits of the scalar result is computed by obtaining the
8930     // element type of the input vector operand, subtracting its width from the
8931     // XLEN, and then adding one (sign bit within the element type). If the
8932     // element type is wider than XLen, the least-significant XLEN bits are
8933     // taken.
8934     unsigned XLen = Subtarget.getXLen();
8935     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8936     if (EltBits <= XLen)
8937       return XLen - EltBits + 1;
8938     break;
8939   }
8940   }
8941 
8942   return 1;
8943 }
8944 
8945 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8946                                                   MachineBasicBlock *BB) {
8947   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8948 
8949   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8950   // Should the count have wrapped while it was being read, we need to try
8951   // again.
8952   // ...
8953   // read:
8954   // rdcycleh x3 # load high word of cycle
8955   // rdcycle  x2 # load low word of cycle
8956   // rdcycleh x4 # load high word of cycle
8957   // bne x3, x4, read # check if high word reads match, otherwise try again
8958   // ...
8959 
8960   MachineFunction &MF = *BB->getParent();
8961   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8962   MachineFunction::iterator It = ++BB->getIterator();
8963 
8964   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8965   MF.insert(It, LoopMBB);
8966 
8967   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8968   MF.insert(It, DoneMBB);
8969 
8970   // Transfer the remainder of BB and its successor edges to DoneMBB.
8971   DoneMBB->splice(DoneMBB->begin(), BB,
8972                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8973   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8974 
8975   BB->addSuccessor(LoopMBB);
8976 
8977   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8978   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8979   Register LoReg = MI.getOperand(0).getReg();
8980   Register HiReg = MI.getOperand(1).getReg();
8981   DebugLoc DL = MI.getDebugLoc();
8982 
8983   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8984   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8985       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8986       .addReg(RISCV::X0);
8987   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8988       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8989       .addReg(RISCV::X0);
8990   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8991       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8992       .addReg(RISCV::X0);
8993 
8994   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8995       .addReg(HiReg)
8996       .addReg(ReadAgainReg)
8997       .addMBB(LoopMBB);
8998 
8999   LoopMBB->addSuccessor(LoopMBB);
9000   LoopMBB->addSuccessor(DoneMBB);
9001 
9002   MI.eraseFromParent();
9003 
9004   return DoneMBB;
9005 }
9006 
9007 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9008                                              MachineBasicBlock *BB) {
9009   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9010 
9011   MachineFunction &MF = *BB->getParent();
9012   DebugLoc DL = MI.getDebugLoc();
9013   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9014   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9015   Register LoReg = MI.getOperand(0).getReg();
9016   Register HiReg = MI.getOperand(1).getReg();
9017   Register SrcReg = MI.getOperand(2).getReg();
9018   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9019   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9020 
9021   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9022                           RI);
9023   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9024   MachineMemOperand *MMOLo =
9025       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9026   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9027       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9028   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9029       .addFrameIndex(FI)
9030       .addImm(0)
9031       .addMemOperand(MMOLo);
9032   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9033       .addFrameIndex(FI)
9034       .addImm(4)
9035       .addMemOperand(MMOHi);
9036   MI.eraseFromParent(); // The pseudo instruction is gone now.
9037   return BB;
9038 }
9039 
9040 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9041                                                  MachineBasicBlock *BB) {
9042   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9043          "Unexpected instruction");
9044 
9045   MachineFunction &MF = *BB->getParent();
9046   DebugLoc DL = MI.getDebugLoc();
9047   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9048   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9049   Register DstReg = MI.getOperand(0).getReg();
9050   Register LoReg = MI.getOperand(1).getReg();
9051   Register HiReg = MI.getOperand(2).getReg();
9052   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9053   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9054 
9055   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9056   MachineMemOperand *MMOLo =
9057       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9058   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9059       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9060   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9061       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9062       .addFrameIndex(FI)
9063       .addImm(0)
9064       .addMemOperand(MMOLo);
9065   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9066       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9067       .addFrameIndex(FI)
9068       .addImm(4)
9069       .addMemOperand(MMOHi);
9070   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9071   MI.eraseFromParent(); // The pseudo instruction is gone now.
9072   return BB;
9073 }
9074 
9075 static bool isSelectPseudo(MachineInstr &MI) {
9076   switch (MI.getOpcode()) {
9077   default:
9078     return false;
9079   case RISCV::Select_GPR_Using_CC_GPR:
9080   case RISCV::Select_FPR16_Using_CC_GPR:
9081   case RISCV::Select_FPR32_Using_CC_GPR:
9082   case RISCV::Select_FPR64_Using_CC_GPR:
9083     return true;
9084   }
9085 }
9086 
9087 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9088                                         unsigned RelOpcode, unsigned EqOpcode,
9089                                         const RISCVSubtarget &Subtarget) {
9090   DebugLoc DL = MI.getDebugLoc();
9091   Register DstReg = MI.getOperand(0).getReg();
9092   Register Src1Reg = MI.getOperand(1).getReg();
9093   Register Src2Reg = MI.getOperand(2).getReg();
9094   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9095   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9096   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9097 
9098   // Save the current FFLAGS.
9099   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9100 
9101   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9102                  .addReg(Src1Reg)
9103                  .addReg(Src2Reg);
9104   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9105     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9106 
9107   // Restore the FFLAGS.
9108   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9109       .addReg(SavedFFlags, RegState::Kill);
9110 
9111   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9112   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9113                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9114                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9115   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9116     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9117 
9118   // Erase the pseudoinstruction.
9119   MI.eraseFromParent();
9120   return BB;
9121 }
9122 
9123 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9124                                            MachineBasicBlock *BB,
9125                                            const RISCVSubtarget &Subtarget) {
9126   // To "insert" Select_* instructions, we actually have to insert the triangle
9127   // control-flow pattern.  The incoming instructions know the destination vreg
9128   // to set, the condition code register to branch on, the true/false values to
9129   // select between, and the condcode to use to select the appropriate branch.
9130   //
9131   // We produce the following control flow:
9132   //     HeadMBB
9133   //     |  \
9134   //     |  IfFalseMBB
9135   //     | /
9136   //    TailMBB
9137   //
9138   // When we find a sequence of selects we attempt to optimize their emission
9139   // by sharing the control flow. Currently we only handle cases where we have
9140   // multiple selects with the exact same condition (same LHS, RHS and CC).
9141   // The selects may be interleaved with other instructions if the other
9142   // instructions meet some requirements we deem safe:
9143   // - They are debug instructions. Otherwise,
9144   // - They do not have side-effects, do not access memory and their inputs do
9145   //   not depend on the results of the select pseudo-instructions.
9146   // The TrueV/FalseV operands of the selects cannot depend on the result of
9147   // previous selects in the sequence.
9148   // These conditions could be further relaxed. See the X86 target for a
9149   // related approach and more information.
9150   Register LHS = MI.getOperand(1).getReg();
9151   Register RHS = MI.getOperand(2).getReg();
9152   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9153 
9154   SmallVector<MachineInstr *, 4> SelectDebugValues;
9155   SmallSet<Register, 4> SelectDests;
9156   SelectDests.insert(MI.getOperand(0).getReg());
9157 
9158   MachineInstr *LastSelectPseudo = &MI;
9159 
9160   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9161        SequenceMBBI != E; ++SequenceMBBI) {
9162     if (SequenceMBBI->isDebugInstr())
9163       continue;
9164     else if (isSelectPseudo(*SequenceMBBI)) {
9165       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9166           SequenceMBBI->getOperand(2).getReg() != RHS ||
9167           SequenceMBBI->getOperand(3).getImm() != CC ||
9168           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9169           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9170         break;
9171       LastSelectPseudo = &*SequenceMBBI;
9172       SequenceMBBI->collectDebugValues(SelectDebugValues);
9173       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9174     } else {
9175       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9176           SequenceMBBI->mayLoadOrStore())
9177         break;
9178       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9179             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9180           }))
9181         break;
9182     }
9183   }
9184 
9185   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9186   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9187   DebugLoc DL = MI.getDebugLoc();
9188   MachineFunction::iterator I = ++BB->getIterator();
9189 
9190   MachineBasicBlock *HeadMBB = BB;
9191   MachineFunction *F = BB->getParent();
9192   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9193   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9194 
9195   F->insert(I, IfFalseMBB);
9196   F->insert(I, TailMBB);
9197 
9198   // Transfer debug instructions associated with the selects to TailMBB.
9199   for (MachineInstr *DebugInstr : SelectDebugValues) {
9200     TailMBB->push_back(DebugInstr->removeFromParent());
9201   }
9202 
9203   // Move all instructions after the sequence to TailMBB.
9204   TailMBB->splice(TailMBB->end(), HeadMBB,
9205                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9206   // Update machine-CFG edges by transferring all successors of the current
9207   // block to the new block which will contain the Phi nodes for the selects.
9208   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9209   // Set the successors for HeadMBB.
9210   HeadMBB->addSuccessor(IfFalseMBB);
9211   HeadMBB->addSuccessor(TailMBB);
9212 
9213   // Insert appropriate branch.
9214   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9215     .addReg(LHS)
9216     .addReg(RHS)
9217     .addMBB(TailMBB);
9218 
9219   // IfFalseMBB just falls through to TailMBB.
9220   IfFalseMBB->addSuccessor(TailMBB);
9221 
9222   // Create PHIs for all of the select pseudo-instructions.
9223   auto SelectMBBI = MI.getIterator();
9224   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9225   auto InsertionPoint = TailMBB->begin();
9226   while (SelectMBBI != SelectEnd) {
9227     auto Next = std::next(SelectMBBI);
9228     if (isSelectPseudo(*SelectMBBI)) {
9229       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9230       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9231               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9232           .addReg(SelectMBBI->getOperand(4).getReg())
9233           .addMBB(HeadMBB)
9234           .addReg(SelectMBBI->getOperand(5).getReg())
9235           .addMBB(IfFalseMBB);
9236       SelectMBBI->eraseFromParent();
9237     }
9238     SelectMBBI = Next;
9239   }
9240 
9241   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9242   return TailMBB;
9243 }
9244 
9245 MachineBasicBlock *
9246 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9247                                                  MachineBasicBlock *BB) const {
9248   switch (MI.getOpcode()) {
9249   default:
9250     llvm_unreachable("Unexpected instr type to insert");
9251   case RISCV::ReadCycleWide:
9252     assert(!Subtarget.is64Bit() &&
9253            "ReadCycleWrite is only to be used on riscv32");
9254     return emitReadCycleWidePseudo(MI, BB);
9255   case RISCV::Select_GPR_Using_CC_GPR:
9256   case RISCV::Select_FPR16_Using_CC_GPR:
9257   case RISCV::Select_FPR32_Using_CC_GPR:
9258   case RISCV::Select_FPR64_Using_CC_GPR:
9259     return emitSelectPseudo(MI, BB, Subtarget);
9260   case RISCV::BuildPairF64Pseudo:
9261     return emitBuildPairF64Pseudo(MI, BB);
9262   case RISCV::SplitF64Pseudo:
9263     return emitSplitF64Pseudo(MI, BB);
9264   case RISCV::PseudoQuietFLE_H:
9265     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9266   case RISCV::PseudoQuietFLT_H:
9267     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9268   case RISCV::PseudoQuietFLE_S:
9269     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9270   case RISCV::PseudoQuietFLT_S:
9271     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9272   case RISCV::PseudoQuietFLE_D:
9273     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9274   case RISCV::PseudoQuietFLT_D:
9275     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9276   }
9277 }
9278 
9279 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9280                                                         SDNode *Node) const {
9281   // Add FRM dependency to any instructions with dynamic rounding mode.
9282   unsigned Opc = MI.getOpcode();
9283   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9284   if (Idx < 0)
9285     return;
9286   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9287     return;
9288   // If the instruction already reads FRM, don't add another read.
9289   if (MI.readsRegister(RISCV::FRM))
9290     return;
9291   MI.addOperand(
9292       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9293 }
9294 
9295 // Calling Convention Implementation.
9296 // The expectations for frontend ABI lowering vary from target to target.
9297 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9298 // details, but this is a longer term goal. For now, we simply try to keep the
9299 // role of the frontend as simple and well-defined as possible. The rules can
9300 // be summarised as:
9301 // * Never split up large scalar arguments. We handle them here.
9302 // * If a hardfloat calling convention is being used, and the struct may be
9303 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9304 // available, then pass as two separate arguments. If either the GPRs or FPRs
9305 // are exhausted, then pass according to the rule below.
9306 // * If a struct could never be passed in registers or directly in a stack
9307 // slot (as it is larger than 2*XLEN and the floating point rules don't
9308 // apply), then pass it using a pointer with the byval attribute.
9309 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9310 // word-sized array or a 2*XLEN scalar (depending on alignment).
9311 // * The frontend can determine whether a struct is returned by reference or
9312 // not based on its size and fields. If it will be returned by reference, the
9313 // frontend must modify the prototype so a pointer with the sret annotation is
9314 // passed as the first argument. This is not necessary for large scalar
9315 // returns.
9316 // * Struct return values and varargs should be coerced to structs containing
9317 // register-size fields in the same situations they would be for fixed
9318 // arguments.
9319 
9320 static const MCPhysReg ArgGPRs[] = {
9321   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9322   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9323 };
9324 static const MCPhysReg ArgFPR16s[] = {
9325   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9326   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9327 };
9328 static const MCPhysReg ArgFPR32s[] = {
9329   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9330   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9331 };
9332 static const MCPhysReg ArgFPR64s[] = {
9333   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9334   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9335 };
9336 // This is an interim calling convention and it may be changed in the future.
9337 static const MCPhysReg ArgVRs[] = {
9338     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9339     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9340     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9341 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9342                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9343                                      RISCV::V20M2, RISCV::V22M2};
9344 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9345                                      RISCV::V20M4};
9346 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9347 
9348 // Pass a 2*XLEN argument that has been split into two XLEN values through
9349 // registers or the stack as necessary.
9350 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9351                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9352                                 MVT ValVT2, MVT LocVT2,
9353                                 ISD::ArgFlagsTy ArgFlags2) {
9354   unsigned XLenInBytes = XLen / 8;
9355   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9356     // At least one half can be passed via register.
9357     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9358                                      VA1.getLocVT(), CCValAssign::Full));
9359   } else {
9360     // Both halves must be passed on the stack, with proper alignment.
9361     Align StackAlign =
9362         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9363     State.addLoc(
9364         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9365                             State.AllocateStack(XLenInBytes, StackAlign),
9366                             VA1.getLocVT(), CCValAssign::Full));
9367     State.addLoc(CCValAssign::getMem(
9368         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9369         LocVT2, CCValAssign::Full));
9370     return false;
9371   }
9372 
9373   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9374     // The second half can also be passed via register.
9375     State.addLoc(
9376         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9377   } else {
9378     // The second half is passed via the stack, without additional alignment.
9379     State.addLoc(CCValAssign::getMem(
9380         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9381         LocVT2, CCValAssign::Full));
9382   }
9383 
9384   return false;
9385 }
9386 
9387 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9388                                Optional<unsigned> FirstMaskArgument,
9389                                CCState &State, const RISCVTargetLowering &TLI) {
9390   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9391   if (RC == &RISCV::VRRegClass) {
9392     // Assign the first mask argument to V0.
9393     // This is an interim calling convention and it may be changed in the
9394     // future.
9395     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9396       return State.AllocateReg(RISCV::V0);
9397     return State.AllocateReg(ArgVRs);
9398   }
9399   if (RC == &RISCV::VRM2RegClass)
9400     return State.AllocateReg(ArgVRM2s);
9401   if (RC == &RISCV::VRM4RegClass)
9402     return State.AllocateReg(ArgVRM4s);
9403   if (RC == &RISCV::VRM8RegClass)
9404     return State.AllocateReg(ArgVRM8s);
9405   llvm_unreachable("Unhandled register class for ValueType");
9406 }
9407 
9408 // Implements the RISC-V calling convention. Returns true upon failure.
9409 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9410                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9411                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9412                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9413                      Optional<unsigned> FirstMaskArgument) {
9414   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9415   assert(XLen == 32 || XLen == 64);
9416   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9417 
9418   // Any return value split in to more than two values can't be returned
9419   // directly. Vectors are returned via the available vector registers.
9420   if (!LocVT.isVector() && IsRet && ValNo > 1)
9421     return true;
9422 
9423   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9424   // variadic argument, or if no F16/F32 argument registers are available.
9425   bool UseGPRForF16_F32 = true;
9426   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9427   // variadic argument, or if no F64 argument registers are available.
9428   bool UseGPRForF64 = true;
9429 
9430   switch (ABI) {
9431   default:
9432     llvm_unreachable("Unexpected ABI");
9433   case RISCVABI::ABI_ILP32:
9434   case RISCVABI::ABI_LP64:
9435     break;
9436   case RISCVABI::ABI_ILP32F:
9437   case RISCVABI::ABI_LP64F:
9438     UseGPRForF16_F32 = !IsFixed;
9439     break;
9440   case RISCVABI::ABI_ILP32D:
9441   case RISCVABI::ABI_LP64D:
9442     UseGPRForF16_F32 = !IsFixed;
9443     UseGPRForF64 = !IsFixed;
9444     break;
9445   }
9446 
9447   // FPR16, FPR32, and FPR64 alias each other.
9448   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9449     UseGPRForF16_F32 = true;
9450     UseGPRForF64 = true;
9451   }
9452 
9453   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9454   // similar local variables rather than directly checking against the target
9455   // ABI.
9456 
9457   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9458     LocVT = XLenVT;
9459     LocInfo = CCValAssign::BCvt;
9460   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9461     LocVT = MVT::i64;
9462     LocInfo = CCValAssign::BCvt;
9463   }
9464 
9465   // If this is a variadic argument, the RISC-V calling convention requires
9466   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9467   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9468   // be used regardless of whether the original argument was split during
9469   // legalisation or not. The argument will not be passed by registers if the
9470   // original type is larger than 2*XLEN, so the register alignment rule does
9471   // not apply.
9472   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9473   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9474       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9475     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9476     // Skip 'odd' register if necessary.
9477     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9478       State.AllocateReg(ArgGPRs);
9479   }
9480 
9481   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9482   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9483       State.getPendingArgFlags();
9484 
9485   assert(PendingLocs.size() == PendingArgFlags.size() &&
9486          "PendingLocs and PendingArgFlags out of sync");
9487 
9488   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9489   // registers are exhausted.
9490   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9491     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9492            "Can't lower f64 if it is split");
9493     // Depending on available argument GPRS, f64 may be passed in a pair of
9494     // GPRs, split between a GPR and the stack, or passed completely on the
9495     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9496     // cases.
9497     Register Reg = State.AllocateReg(ArgGPRs);
9498     LocVT = MVT::i32;
9499     if (!Reg) {
9500       unsigned StackOffset = State.AllocateStack(8, Align(8));
9501       State.addLoc(
9502           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9503       return false;
9504     }
9505     if (!State.AllocateReg(ArgGPRs))
9506       State.AllocateStack(4, Align(4));
9507     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9508     return false;
9509   }
9510 
9511   // Fixed-length vectors are located in the corresponding scalable-vector
9512   // container types.
9513   if (ValVT.isFixedLengthVector())
9514     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9515 
9516   // Split arguments might be passed indirectly, so keep track of the pending
9517   // values. Split vectors are passed via a mix of registers and indirectly, so
9518   // treat them as we would any other argument.
9519   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9520     LocVT = XLenVT;
9521     LocInfo = CCValAssign::Indirect;
9522     PendingLocs.push_back(
9523         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9524     PendingArgFlags.push_back(ArgFlags);
9525     if (!ArgFlags.isSplitEnd()) {
9526       return false;
9527     }
9528   }
9529 
9530   // If the split argument only had two elements, it should be passed directly
9531   // in registers or on the stack.
9532   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9533       PendingLocs.size() <= 2) {
9534     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9535     // Apply the normal calling convention rules to the first half of the
9536     // split argument.
9537     CCValAssign VA = PendingLocs[0];
9538     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9539     PendingLocs.clear();
9540     PendingArgFlags.clear();
9541     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9542                                ArgFlags);
9543   }
9544 
9545   // Allocate to a register if possible, or else a stack slot.
9546   Register Reg;
9547   unsigned StoreSizeBytes = XLen / 8;
9548   Align StackAlign = Align(XLen / 8);
9549 
9550   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9551     Reg = State.AllocateReg(ArgFPR16s);
9552   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9553     Reg = State.AllocateReg(ArgFPR32s);
9554   else if (ValVT == MVT::f64 && !UseGPRForF64)
9555     Reg = State.AllocateReg(ArgFPR64s);
9556   else if (ValVT.isVector()) {
9557     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9558     if (!Reg) {
9559       // For return values, the vector must be passed fully via registers or
9560       // via the stack.
9561       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9562       // but we're using all of them.
9563       if (IsRet)
9564         return true;
9565       // Try using a GPR to pass the address
9566       if ((Reg = State.AllocateReg(ArgGPRs))) {
9567         LocVT = XLenVT;
9568         LocInfo = CCValAssign::Indirect;
9569       } else if (ValVT.isScalableVector()) {
9570         LocVT = XLenVT;
9571         LocInfo = CCValAssign::Indirect;
9572       } else {
9573         // Pass fixed-length vectors on the stack.
9574         LocVT = ValVT;
9575         StoreSizeBytes = ValVT.getStoreSize();
9576         // Align vectors to their element sizes, being careful for vXi1
9577         // vectors.
9578         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9579       }
9580     }
9581   } else {
9582     Reg = State.AllocateReg(ArgGPRs);
9583   }
9584 
9585   unsigned StackOffset =
9586       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9587 
9588   // If we reach this point and PendingLocs is non-empty, we must be at the
9589   // end of a split argument that must be passed indirectly.
9590   if (!PendingLocs.empty()) {
9591     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9592     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9593 
9594     for (auto &It : PendingLocs) {
9595       if (Reg)
9596         It.convertToReg(Reg);
9597       else
9598         It.convertToMem(StackOffset);
9599       State.addLoc(It);
9600     }
9601     PendingLocs.clear();
9602     PendingArgFlags.clear();
9603     return false;
9604   }
9605 
9606   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9607           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9608          "Expected an XLenVT or vector types at this stage");
9609 
9610   if (Reg) {
9611     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9612     return false;
9613   }
9614 
9615   // When a floating-point value is passed on the stack, no bit-conversion is
9616   // needed.
9617   if (ValVT.isFloatingPoint()) {
9618     LocVT = ValVT;
9619     LocInfo = CCValAssign::Full;
9620   }
9621   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9622   return false;
9623 }
9624 
9625 template <typename ArgTy>
9626 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9627   for (const auto &ArgIdx : enumerate(Args)) {
9628     MVT ArgVT = ArgIdx.value().VT;
9629     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9630       return ArgIdx.index();
9631   }
9632   return None;
9633 }
9634 
9635 void RISCVTargetLowering::analyzeInputArgs(
9636     MachineFunction &MF, CCState &CCInfo,
9637     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9638     RISCVCCAssignFn Fn) const {
9639   unsigned NumArgs = Ins.size();
9640   FunctionType *FType = MF.getFunction().getFunctionType();
9641 
9642   Optional<unsigned> FirstMaskArgument;
9643   if (Subtarget.hasVInstructions())
9644     FirstMaskArgument = preAssignMask(Ins);
9645 
9646   for (unsigned i = 0; i != NumArgs; ++i) {
9647     MVT ArgVT = Ins[i].VT;
9648     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9649 
9650     Type *ArgTy = nullptr;
9651     if (IsRet)
9652       ArgTy = FType->getReturnType();
9653     else if (Ins[i].isOrigArg())
9654       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9655 
9656     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9657     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9658            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9659            FirstMaskArgument)) {
9660       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9661                         << EVT(ArgVT).getEVTString() << '\n');
9662       llvm_unreachable(nullptr);
9663     }
9664   }
9665 }
9666 
9667 void RISCVTargetLowering::analyzeOutputArgs(
9668     MachineFunction &MF, CCState &CCInfo,
9669     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9670     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9671   unsigned NumArgs = Outs.size();
9672 
9673   Optional<unsigned> FirstMaskArgument;
9674   if (Subtarget.hasVInstructions())
9675     FirstMaskArgument = preAssignMask(Outs);
9676 
9677   for (unsigned i = 0; i != NumArgs; i++) {
9678     MVT ArgVT = Outs[i].VT;
9679     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9680     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9681 
9682     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9683     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9684            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9685            FirstMaskArgument)) {
9686       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9687                         << EVT(ArgVT).getEVTString() << "\n");
9688       llvm_unreachable(nullptr);
9689     }
9690   }
9691 }
9692 
9693 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9694 // values.
9695 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9696                                    const CCValAssign &VA, const SDLoc &DL,
9697                                    const RISCVSubtarget &Subtarget) {
9698   switch (VA.getLocInfo()) {
9699   default:
9700     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9701   case CCValAssign::Full:
9702     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9703       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9704     break;
9705   case CCValAssign::BCvt:
9706     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9707       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9708     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9709       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9710     else
9711       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9712     break;
9713   }
9714   return Val;
9715 }
9716 
9717 // The caller is responsible for loading the full value if the argument is
9718 // passed with CCValAssign::Indirect.
9719 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9720                                 const CCValAssign &VA, const SDLoc &DL,
9721                                 const RISCVTargetLowering &TLI) {
9722   MachineFunction &MF = DAG.getMachineFunction();
9723   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9724   EVT LocVT = VA.getLocVT();
9725   SDValue Val;
9726   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9727   Register VReg = RegInfo.createVirtualRegister(RC);
9728   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9729   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9730 
9731   if (VA.getLocInfo() == CCValAssign::Indirect)
9732     return Val;
9733 
9734   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9735 }
9736 
9737 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9738                                    const CCValAssign &VA, const SDLoc &DL,
9739                                    const RISCVSubtarget &Subtarget) {
9740   EVT LocVT = VA.getLocVT();
9741 
9742   switch (VA.getLocInfo()) {
9743   default:
9744     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9745   case CCValAssign::Full:
9746     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9747       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9748     break;
9749   case CCValAssign::BCvt:
9750     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9751       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9752     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9753       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9754     else
9755       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9756     break;
9757   }
9758   return Val;
9759 }
9760 
9761 // The caller is responsible for loading the full value if the argument is
9762 // passed with CCValAssign::Indirect.
9763 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9764                                 const CCValAssign &VA, const SDLoc &DL) {
9765   MachineFunction &MF = DAG.getMachineFunction();
9766   MachineFrameInfo &MFI = MF.getFrameInfo();
9767   EVT LocVT = VA.getLocVT();
9768   EVT ValVT = VA.getValVT();
9769   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9770   if (ValVT.isScalableVector()) {
9771     // When the value is a scalable vector, we save the pointer which points to
9772     // the scalable vector value in the stack. The ValVT will be the pointer
9773     // type, instead of the scalable vector type.
9774     ValVT = LocVT;
9775   }
9776   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9777                                  /*IsImmutable=*/true);
9778   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9779   SDValue Val;
9780 
9781   ISD::LoadExtType ExtType;
9782   switch (VA.getLocInfo()) {
9783   default:
9784     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9785   case CCValAssign::Full:
9786   case CCValAssign::Indirect:
9787   case CCValAssign::BCvt:
9788     ExtType = ISD::NON_EXTLOAD;
9789     break;
9790   }
9791   Val = DAG.getExtLoad(
9792       ExtType, DL, LocVT, Chain, FIN,
9793       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9794   return Val;
9795 }
9796 
9797 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9798                                        const CCValAssign &VA, const SDLoc &DL) {
9799   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9800          "Unexpected VA");
9801   MachineFunction &MF = DAG.getMachineFunction();
9802   MachineFrameInfo &MFI = MF.getFrameInfo();
9803   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9804 
9805   if (VA.isMemLoc()) {
9806     // f64 is passed on the stack.
9807     int FI =
9808         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9809     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9810     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9811                        MachinePointerInfo::getFixedStack(MF, FI));
9812   }
9813 
9814   assert(VA.isRegLoc() && "Expected register VA assignment");
9815 
9816   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9817   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9818   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9819   SDValue Hi;
9820   if (VA.getLocReg() == RISCV::X17) {
9821     // Second half of f64 is passed on the stack.
9822     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9823     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9824     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9825                      MachinePointerInfo::getFixedStack(MF, FI));
9826   } else {
9827     // Second half of f64 is passed in another GPR.
9828     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9829     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9830     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9831   }
9832   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9833 }
9834 
9835 // FastCC has less than 1% performance improvement for some particular
9836 // benchmark. But theoretically, it may has benenfit for some cases.
9837 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9838                             unsigned ValNo, MVT ValVT, MVT LocVT,
9839                             CCValAssign::LocInfo LocInfo,
9840                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9841                             bool IsFixed, bool IsRet, Type *OrigTy,
9842                             const RISCVTargetLowering &TLI,
9843                             Optional<unsigned> FirstMaskArgument) {
9844 
9845   // X5 and X6 might be used for save-restore libcall.
9846   static const MCPhysReg GPRList[] = {
9847       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9848       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9849       RISCV::X29, RISCV::X30, RISCV::X31};
9850 
9851   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9852     if (unsigned Reg = State.AllocateReg(GPRList)) {
9853       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9854       return false;
9855     }
9856   }
9857 
9858   if (LocVT == MVT::f16) {
9859     static const MCPhysReg FPR16List[] = {
9860         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9861         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9862         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9863         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9864     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9865       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9866       return false;
9867     }
9868   }
9869 
9870   if (LocVT == MVT::f32) {
9871     static const MCPhysReg FPR32List[] = {
9872         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9873         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9874         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9875         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9876     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9877       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9878       return false;
9879     }
9880   }
9881 
9882   if (LocVT == MVT::f64) {
9883     static const MCPhysReg FPR64List[] = {
9884         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9885         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9886         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9887         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9888     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9889       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9890       return false;
9891     }
9892   }
9893 
9894   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9895     unsigned Offset4 = State.AllocateStack(4, Align(4));
9896     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9897     return false;
9898   }
9899 
9900   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9901     unsigned Offset5 = State.AllocateStack(8, Align(8));
9902     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9903     return false;
9904   }
9905 
9906   if (LocVT.isVector()) {
9907     if (unsigned Reg =
9908             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9909       // Fixed-length vectors are located in the corresponding scalable-vector
9910       // container types.
9911       if (ValVT.isFixedLengthVector())
9912         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9913       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9914     } else {
9915       // Try and pass the address via a "fast" GPR.
9916       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9917         LocInfo = CCValAssign::Indirect;
9918         LocVT = TLI.getSubtarget().getXLenVT();
9919         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9920       } else if (ValVT.isFixedLengthVector()) {
9921         auto StackAlign =
9922             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9923         unsigned StackOffset =
9924             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9925         State.addLoc(
9926             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9927       } else {
9928         // Can't pass scalable vectors on the stack.
9929         return true;
9930       }
9931     }
9932 
9933     return false;
9934   }
9935 
9936   return true; // CC didn't match.
9937 }
9938 
9939 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9940                          CCValAssign::LocInfo LocInfo,
9941                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9942 
9943   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9944     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9945     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9946     static const MCPhysReg GPRList[] = {
9947         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9948         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9949     if (unsigned Reg = State.AllocateReg(GPRList)) {
9950       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9951       return false;
9952     }
9953   }
9954 
9955   if (LocVT == MVT::f32) {
9956     // Pass in STG registers: F1, ..., F6
9957     //                        fs0 ... fs5
9958     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9959                                           RISCV::F18_F, RISCV::F19_F,
9960                                           RISCV::F20_F, RISCV::F21_F};
9961     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9962       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9963       return false;
9964     }
9965   }
9966 
9967   if (LocVT == MVT::f64) {
9968     // Pass in STG registers: D1, ..., D6
9969     //                        fs6 ... fs11
9970     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9971                                           RISCV::F24_D, RISCV::F25_D,
9972                                           RISCV::F26_D, RISCV::F27_D};
9973     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9974       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9975       return false;
9976     }
9977   }
9978 
9979   report_fatal_error("No registers left in GHC calling convention");
9980   return true;
9981 }
9982 
9983 // Transform physical registers into virtual registers.
9984 SDValue RISCVTargetLowering::LowerFormalArguments(
9985     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9986     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9987     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9988 
9989   MachineFunction &MF = DAG.getMachineFunction();
9990 
9991   switch (CallConv) {
9992   default:
9993     report_fatal_error("Unsupported calling convention");
9994   case CallingConv::C:
9995   case CallingConv::Fast:
9996     break;
9997   case CallingConv::GHC:
9998     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9999         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10000       report_fatal_error(
10001         "GHC calling convention requires the F and D instruction set extensions");
10002   }
10003 
10004   const Function &Func = MF.getFunction();
10005   if (Func.hasFnAttribute("interrupt")) {
10006     if (!Func.arg_empty())
10007       report_fatal_error(
10008         "Functions with the interrupt attribute cannot have arguments!");
10009 
10010     StringRef Kind =
10011       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10012 
10013     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10014       report_fatal_error(
10015         "Function interrupt attribute argument not supported!");
10016   }
10017 
10018   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10019   MVT XLenVT = Subtarget.getXLenVT();
10020   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10021   // Used with vargs to acumulate store chains.
10022   std::vector<SDValue> OutChains;
10023 
10024   // Assign locations to all of the incoming arguments.
10025   SmallVector<CCValAssign, 16> ArgLocs;
10026   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10027 
10028   if (CallConv == CallingConv::GHC)
10029     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10030   else
10031     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10032                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10033                                                    : CC_RISCV);
10034 
10035   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10036     CCValAssign &VA = ArgLocs[i];
10037     SDValue ArgValue;
10038     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10039     // case.
10040     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10041       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10042     else if (VA.isRegLoc())
10043       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10044     else
10045       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10046 
10047     if (VA.getLocInfo() == CCValAssign::Indirect) {
10048       // If the original argument was split and passed by reference (e.g. i128
10049       // on RV32), we need to load all parts of it here (using the same
10050       // address). Vectors may be partly split to registers and partly to the
10051       // stack, in which case the base address is partly offset and subsequent
10052       // stores are relative to that.
10053       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10054                                    MachinePointerInfo()));
10055       unsigned ArgIndex = Ins[i].OrigArgIndex;
10056       unsigned ArgPartOffset = Ins[i].PartOffset;
10057       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10058       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10059         CCValAssign &PartVA = ArgLocs[i + 1];
10060         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10061         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10062         if (PartVA.getValVT().isScalableVector())
10063           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10064         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10065         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10066                                      MachinePointerInfo()));
10067         ++i;
10068       }
10069       continue;
10070     }
10071     InVals.push_back(ArgValue);
10072   }
10073 
10074   if (IsVarArg) {
10075     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10076     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10077     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10078     MachineFrameInfo &MFI = MF.getFrameInfo();
10079     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10080     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10081 
10082     // Offset of the first variable argument from stack pointer, and size of
10083     // the vararg save area. For now, the varargs save area is either zero or
10084     // large enough to hold a0-a7.
10085     int VaArgOffset, VarArgsSaveSize;
10086 
10087     // If all registers are allocated, then all varargs must be passed on the
10088     // stack and we don't need to save any argregs.
10089     if (ArgRegs.size() == Idx) {
10090       VaArgOffset = CCInfo.getNextStackOffset();
10091       VarArgsSaveSize = 0;
10092     } else {
10093       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10094       VaArgOffset = -VarArgsSaveSize;
10095     }
10096 
10097     // Record the frame index of the first variable argument
10098     // which is a value necessary to VASTART.
10099     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10100     RVFI->setVarArgsFrameIndex(FI);
10101 
10102     // If saving an odd number of registers then create an extra stack slot to
10103     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10104     // offsets to even-numbered registered remain 2*XLEN-aligned.
10105     if (Idx % 2) {
10106       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10107       VarArgsSaveSize += XLenInBytes;
10108     }
10109 
10110     // Copy the integer registers that may have been used for passing varargs
10111     // to the vararg save area.
10112     for (unsigned I = Idx; I < ArgRegs.size();
10113          ++I, VaArgOffset += XLenInBytes) {
10114       const Register Reg = RegInfo.createVirtualRegister(RC);
10115       RegInfo.addLiveIn(ArgRegs[I], Reg);
10116       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10117       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10118       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10119       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10120                                    MachinePointerInfo::getFixedStack(MF, FI));
10121       cast<StoreSDNode>(Store.getNode())
10122           ->getMemOperand()
10123           ->setValue((Value *)nullptr);
10124       OutChains.push_back(Store);
10125     }
10126     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10127   }
10128 
10129   // All stores are grouped in one node to allow the matching between
10130   // the size of Ins and InVals. This only happens for vararg functions.
10131   if (!OutChains.empty()) {
10132     OutChains.push_back(Chain);
10133     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10134   }
10135 
10136   return Chain;
10137 }
10138 
10139 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10140 /// for tail call optimization.
10141 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10142 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10143     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10144     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10145 
10146   auto &Callee = CLI.Callee;
10147   auto CalleeCC = CLI.CallConv;
10148   auto &Outs = CLI.Outs;
10149   auto &Caller = MF.getFunction();
10150   auto CallerCC = Caller.getCallingConv();
10151 
10152   // Exception-handling functions need a special set of instructions to
10153   // indicate a return to the hardware. Tail-calling another function would
10154   // probably break this.
10155   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10156   // should be expanded as new function attributes are introduced.
10157   if (Caller.hasFnAttribute("interrupt"))
10158     return false;
10159 
10160   // Do not tail call opt if the stack is used to pass parameters.
10161   if (CCInfo.getNextStackOffset() != 0)
10162     return false;
10163 
10164   // Do not tail call opt if any parameters need to be passed indirectly.
10165   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10166   // passed indirectly. So the address of the value will be passed in a
10167   // register, or if not available, then the address is put on the stack. In
10168   // order to pass indirectly, space on the stack often needs to be allocated
10169   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10170   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10171   // are passed CCValAssign::Indirect.
10172   for (auto &VA : ArgLocs)
10173     if (VA.getLocInfo() == CCValAssign::Indirect)
10174       return false;
10175 
10176   // Do not tail call opt if either caller or callee uses struct return
10177   // semantics.
10178   auto IsCallerStructRet = Caller.hasStructRetAttr();
10179   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10180   if (IsCallerStructRet || IsCalleeStructRet)
10181     return false;
10182 
10183   // Externally-defined functions with weak linkage should not be
10184   // tail-called. The behaviour of branch instructions in this situation (as
10185   // used for tail calls) is implementation-defined, so we cannot rely on the
10186   // linker replacing the tail call with a return.
10187   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10188     const GlobalValue *GV = G->getGlobal();
10189     if (GV->hasExternalWeakLinkage())
10190       return false;
10191   }
10192 
10193   // The callee has to preserve all registers the caller needs to preserve.
10194   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10195   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10196   if (CalleeCC != CallerCC) {
10197     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10198     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10199       return false;
10200   }
10201 
10202   // Byval parameters hand the function a pointer directly into the stack area
10203   // we want to reuse during a tail call. Working around this *is* possible
10204   // but less efficient and uglier in LowerCall.
10205   for (auto &Arg : Outs)
10206     if (Arg.Flags.isByVal())
10207       return false;
10208 
10209   return true;
10210 }
10211 
10212 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10213   return DAG.getDataLayout().getPrefTypeAlign(
10214       VT.getTypeForEVT(*DAG.getContext()));
10215 }
10216 
10217 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10218 // and output parameter nodes.
10219 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10220                                        SmallVectorImpl<SDValue> &InVals) const {
10221   SelectionDAG &DAG = CLI.DAG;
10222   SDLoc &DL = CLI.DL;
10223   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10224   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10225   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10226   SDValue Chain = CLI.Chain;
10227   SDValue Callee = CLI.Callee;
10228   bool &IsTailCall = CLI.IsTailCall;
10229   CallingConv::ID CallConv = CLI.CallConv;
10230   bool IsVarArg = CLI.IsVarArg;
10231   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10232   MVT XLenVT = Subtarget.getXLenVT();
10233 
10234   MachineFunction &MF = DAG.getMachineFunction();
10235 
10236   // Analyze the operands of the call, assigning locations to each operand.
10237   SmallVector<CCValAssign, 16> ArgLocs;
10238   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10239 
10240   if (CallConv == CallingConv::GHC)
10241     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10242   else
10243     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10244                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10245                                                     : CC_RISCV);
10246 
10247   // Check if it's really possible to do a tail call.
10248   if (IsTailCall)
10249     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10250 
10251   if (IsTailCall)
10252     ++NumTailCalls;
10253   else if (CLI.CB && CLI.CB->isMustTailCall())
10254     report_fatal_error("failed to perform tail call elimination on a call "
10255                        "site marked musttail");
10256 
10257   // Get a count of how many bytes are to be pushed on the stack.
10258   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10259 
10260   // Create local copies for byval args
10261   SmallVector<SDValue, 8> ByValArgs;
10262   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10263     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10264     if (!Flags.isByVal())
10265       continue;
10266 
10267     SDValue Arg = OutVals[i];
10268     unsigned Size = Flags.getByValSize();
10269     Align Alignment = Flags.getNonZeroByValAlign();
10270 
10271     int FI =
10272         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10273     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10274     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10275 
10276     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10277                           /*IsVolatile=*/false,
10278                           /*AlwaysInline=*/false, IsTailCall,
10279                           MachinePointerInfo(), MachinePointerInfo());
10280     ByValArgs.push_back(FIPtr);
10281   }
10282 
10283   if (!IsTailCall)
10284     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10285 
10286   // Copy argument values to their designated locations.
10287   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10288   SmallVector<SDValue, 8> MemOpChains;
10289   SDValue StackPtr;
10290   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10291     CCValAssign &VA = ArgLocs[i];
10292     SDValue ArgValue = OutVals[i];
10293     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10294 
10295     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10296     bool IsF64OnRV32DSoftABI =
10297         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10298     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10299       SDValue SplitF64 = DAG.getNode(
10300           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10301       SDValue Lo = SplitF64.getValue(0);
10302       SDValue Hi = SplitF64.getValue(1);
10303 
10304       Register RegLo = VA.getLocReg();
10305       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10306 
10307       if (RegLo == RISCV::X17) {
10308         // Second half of f64 is passed on the stack.
10309         // Work out the address of the stack slot.
10310         if (!StackPtr.getNode())
10311           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10312         // Emit the store.
10313         MemOpChains.push_back(
10314             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10315       } else {
10316         // Second half of f64 is passed in another GPR.
10317         assert(RegLo < RISCV::X31 && "Invalid register pair");
10318         Register RegHigh = RegLo + 1;
10319         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10320       }
10321       continue;
10322     }
10323 
10324     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10325     // as any other MemLoc.
10326 
10327     // Promote the value if needed.
10328     // For now, only handle fully promoted and indirect arguments.
10329     if (VA.getLocInfo() == CCValAssign::Indirect) {
10330       // Store the argument in a stack slot and pass its address.
10331       Align StackAlign =
10332           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10333                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10334       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10335       // If the original argument was split (e.g. i128), we need
10336       // to store the required parts of it here (and pass just one address).
10337       // Vectors may be partly split to registers and partly to the stack, in
10338       // which case the base address is partly offset and subsequent stores are
10339       // relative to that.
10340       unsigned ArgIndex = Outs[i].OrigArgIndex;
10341       unsigned ArgPartOffset = Outs[i].PartOffset;
10342       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10343       // Calculate the total size to store. We don't have access to what we're
10344       // actually storing other than performing the loop and collecting the
10345       // info.
10346       SmallVector<std::pair<SDValue, SDValue>> Parts;
10347       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10348         SDValue PartValue = OutVals[i + 1];
10349         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10350         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10351         EVT PartVT = PartValue.getValueType();
10352         if (PartVT.isScalableVector())
10353           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10354         StoredSize += PartVT.getStoreSize();
10355         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10356         Parts.push_back(std::make_pair(PartValue, Offset));
10357         ++i;
10358       }
10359       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10360       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10361       MemOpChains.push_back(
10362           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10363                        MachinePointerInfo::getFixedStack(MF, FI)));
10364       for (const auto &Part : Parts) {
10365         SDValue PartValue = Part.first;
10366         SDValue PartOffset = Part.second;
10367         SDValue Address =
10368             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10369         MemOpChains.push_back(
10370             DAG.getStore(Chain, DL, PartValue, Address,
10371                          MachinePointerInfo::getFixedStack(MF, FI)));
10372       }
10373       ArgValue = SpillSlot;
10374     } else {
10375       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10376     }
10377 
10378     // Use local copy if it is a byval arg.
10379     if (Flags.isByVal())
10380       ArgValue = ByValArgs[j++];
10381 
10382     if (VA.isRegLoc()) {
10383       // Queue up the argument copies and emit them at the end.
10384       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10385     } else {
10386       assert(VA.isMemLoc() && "Argument not register or memory");
10387       assert(!IsTailCall && "Tail call not allowed if stack is used "
10388                             "for passing parameters");
10389 
10390       // Work out the address of the stack slot.
10391       if (!StackPtr.getNode())
10392         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10393       SDValue Address =
10394           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10395                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10396 
10397       // Emit the store.
10398       MemOpChains.push_back(
10399           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10400     }
10401   }
10402 
10403   // Join the stores, which are independent of one another.
10404   if (!MemOpChains.empty())
10405     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10406 
10407   SDValue Glue;
10408 
10409   // Build a sequence of copy-to-reg nodes, chained and glued together.
10410   for (auto &Reg : RegsToPass) {
10411     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10412     Glue = Chain.getValue(1);
10413   }
10414 
10415   // Validate that none of the argument registers have been marked as
10416   // reserved, if so report an error. Do the same for the return address if this
10417   // is not a tailcall.
10418   validateCCReservedRegs(RegsToPass, MF);
10419   if (!IsTailCall &&
10420       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10421     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10422         MF.getFunction(),
10423         "Return address register required, but has been reserved."});
10424 
10425   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10426   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10427   // split it and then direct call can be matched by PseudoCALL.
10428   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10429     const GlobalValue *GV = S->getGlobal();
10430 
10431     unsigned OpFlags = RISCVII::MO_CALL;
10432     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10433       OpFlags = RISCVII::MO_PLT;
10434 
10435     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10436   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10437     unsigned OpFlags = RISCVII::MO_CALL;
10438 
10439     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10440                                                  nullptr))
10441       OpFlags = RISCVII::MO_PLT;
10442 
10443     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10444   }
10445 
10446   // The first call operand is the chain and the second is the target address.
10447   SmallVector<SDValue, 8> Ops;
10448   Ops.push_back(Chain);
10449   Ops.push_back(Callee);
10450 
10451   // Add argument registers to the end of the list so that they are
10452   // known live into the call.
10453   for (auto &Reg : RegsToPass)
10454     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10455 
10456   if (!IsTailCall) {
10457     // Add a register mask operand representing the call-preserved registers.
10458     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10459     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10460     assert(Mask && "Missing call preserved mask for calling convention");
10461     Ops.push_back(DAG.getRegisterMask(Mask));
10462   }
10463 
10464   // Glue the call to the argument copies, if any.
10465   if (Glue.getNode())
10466     Ops.push_back(Glue);
10467 
10468   // Emit the call.
10469   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10470 
10471   if (IsTailCall) {
10472     MF.getFrameInfo().setHasTailCall();
10473     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10474   }
10475 
10476   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10477   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10478   Glue = Chain.getValue(1);
10479 
10480   // Mark the end of the call, which is glued to the call itself.
10481   Chain = DAG.getCALLSEQ_END(Chain,
10482                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10483                              DAG.getConstant(0, DL, PtrVT, true),
10484                              Glue, DL);
10485   Glue = Chain.getValue(1);
10486 
10487   // Assign locations to each value returned by this call.
10488   SmallVector<CCValAssign, 16> RVLocs;
10489   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10490   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10491 
10492   // Copy all of the result registers out of their specified physreg.
10493   for (auto &VA : RVLocs) {
10494     // Copy the value out
10495     SDValue RetValue =
10496         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10497     // Glue the RetValue to the end of the call sequence
10498     Chain = RetValue.getValue(1);
10499     Glue = RetValue.getValue(2);
10500 
10501     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10502       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10503       SDValue RetValue2 =
10504           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10505       Chain = RetValue2.getValue(1);
10506       Glue = RetValue2.getValue(2);
10507       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10508                              RetValue2);
10509     }
10510 
10511     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10512 
10513     InVals.push_back(RetValue);
10514   }
10515 
10516   return Chain;
10517 }
10518 
10519 bool RISCVTargetLowering::CanLowerReturn(
10520     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10521     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10522   SmallVector<CCValAssign, 16> RVLocs;
10523   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10524 
10525   Optional<unsigned> FirstMaskArgument;
10526   if (Subtarget.hasVInstructions())
10527     FirstMaskArgument = preAssignMask(Outs);
10528 
10529   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10530     MVT VT = Outs[i].VT;
10531     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10532     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10533     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10534                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10535                  *this, FirstMaskArgument))
10536       return false;
10537   }
10538   return true;
10539 }
10540 
10541 SDValue
10542 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10543                                  bool IsVarArg,
10544                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10545                                  const SmallVectorImpl<SDValue> &OutVals,
10546                                  const SDLoc &DL, SelectionDAG &DAG) const {
10547   const MachineFunction &MF = DAG.getMachineFunction();
10548   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10549 
10550   // Stores the assignment of the return value to a location.
10551   SmallVector<CCValAssign, 16> RVLocs;
10552 
10553   // Info about the registers and stack slot.
10554   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10555                  *DAG.getContext());
10556 
10557   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10558                     nullptr, CC_RISCV);
10559 
10560   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10561     report_fatal_error("GHC functions return void only");
10562 
10563   SDValue Glue;
10564   SmallVector<SDValue, 4> RetOps(1, Chain);
10565 
10566   // Copy the result values into the output registers.
10567   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10568     SDValue Val = OutVals[i];
10569     CCValAssign &VA = RVLocs[i];
10570     assert(VA.isRegLoc() && "Can only return in registers!");
10571 
10572     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10573       // Handle returning f64 on RV32D with a soft float ABI.
10574       assert(VA.isRegLoc() && "Expected return via registers");
10575       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10576                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10577       SDValue Lo = SplitF64.getValue(0);
10578       SDValue Hi = SplitF64.getValue(1);
10579       Register RegLo = VA.getLocReg();
10580       assert(RegLo < RISCV::X31 && "Invalid register pair");
10581       Register RegHi = RegLo + 1;
10582 
10583       if (STI.isRegisterReservedByUser(RegLo) ||
10584           STI.isRegisterReservedByUser(RegHi))
10585         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10586             MF.getFunction(),
10587             "Return value register required, but has been reserved."});
10588 
10589       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10590       Glue = Chain.getValue(1);
10591       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10592       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10593       Glue = Chain.getValue(1);
10594       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10595     } else {
10596       // Handle a 'normal' return.
10597       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10598       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10599 
10600       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10601         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10602             MF.getFunction(),
10603             "Return value register required, but has been reserved."});
10604 
10605       // Guarantee that all emitted copies are stuck together.
10606       Glue = Chain.getValue(1);
10607       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10608     }
10609   }
10610 
10611   RetOps[0] = Chain; // Update chain.
10612 
10613   // Add the glue node if we have it.
10614   if (Glue.getNode()) {
10615     RetOps.push_back(Glue);
10616   }
10617 
10618   unsigned RetOpc = RISCVISD::RET_FLAG;
10619   // Interrupt service routines use different return instructions.
10620   const Function &Func = DAG.getMachineFunction().getFunction();
10621   if (Func.hasFnAttribute("interrupt")) {
10622     if (!Func.getReturnType()->isVoidTy())
10623       report_fatal_error(
10624           "Functions with the interrupt attribute must have void return type!");
10625 
10626     MachineFunction &MF = DAG.getMachineFunction();
10627     StringRef Kind =
10628       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10629 
10630     if (Kind == "user")
10631       RetOpc = RISCVISD::URET_FLAG;
10632     else if (Kind == "supervisor")
10633       RetOpc = RISCVISD::SRET_FLAG;
10634     else
10635       RetOpc = RISCVISD::MRET_FLAG;
10636   }
10637 
10638   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10639 }
10640 
10641 void RISCVTargetLowering::validateCCReservedRegs(
10642     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10643     MachineFunction &MF) const {
10644   const Function &F = MF.getFunction();
10645   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10646 
10647   if (llvm::any_of(Regs, [&STI](auto Reg) {
10648         return STI.isRegisterReservedByUser(Reg.first);
10649       }))
10650     F.getContext().diagnose(DiagnosticInfoUnsupported{
10651         F, "Argument register required, but has been reserved."});
10652 }
10653 
10654 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10655   return CI->isTailCall();
10656 }
10657 
10658 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10659 #define NODE_NAME_CASE(NODE)                                                   \
10660   case RISCVISD::NODE:                                                         \
10661     return "RISCVISD::" #NODE;
10662   // clang-format off
10663   switch ((RISCVISD::NodeType)Opcode) {
10664   case RISCVISD::FIRST_NUMBER:
10665     break;
10666   NODE_NAME_CASE(RET_FLAG)
10667   NODE_NAME_CASE(URET_FLAG)
10668   NODE_NAME_CASE(SRET_FLAG)
10669   NODE_NAME_CASE(MRET_FLAG)
10670   NODE_NAME_CASE(CALL)
10671   NODE_NAME_CASE(SELECT_CC)
10672   NODE_NAME_CASE(BR_CC)
10673   NODE_NAME_CASE(BuildPairF64)
10674   NODE_NAME_CASE(SplitF64)
10675   NODE_NAME_CASE(TAIL)
10676   NODE_NAME_CASE(MULHSU)
10677   NODE_NAME_CASE(SLLW)
10678   NODE_NAME_CASE(SRAW)
10679   NODE_NAME_CASE(SRLW)
10680   NODE_NAME_CASE(DIVW)
10681   NODE_NAME_CASE(DIVUW)
10682   NODE_NAME_CASE(REMUW)
10683   NODE_NAME_CASE(ROLW)
10684   NODE_NAME_CASE(RORW)
10685   NODE_NAME_CASE(CLZW)
10686   NODE_NAME_CASE(CTZW)
10687   NODE_NAME_CASE(FSLW)
10688   NODE_NAME_CASE(FSRW)
10689   NODE_NAME_CASE(FSL)
10690   NODE_NAME_CASE(FSR)
10691   NODE_NAME_CASE(FMV_H_X)
10692   NODE_NAME_CASE(FMV_X_ANYEXTH)
10693   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10694   NODE_NAME_CASE(FMV_W_X_RV64)
10695   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10696   NODE_NAME_CASE(FCVT_X)
10697   NODE_NAME_CASE(FCVT_XU)
10698   NODE_NAME_CASE(FCVT_W_RV64)
10699   NODE_NAME_CASE(FCVT_WU_RV64)
10700   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10701   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10702   NODE_NAME_CASE(READ_CYCLE_WIDE)
10703   NODE_NAME_CASE(GREV)
10704   NODE_NAME_CASE(GREVW)
10705   NODE_NAME_CASE(GORC)
10706   NODE_NAME_CASE(GORCW)
10707   NODE_NAME_CASE(SHFL)
10708   NODE_NAME_CASE(SHFLW)
10709   NODE_NAME_CASE(UNSHFL)
10710   NODE_NAME_CASE(UNSHFLW)
10711   NODE_NAME_CASE(BFP)
10712   NODE_NAME_CASE(BFPW)
10713   NODE_NAME_CASE(BCOMPRESS)
10714   NODE_NAME_CASE(BCOMPRESSW)
10715   NODE_NAME_CASE(BDECOMPRESS)
10716   NODE_NAME_CASE(BDECOMPRESSW)
10717   NODE_NAME_CASE(VMV_V_X_VL)
10718   NODE_NAME_CASE(VFMV_V_F_VL)
10719   NODE_NAME_CASE(VMV_X_S)
10720   NODE_NAME_CASE(VMV_S_X_VL)
10721   NODE_NAME_CASE(VFMV_S_F_VL)
10722   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10723   NODE_NAME_CASE(READ_VLENB)
10724   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10725   NODE_NAME_CASE(VSLIDEUP_VL)
10726   NODE_NAME_CASE(VSLIDE1UP_VL)
10727   NODE_NAME_CASE(VSLIDEDOWN_VL)
10728   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10729   NODE_NAME_CASE(VID_VL)
10730   NODE_NAME_CASE(VFNCVT_ROD_VL)
10731   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10732   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10733   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10734   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10735   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10736   NODE_NAME_CASE(VECREDUCE_AND_VL)
10737   NODE_NAME_CASE(VECREDUCE_OR_VL)
10738   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10739   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10740   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10741   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10742   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10743   NODE_NAME_CASE(ADD_VL)
10744   NODE_NAME_CASE(AND_VL)
10745   NODE_NAME_CASE(MUL_VL)
10746   NODE_NAME_CASE(OR_VL)
10747   NODE_NAME_CASE(SDIV_VL)
10748   NODE_NAME_CASE(SHL_VL)
10749   NODE_NAME_CASE(SREM_VL)
10750   NODE_NAME_CASE(SRA_VL)
10751   NODE_NAME_CASE(SRL_VL)
10752   NODE_NAME_CASE(SUB_VL)
10753   NODE_NAME_CASE(UDIV_VL)
10754   NODE_NAME_CASE(UREM_VL)
10755   NODE_NAME_CASE(XOR_VL)
10756   NODE_NAME_CASE(SADDSAT_VL)
10757   NODE_NAME_CASE(UADDSAT_VL)
10758   NODE_NAME_CASE(SSUBSAT_VL)
10759   NODE_NAME_CASE(USUBSAT_VL)
10760   NODE_NAME_CASE(FADD_VL)
10761   NODE_NAME_CASE(FSUB_VL)
10762   NODE_NAME_CASE(FMUL_VL)
10763   NODE_NAME_CASE(FDIV_VL)
10764   NODE_NAME_CASE(FNEG_VL)
10765   NODE_NAME_CASE(FABS_VL)
10766   NODE_NAME_CASE(FSQRT_VL)
10767   NODE_NAME_CASE(FMA_VL)
10768   NODE_NAME_CASE(FCOPYSIGN_VL)
10769   NODE_NAME_CASE(SMIN_VL)
10770   NODE_NAME_CASE(SMAX_VL)
10771   NODE_NAME_CASE(UMIN_VL)
10772   NODE_NAME_CASE(UMAX_VL)
10773   NODE_NAME_CASE(FMINNUM_VL)
10774   NODE_NAME_CASE(FMAXNUM_VL)
10775   NODE_NAME_CASE(MULHS_VL)
10776   NODE_NAME_CASE(MULHU_VL)
10777   NODE_NAME_CASE(FP_TO_SINT_VL)
10778   NODE_NAME_CASE(FP_TO_UINT_VL)
10779   NODE_NAME_CASE(SINT_TO_FP_VL)
10780   NODE_NAME_CASE(UINT_TO_FP_VL)
10781   NODE_NAME_CASE(FP_EXTEND_VL)
10782   NODE_NAME_CASE(FP_ROUND_VL)
10783   NODE_NAME_CASE(VWMUL_VL)
10784   NODE_NAME_CASE(VWMULU_VL)
10785   NODE_NAME_CASE(VWMULSU_VL)
10786   NODE_NAME_CASE(VWADD_VL)
10787   NODE_NAME_CASE(VWADDU_VL)
10788   NODE_NAME_CASE(VWSUB_VL)
10789   NODE_NAME_CASE(VWSUBU_VL)
10790   NODE_NAME_CASE(VWADD_W_VL)
10791   NODE_NAME_CASE(VWADDU_W_VL)
10792   NODE_NAME_CASE(VWSUB_W_VL)
10793   NODE_NAME_CASE(VWSUBU_W_VL)
10794   NODE_NAME_CASE(SETCC_VL)
10795   NODE_NAME_CASE(VSELECT_VL)
10796   NODE_NAME_CASE(VP_MERGE_VL)
10797   NODE_NAME_CASE(VMAND_VL)
10798   NODE_NAME_CASE(VMOR_VL)
10799   NODE_NAME_CASE(VMXOR_VL)
10800   NODE_NAME_CASE(VMCLR_VL)
10801   NODE_NAME_CASE(VMSET_VL)
10802   NODE_NAME_CASE(VRGATHER_VX_VL)
10803   NODE_NAME_CASE(VRGATHER_VV_VL)
10804   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10805   NODE_NAME_CASE(VSEXT_VL)
10806   NODE_NAME_CASE(VZEXT_VL)
10807   NODE_NAME_CASE(VCPOP_VL)
10808   NODE_NAME_CASE(READ_CSR)
10809   NODE_NAME_CASE(WRITE_CSR)
10810   NODE_NAME_CASE(SWAP_CSR)
10811   }
10812   // clang-format on
10813   return nullptr;
10814 #undef NODE_NAME_CASE
10815 }
10816 
10817 /// getConstraintType - Given a constraint letter, return the type of
10818 /// constraint it is for this target.
10819 RISCVTargetLowering::ConstraintType
10820 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10821   if (Constraint.size() == 1) {
10822     switch (Constraint[0]) {
10823     default:
10824       break;
10825     case 'f':
10826       return C_RegisterClass;
10827     case 'I':
10828     case 'J':
10829     case 'K':
10830       return C_Immediate;
10831     case 'A':
10832       return C_Memory;
10833     case 'S': // A symbolic address
10834       return C_Other;
10835     }
10836   } else {
10837     if (Constraint == "vr" || Constraint == "vm")
10838       return C_RegisterClass;
10839   }
10840   return TargetLowering::getConstraintType(Constraint);
10841 }
10842 
10843 std::pair<unsigned, const TargetRegisterClass *>
10844 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10845                                                   StringRef Constraint,
10846                                                   MVT VT) const {
10847   // First, see if this is a constraint that directly corresponds to a
10848   // RISCV register class.
10849   if (Constraint.size() == 1) {
10850     switch (Constraint[0]) {
10851     case 'r':
10852       // TODO: Support fixed vectors up to XLen for P extension?
10853       if (VT.isVector())
10854         break;
10855       return std::make_pair(0U, &RISCV::GPRRegClass);
10856     case 'f':
10857       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10858         return std::make_pair(0U, &RISCV::FPR16RegClass);
10859       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10860         return std::make_pair(0U, &RISCV::FPR32RegClass);
10861       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10862         return std::make_pair(0U, &RISCV::FPR64RegClass);
10863       break;
10864     default:
10865       break;
10866     }
10867   } else if (Constraint == "vr") {
10868     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10869                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10870       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10871         return std::make_pair(0U, RC);
10872     }
10873   } else if (Constraint == "vm") {
10874     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10875       return std::make_pair(0U, &RISCV::VMV0RegClass);
10876   }
10877 
10878   // Clang will correctly decode the usage of register name aliases into their
10879   // official names. However, other frontends like `rustc` do not. This allows
10880   // users of these frontends to use the ABI names for registers in LLVM-style
10881   // register constraints.
10882   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10883                                .Case("{zero}", RISCV::X0)
10884                                .Case("{ra}", RISCV::X1)
10885                                .Case("{sp}", RISCV::X2)
10886                                .Case("{gp}", RISCV::X3)
10887                                .Case("{tp}", RISCV::X4)
10888                                .Case("{t0}", RISCV::X5)
10889                                .Case("{t1}", RISCV::X6)
10890                                .Case("{t2}", RISCV::X7)
10891                                .Cases("{s0}", "{fp}", RISCV::X8)
10892                                .Case("{s1}", RISCV::X9)
10893                                .Case("{a0}", RISCV::X10)
10894                                .Case("{a1}", RISCV::X11)
10895                                .Case("{a2}", RISCV::X12)
10896                                .Case("{a3}", RISCV::X13)
10897                                .Case("{a4}", RISCV::X14)
10898                                .Case("{a5}", RISCV::X15)
10899                                .Case("{a6}", RISCV::X16)
10900                                .Case("{a7}", RISCV::X17)
10901                                .Case("{s2}", RISCV::X18)
10902                                .Case("{s3}", RISCV::X19)
10903                                .Case("{s4}", RISCV::X20)
10904                                .Case("{s5}", RISCV::X21)
10905                                .Case("{s6}", RISCV::X22)
10906                                .Case("{s7}", RISCV::X23)
10907                                .Case("{s8}", RISCV::X24)
10908                                .Case("{s9}", RISCV::X25)
10909                                .Case("{s10}", RISCV::X26)
10910                                .Case("{s11}", RISCV::X27)
10911                                .Case("{t3}", RISCV::X28)
10912                                .Case("{t4}", RISCV::X29)
10913                                .Case("{t5}", RISCV::X30)
10914                                .Case("{t6}", RISCV::X31)
10915                                .Default(RISCV::NoRegister);
10916   if (XRegFromAlias != RISCV::NoRegister)
10917     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10918 
10919   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10920   // TableGen record rather than the AsmName to choose registers for InlineAsm
10921   // constraints, plus we want to match those names to the widest floating point
10922   // register type available, manually select floating point registers here.
10923   //
10924   // The second case is the ABI name of the register, so that frontends can also
10925   // use the ABI names in register constraint lists.
10926   if (Subtarget.hasStdExtF()) {
10927     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10928                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10929                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10930                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10931                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10932                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10933                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10934                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10935                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10936                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10937                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10938                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10939                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10940                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10941                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10942                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10943                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10944                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10945                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10946                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10947                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10948                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10949                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10950                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10951                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10952                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10953                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10954                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10955                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10956                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10957                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10958                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10959                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10960                         .Default(RISCV::NoRegister);
10961     if (FReg != RISCV::NoRegister) {
10962       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10963       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10964         unsigned RegNo = FReg - RISCV::F0_F;
10965         unsigned DReg = RISCV::F0_D + RegNo;
10966         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10967       }
10968       if (VT == MVT::f32 || VT == MVT::Other)
10969         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10970       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10971         unsigned RegNo = FReg - RISCV::F0_F;
10972         unsigned HReg = RISCV::F0_H + RegNo;
10973         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10974       }
10975     }
10976   }
10977 
10978   if (Subtarget.hasVInstructions()) {
10979     Register VReg = StringSwitch<Register>(Constraint.lower())
10980                         .Case("{v0}", RISCV::V0)
10981                         .Case("{v1}", RISCV::V1)
10982                         .Case("{v2}", RISCV::V2)
10983                         .Case("{v3}", RISCV::V3)
10984                         .Case("{v4}", RISCV::V4)
10985                         .Case("{v5}", RISCV::V5)
10986                         .Case("{v6}", RISCV::V6)
10987                         .Case("{v7}", RISCV::V7)
10988                         .Case("{v8}", RISCV::V8)
10989                         .Case("{v9}", RISCV::V9)
10990                         .Case("{v10}", RISCV::V10)
10991                         .Case("{v11}", RISCV::V11)
10992                         .Case("{v12}", RISCV::V12)
10993                         .Case("{v13}", RISCV::V13)
10994                         .Case("{v14}", RISCV::V14)
10995                         .Case("{v15}", RISCV::V15)
10996                         .Case("{v16}", RISCV::V16)
10997                         .Case("{v17}", RISCV::V17)
10998                         .Case("{v18}", RISCV::V18)
10999                         .Case("{v19}", RISCV::V19)
11000                         .Case("{v20}", RISCV::V20)
11001                         .Case("{v21}", RISCV::V21)
11002                         .Case("{v22}", RISCV::V22)
11003                         .Case("{v23}", RISCV::V23)
11004                         .Case("{v24}", RISCV::V24)
11005                         .Case("{v25}", RISCV::V25)
11006                         .Case("{v26}", RISCV::V26)
11007                         .Case("{v27}", RISCV::V27)
11008                         .Case("{v28}", RISCV::V28)
11009                         .Case("{v29}", RISCV::V29)
11010                         .Case("{v30}", RISCV::V30)
11011                         .Case("{v31}", RISCV::V31)
11012                         .Default(RISCV::NoRegister);
11013     if (VReg != RISCV::NoRegister) {
11014       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11015         return std::make_pair(VReg, &RISCV::VMRegClass);
11016       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11017         return std::make_pair(VReg, &RISCV::VRRegClass);
11018       for (const auto *RC :
11019            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11020         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11021           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11022           return std::make_pair(VReg, RC);
11023         }
11024       }
11025     }
11026   }
11027 
11028   std::pair<Register, const TargetRegisterClass *> Res =
11029       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11030 
11031   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11032   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11033   // Subtarget into account.
11034   if (Res.second == &RISCV::GPRF16RegClass ||
11035       Res.second == &RISCV::GPRF32RegClass ||
11036       Res.second == &RISCV::GPRF64RegClass)
11037     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11038 
11039   return Res;
11040 }
11041 
11042 unsigned
11043 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11044   // Currently only support length 1 constraints.
11045   if (ConstraintCode.size() == 1) {
11046     switch (ConstraintCode[0]) {
11047     case 'A':
11048       return InlineAsm::Constraint_A;
11049     default:
11050       break;
11051     }
11052   }
11053 
11054   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11055 }
11056 
11057 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11058     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11059     SelectionDAG &DAG) const {
11060   // Currently only support length 1 constraints.
11061   if (Constraint.length() == 1) {
11062     switch (Constraint[0]) {
11063     case 'I':
11064       // Validate & create a 12-bit signed immediate operand.
11065       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11066         uint64_t CVal = C->getSExtValue();
11067         if (isInt<12>(CVal))
11068           Ops.push_back(
11069               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11070       }
11071       return;
11072     case 'J':
11073       // Validate & create an integer zero operand.
11074       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11075         if (C->getZExtValue() == 0)
11076           Ops.push_back(
11077               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11078       return;
11079     case 'K':
11080       // Validate & create a 5-bit unsigned immediate operand.
11081       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11082         uint64_t CVal = C->getZExtValue();
11083         if (isUInt<5>(CVal))
11084           Ops.push_back(
11085               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11086       }
11087       return;
11088     case 'S':
11089       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11090         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11091                                                  GA->getValueType(0)));
11092       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11093         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11094                                                 BA->getValueType(0)));
11095       }
11096       return;
11097     default:
11098       break;
11099     }
11100   }
11101   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11102 }
11103 
11104 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11105                                                    Instruction *Inst,
11106                                                    AtomicOrdering Ord) const {
11107   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11108     return Builder.CreateFence(Ord);
11109   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11110     return Builder.CreateFence(AtomicOrdering::Release);
11111   return nullptr;
11112 }
11113 
11114 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11115                                                     Instruction *Inst,
11116                                                     AtomicOrdering Ord) const {
11117   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11118     return Builder.CreateFence(AtomicOrdering::Acquire);
11119   return nullptr;
11120 }
11121 
11122 TargetLowering::AtomicExpansionKind
11123 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11124   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11125   // point operations can't be used in an lr/sc sequence without breaking the
11126   // forward-progress guarantee.
11127   if (AI->isFloatingPointOperation())
11128     return AtomicExpansionKind::CmpXChg;
11129 
11130   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11131   if (Size == 8 || Size == 16)
11132     return AtomicExpansionKind::MaskedIntrinsic;
11133   return AtomicExpansionKind::None;
11134 }
11135 
11136 static Intrinsic::ID
11137 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11138   if (XLen == 32) {
11139     switch (BinOp) {
11140     default:
11141       llvm_unreachable("Unexpected AtomicRMW BinOp");
11142     case AtomicRMWInst::Xchg:
11143       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11144     case AtomicRMWInst::Add:
11145       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11146     case AtomicRMWInst::Sub:
11147       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11148     case AtomicRMWInst::Nand:
11149       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11150     case AtomicRMWInst::Max:
11151       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11152     case AtomicRMWInst::Min:
11153       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11154     case AtomicRMWInst::UMax:
11155       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11156     case AtomicRMWInst::UMin:
11157       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11158     }
11159   }
11160 
11161   if (XLen == 64) {
11162     switch (BinOp) {
11163     default:
11164       llvm_unreachable("Unexpected AtomicRMW BinOp");
11165     case AtomicRMWInst::Xchg:
11166       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11167     case AtomicRMWInst::Add:
11168       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11169     case AtomicRMWInst::Sub:
11170       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11171     case AtomicRMWInst::Nand:
11172       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11173     case AtomicRMWInst::Max:
11174       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11175     case AtomicRMWInst::Min:
11176       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11177     case AtomicRMWInst::UMax:
11178       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11179     case AtomicRMWInst::UMin:
11180       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11181     }
11182   }
11183 
11184   llvm_unreachable("Unexpected XLen\n");
11185 }
11186 
11187 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11188     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11189     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11190   unsigned XLen = Subtarget.getXLen();
11191   Value *Ordering =
11192       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11193   Type *Tys[] = {AlignedAddr->getType()};
11194   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11195       AI->getModule(),
11196       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11197 
11198   if (XLen == 64) {
11199     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11200     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11201     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11202   }
11203 
11204   Value *Result;
11205 
11206   // Must pass the shift amount needed to sign extend the loaded value prior
11207   // to performing a signed comparison for min/max. ShiftAmt is the number of
11208   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11209   // is the number of bits to left+right shift the value in order to
11210   // sign-extend.
11211   if (AI->getOperation() == AtomicRMWInst::Min ||
11212       AI->getOperation() == AtomicRMWInst::Max) {
11213     const DataLayout &DL = AI->getModule()->getDataLayout();
11214     unsigned ValWidth =
11215         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11216     Value *SextShamt =
11217         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11218     Result = Builder.CreateCall(LrwOpScwLoop,
11219                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11220   } else {
11221     Result =
11222         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11223   }
11224 
11225   if (XLen == 64)
11226     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11227   return Result;
11228 }
11229 
11230 TargetLowering::AtomicExpansionKind
11231 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11232     AtomicCmpXchgInst *CI) const {
11233   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11234   if (Size == 8 || Size == 16)
11235     return AtomicExpansionKind::MaskedIntrinsic;
11236   return AtomicExpansionKind::None;
11237 }
11238 
11239 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11240     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11241     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11242   unsigned XLen = Subtarget.getXLen();
11243   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11244   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11245   if (XLen == 64) {
11246     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11247     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11248     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11249     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11250   }
11251   Type *Tys[] = {AlignedAddr->getType()};
11252   Function *MaskedCmpXchg =
11253       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11254   Value *Result = Builder.CreateCall(
11255       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11256   if (XLen == 64)
11257     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11258   return Result;
11259 }
11260 
11261 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11262   return false;
11263 }
11264 
11265 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11266                                                EVT VT) const {
11267   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11268     return false;
11269 
11270   switch (FPVT.getSimpleVT().SimpleTy) {
11271   case MVT::f16:
11272     return Subtarget.hasStdExtZfh();
11273   case MVT::f32:
11274     return Subtarget.hasStdExtF();
11275   case MVT::f64:
11276     return Subtarget.hasStdExtD();
11277   default:
11278     return false;
11279   }
11280 }
11281 
11282 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11283   // If we are using the small code model, we can reduce size of jump table
11284   // entry to 4 bytes.
11285   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11286       getTargetMachine().getCodeModel() == CodeModel::Small) {
11287     return MachineJumpTableInfo::EK_Custom32;
11288   }
11289   return TargetLowering::getJumpTableEncoding();
11290 }
11291 
11292 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11293     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11294     unsigned uid, MCContext &Ctx) const {
11295   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11296          getTargetMachine().getCodeModel() == CodeModel::Small);
11297   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11298 }
11299 
11300 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11301                                                      EVT VT) const {
11302   VT = VT.getScalarType();
11303 
11304   if (!VT.isSimple())
11305     return false;
11306 
11307   switch (VT.getSimpleVT().SimpleTy) {
11308   case MVT::f16:
11309     return Subtarget.hasStdExtZfh();
11310   case MVT::f32:
11311     return Subtarget.hasStdExtF();
11312   case MVT::f64:
11313     return Subtarget.hasStdExtD();
11314   default:
11315     break;
11316   }
11317 
11318   return false;
11319 }
11320 
11321 Register RISCVTargetLowering::getExceptionPointerRegister(
11322     const Constant *PersonalityFn) const {
11323   return RISCV::X10;
11324 }
11325 
11326 Register RISCVTargetLowering::getExceptionSelectorRegister(
11327     const Constant *PersonalityFn) const {
11328   return RISCV::X11;
11329 }
11330 
11331 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11332   // Return false to suppress the unnecessary extensions if the LibCall
11333   // arguments or return value is f32 type for LP64 ABI.
11334   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11335   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11336     return false;
11337 
11338   return true;
11339 }
11340 
11341 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11342   if (Subtarget.is64Bit() && Type == MVT::i32)
11343     return true;
11344 
11345   return IsSigned;
11346 }
11347 
11348 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11349                                                  SDValue C) const {
11350   // Check integral scalar types.
11351   if (VT.isScalarInteger()) {
11352     // Omit the optimization if the sub target has the M extension and the data
11353     // size exceeds XLen.
11354     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11355       return false;
11356     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11357       // Break the MUL to a SLLI and an ADD/SUB.
11358       const APInt &Imm = ConstNode->getAPIntValue();
11359       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11360           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11361         return true;
11362       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11363       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11364           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11365            (Imm - 8).isPowerOf2()))
11366         return true;
11367       // Omit the following optimization if the sub target has the M extension
11368       // and the data size >= XLen.
11369       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11370         return false;
11371       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11372       // a pair of LUI/ADDI.
11373       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11374         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11375         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11376             (1 - ImmS).isPowerOf2())
11377         return true;
11378       }
11379     }
11380   }
11381 
11382   return false;
11383 }
11384 
11385 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11386                                                       SDValue ConstNode) const {
11387   // Let the DAGCombiner decide for vectors.
11388   EVT VT = AddNode.getValueType();
11389   if (VT.isVector())
11390     return true;
11391 
11392   // Let the DAGCombiner decide for larger types.
11393   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11394     return true;
11395 
11396   // It is worse if c1 is simm12 while c1*c2 is not.
11397   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11398   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11399   const APInt &C1 = C1Node->getAPIntValue();
11400   const APInt &C2 = C2Node->getAPIntValue();
11401   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11402     return false;
11403 
11404   // Default to true and let the DAGCombiner decide.
11405   return true;
11406 }
11407 
11408 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11409     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11410     bool *Fast) const {
11411   if (!VT.isVector())
11412     return false;
11413 
11414   EVT ElemVT = VT.getVectorElementType();
11415   if (Alignment >= ElemVT.getStoreSize()) {
11416     if (Fast)
11417       *Fast = true;
11418     return true;
11419   }
11420 
11421   return false;
11422 }
11423 
11424 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11425     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11426     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11427   bool IsABIRegCopy = CC.hasValue();
11428   EVT ValueVT = Val.getValueType();
11429   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11430     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11431     // and cast to f32.
11432     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11433     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11434     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11435                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11436     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11437     Parts[0] = Val;
11438     return true;
11439   }
11440 
11441   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11442     LLVMContext &Context = *DAG.getContext();
11443     EVT ValueEltVT = ValueVT.getVectorElementType();
11444     EVT PartEltVT = PartVT.getVectorElementType();
11445     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11446     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11447     if (PartVTBitSize % ValueVTBitSize == 0) {
11448       assert(PartVTBitSize >= ValueVTBitSize);
11449       // If the element types are different, bitcast to the same element type of
11450       // PartVT first.
11451       // Give an example here, we want copy a <vscale x 1 x i8> value to
11452       // <vscale x 4 x i16>.
11453       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11454       // subvector, then we can bitcast to <vscale x 4 x i16>.
11455       if (ValueEltVT != PartEltVT) {
11456         if (PartVTBitSize > ValueVTBitSize) {
11457           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11458           assert(Count != 0 && "The number of element should not be zero.");
11459           EVT SameEltTypeVT =
11460               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11461           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11462                             DAG.getUNDEF(SameEltTypeVT), Val,
11463                             DAG.getVectorIdxConstant(0, DL));
11464         }
11465         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11466       } else {
11467         Val =
11468             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11469                         Val, DAG.getVectorIdxConstant(0, DL));
11470       }
11471       Parts[0] = Val;
11472       return true;
11473     }
11474   }
11475   return false;
11476 }
11477 
11478 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11479     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11480     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11481   bool IsABIRegCopy = CC.hasValue();
11482   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11483     SDValue Val = Parts[0];
11484 
11485     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11486     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11487     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11488     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11489     return Val;
11490   }
11491 
11492   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11493     LLVMContext &Context = *DAG.getContext();
11494     SDValue Val = Parts[0];
11495     EVT ValueEltVT = ValueVT.getVectorElementType();
11496     EVT PartEltVT = PartVT.getVectorElementType();
11497     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11498     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11499     if (PartVTBitSize % ValueVTBitSize == 0) {
11500       assert(PartVTBitSize >= ValueVTBitSize);
11501       EVT SameEltTypeVT = ValueVT;
11502       // If the element types are different, convert it to the same element type
11503       // of PartVT.
11504       // Give an example here, we want copy a <vscale x 1 x i8> value from
11505       // <vscale x 4 x i16>.
11506       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11507       // then we can extract <vscale x 1 x i8>.
11508       if (ValueEltVT != PartEltVT) {
11509         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11510         assert(Count != 0 && "The number of element should not be zero.");
11511         SameEltTypeVT =
11512             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11513         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11514       }
11515       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11516                         DAG.getVectorIdxConstant(0, DL));
11517       return Val;
11518     }
11519   }
11520   return SDValue();
11521 }
11522 
11523 SDValue
11524 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11525                                    SelectionDAG &DAG,
11526                                    SmallVectorImpl<SDNode *> &Created) const {
11527   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11528   if (isIntDivCheap(N->getValueType(0), Attr))
11529     return SDValue(N, 0); // Lower SDIV as SDIV
11530 
11531   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11532          "Unexpected divisor!");
11533 
11534   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11535   if (!Subtarget.hasStdExtZbt())
11536     return SDValue();
11537 
11538   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11539   // Besides, more critical path instructions will be generated when dividing
11540   // by 2. So we keep using the original DAGs for these cases.
11541   unsigned Lg2 = Divisor.countTrailingZeros();
11542   if (Lg2 == 1 || Lg2 >= 12)
11543     return SDValue();
11544 
11545   // fold (sdiv X, pow2)
11546   EVT VT = N->getValueType(0);
11547   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11548     return SDValue();
11549 
11550   SDLoc DL(N);
11551   SDValue N0 = N->getOperand(0);
11552   SDValue Zero = DAG.getConstant(0, DL, VT);
11553   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11554 
11555   // Add (N0 < 0) ? Pow2 - 1 : 0;
11556   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11557   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11558   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11559 
11560   Created.push_back(Cmp.getNode());
11561   Created.push_back(Add.getNode());
11562   Created.push_back(Sel.getNode());
11563 
11564   // Divide by pow2.
11565   SDValue SRA =
11566       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11567 
11568   // If we're dividing by a positive value, we're done.  Otherwise, we must
11569   // negate the result.
11570   if (Divisor.isNonNegative())
11571     return SRA;
11572 
11573   Created.push_back(SRA.getNode());
11574   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11575 }
11576 
11577 #define GET_REGISTER_MATCHER
11578 #include "RISCVGenAsmMatcher.inc"
11579 
11580 Register
11581 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11582                                        const MachineFunction &MF) const {
11583   Register Reg = MatchRegisterAltName(RegName);
11584   if (Reg == RISCV::NoRegister)
11585     Reg = MatchRegisterName(RegName);
11586   if (Reg == RISCV::NoRegister)
11587     report_fatal_error(
11588         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11589   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11590   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11591     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11592                              StringRef(RegName) + "\"."));
11593   return Reg;
11594 }
11595 
11596 namespace llvm {
11597 namespace RISCVVIntrinsicsTable {
11598 
11599 #define GET_RISCVVIntrinsicsTable_IMPL
11600 #include "RISCVGenSearchableTables.inc"
11601 
11602 } // namespace RISCVVIntrinsicsTable
11603 
11604 } // namespace llvm
11605