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,      ISD::VP_FPTOSI};
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         ISD::VP_SITOFP};
501 
502     if (!Subtarget.is64Bit()) {
503       // We must custom-lower certain vXi64 operations on RV32 due to the vector
504       // element type being illegal.
505       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
506       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
507 
508       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
509       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
510       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
511       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
512       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
513       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
515       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
516 
517       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
518       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
519       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
520       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
521       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
522       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
524       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
525     }
526 
527     for (MVT VT : BoolVecVTs) {
528       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
529 
530       // Mask VTs are custom-expanded into a series of standard nodes
531       setOperationAction(ISD::TRUNCATE, VT, Custom);
532       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
533       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
534       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
535 
536       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
537       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
538 
539       setOperationAction(ISD::SELECT, VT, Custom);
540       setOperationAction(ISD::SELECT_CC, VT, Expand);
541       setOperationAction(ISD::VSELECT, VT, Expand);
542       setOperationAction(ISD::VP_MERGE, VT, Expand);
543       setOperationAction(ISD::VP_SELECT, VT, Expand);
544 
545       setOperationAction(ISD::VP_AND, VT, Custom);
546       setOperationAction(ISD::VP_OR, VT, Custom);
547       setOperationAction(ISD::VP_XOR, VT, Custom);
548 
549       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
550       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
551       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
552 
553       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
554       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
555       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
556 
557       // RVV has native int->float & float->int conversions where the
558       // element type sizes are within one power-of-two of each other. Any
559       // wider distances between type sizes have to be lowered as sequences
560       // which progressively narrow the gap in stages.
561       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
562       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
563       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
564       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
565 
566       // Expand all extending loads to types larger than this, and truncating
567       // stores from types larger than this.
568       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
569         setTruncStoreAction(OtherVT, VT, Expand);
570         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
571         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
572         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
573       }
574     }
575 
576     for (MVT VT : IntVecVTs) {
577       if (VT.getVectorElementType() == MVT::i64 &&
578           !Subtarget.hasVInstructionsI64())
579         continue;
580 
581       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
582       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
583 
584       // Vectors implement MULHS/MULHU.
585       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
586       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
587 
588       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
589       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
590         setOperationAction(ISD::MULHU, VT, Expand);
591         setOperationAction(ISD::MULHS, VT, Expand);
592       }
593 
594       setOperationAction(ISD::SMIN, VT, Legal);
595       setOperationAction(ISD::SMAX, VT, Legal);
596       setOperationAction(ISD::UMIN, VT, Legal);
597       setOperationAction(ISD::UMAX, VT, Legal);
598 
599       setOperationAction(ISD::ROTL, VT, Expand);
600       setOperationAction(ISD::ROTR, VT, Expand);
601 
602       setOperationAction(ISD::CTTZ, VT, Expand);
603       setOperationAction(ISD::CTLZ, VT, Expand);
604       setOperationAction(ISD::CTPOP, VT, Expand);
605 
606       setOperationAction(ISD::BSWAP, VT, Expand);
607 
608       // Custom-lower extensions and truncations from/to mask types.
609       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
610       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
611       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
612 
613       // RVV has native int->float & float->int conversions where the
614       // element type sizes are within one power-of-two of each other. Any
615       // wider distances between type sizes have to be lowered as sequences
616       // which progressively narrow the gap in stages.
617       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
618       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
619       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
620       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
621 
622       setOperationAction(ISD::SADDSAT, VT, Legal);
623       setOperationAction(ISD::UADDSAT, VT, Legal);
624       setOperationAction(ISD::SSUBSAT, VT, Legal);
625       setOperationAction(ISD::USUBSAT, VT, Legal);
626 
627       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
628       // nodes which truncate by one power of two at a time.
629       setOperationAction(ISD::TRUNCATE, VT, Custom);
630 
631       // Custom-lower insert/extract operations to simplify patterns.
632       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
633       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
634 
635       // Custom-lower reduction operations to set up the corresponding custom
636       // nodes' operands.
637       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
638       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
639       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
640       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
641       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
642       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
643       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
644       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
645 
646       for (unsigned VPOpc : IntegerVPOps)
647         setOperationAction(VPOpc, VT, Custom);
648 
649       setOperationAction(ISD::LOAD, VT, Custom);
650       setOperationAction(ISD::STORE, VT, Custom);
651 
652       setOperationAction(ISD::MLOAD, VT, Custom);
653       setOperationAction(ISD::MSTORE, VT, Custom);
654       setOperationAction(ISD::MGATHER, VT, Custom);
655       setOperationAction(ISD::MSCATTER, VT, Custom);
656 
657       setOperationAction(ISD::VP_LOAD, VT, Custom);
658       setOperationAction(ISD::VP_STORE, VT, Custom);
659       setOperationAction(ISD::VP_GATHER, VT, Custom);
660       setOperationAction(ISD::VP_SCATTER, VT, Custom);
661 
662       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
663       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
664       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
665 
666       setOperationAction(ISD::SELECT, VT, Custom);
667       setOperationAction(ISD::SELECT_CC, VT, Expand);
668 
669       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
670       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
671 
672       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
673         setTruncStoreAction(VT, OtherVT, Expand);
674         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
675         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
676         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
677       }
678 
679       // Splice
680       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
681 
682       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
683       // type that can represent the value exactly.
684       if (VT.getVectorElementType() != MVT::i64) {
685         MVT FloatEltVT =
686             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
687         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
688         if (isTypeLegal(FloatVT)) {
689           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
690           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
691         }
692       }
693     }
694 
695     // Expand various CCs to best match the RVV ISA, which natively supports UNE
696     // but no other unordered comparisons, and supports all ordered comparisons
697     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
698     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
699     // and we pattern-match those back to the "original", swapping operands once
700     // more. This way we catch both operations and both "vf" and "fv" forms with
701     // fewer patterns.
702     static const ISD::CondCode VFPCCToExpand[] = {
703         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
704         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
705         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
706     };
707 
708     // Sets common operation actions on RVV floating-point vector types.
709     const auto SetCommonVFPActions = [&](MVT VT) {
710       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
711       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
712       // sizes are within one power-of-two of each other. Therefore conversions
713       // between vXf16 and vXf64 must be lowered as sequences which convert via
714       // vXf32.
715       setOperationAction(ISD::FP_ROUND, VT, Custom);
716       setOperationAction(ISD::FP_EXTEND, VT, Custom);
717       // Custom-lower insert/extract operations to simplify patterns.
718       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
719       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
720       // Expand various condition codes (explained above).
721       for (auto CC : VFPCCToExpand)
722         setCondCodeAction(CC, VT, Expand);
723 
724       setOperationAction(ISD::FMINNUM, VT, Legal);
725       setOperationAction(ISD::FMAXNUM, VT, Legal);
726 
727       setOperationAction(ISD::FTRUNC, VT, Custom);
728       setOperationAction(ISD::FCEIL, VT, Custom);
729       setOperationAction(ISD::FFLOOR, VT, Custom);
730       setOperationAction(ISD::FROUND, VT, Custom);
731 
732       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
733       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
734       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
735       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
736 
737       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
738 
739       setOperationAction(ISD::LOAD, VT, Custom);
740       setOperationAction(ISD::STORE, VT, Custom);
741 
742       setOperationAction(ISD::MLOAD, VT, Custom);
743       setOperationAction(ISD::MSTORE, VT, Custom);
744       setOperationAction(ISD::MGATHER, VT, Custom);
745       setOperationAction(ISD::MSCATTER, VT, Custom);
746 
747       setOperationAction(ISD::VP_LOAD, VT, Custom);
748       setOperationAction(ISD::VP_STORE, VT, Custom);
749       setOperationAction(ISD::VP_GATHER, VT, Custom);
750       setOperationAction(ISD::VP_SCATTER, VT, Custom);
751 
752       setOperationAction(ISD::SELECT, VT, Custom);
753       setOperationAction(ISD::SELECT_CC, VT, Expand);
754 
755       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
756       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
757       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
758 
759       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
760       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
761 
762       for (unsigned VPOpc : FloatingPointVPOps)
763         setOperationAction(VPOpc, VT, Custom);
764     };
765 
766     // Sets common extload/truncstore actions on RVV floating-point vector
767     // types.
768     const auto SetCommonVFPExtLoadTruncStoreActions =
769         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
770           for (auto SmallVT : SmallerVTs) {
771             setTruncStoreAction(VT, SmallVT, Expand);
772             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
773           }
774         };
775 
776     if (Subtarget.hasVInstructionsF16())
777       for (MVT VT : F16VecVTs)
778         SetCommonVFPActions(VT);
779 
780     for (MVT VT : F32VecVTs) {
781       if (Subtarget.hasVInstructionsF32())
782         SetCommonVFPActions(VT);
783       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
784     }
785 
786     for (MVT VT : F64VecVTs) {
787       if (Subtarget.hasVInstructionsF64())
788         SetCommonVFPActions(VT);
789       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
790       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
791     }
792 
793     if (Subtarget.useRVVForFixedLengthVectors()) {
794       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
795         if (!useRVVForFixedLengthVectorVT(VT))
796           continue;
797 
798         // By default everything must be expanded.
799         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
800           setOperationAction(Op, VT, Expand);
801         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
802           setTruncStoreAction(VT, OtherVT, Expand);
803           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
804           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
805           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
806         }
807 
808         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
809         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
810         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
811 
812         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
813         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
814 
815         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
816         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
817 
818         setOperationAction(ISD::LOAD, VT, Custom);
819         setOperationAction(ISD::STORE, VT, Custom);
820 
821         setOperationAction(ISD::SETCC, VT, Custom);
822 
823         setOperationAction(ISD::SELECT, VT, Custom);
824 
825         setOperationAction(ISD::TRUNCATE, VT, Custom);
826 
827         setOperationAction(ISD::BITCAST, VT, Custom);
828 
829         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
830         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
831         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
832 
833         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
834         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
835         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
836 
837         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
838         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
839         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
840         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
841 
842         // Operations below are different for between masks and other vectors.
843         if (VT.getVectorElementType() == MVT::i1) {
844           setOperationAction(ISD::VP_AND, VT, Custom);
845           setOperationAction(ISD::VP_OR, VT, Custom);
846           setOperationAction(ISD::VP_XOR, VT, Custom);
847           setOperationAction(ISD::AND, VT, Custom);
848           setOperationAction(ISD::OR, VT, Custom);
849           setOperationAction(ISD::XOR, VT, Custom);
850 
851           setOperationAction(ISD::VP_FPTOSI, VT, Custom);
852           continue;
853         }
854 
855         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
856         // it before type legalization for i64 vectors on RV32. It will then be
857         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
858         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
859         // improvements first.
860         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
861           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
862           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
863         }
864 
865         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
866         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
867 
868         setOperationAction(ISD::MLOAD, VT, Custom);
869         setOperationAction(ISD::MSTORE, VT, Custom);
870         setOperationAction(ISD::MGATHER, VT, Custom);
871         setOperationAction(ISD::MSCATTER, VT, Custom);
872 
873         setOperationAction(ISD::VP_LOAD, VT, Custom);
874         setOperationAction(ISD::VP_STORE, VT, Custom);
875         setOperationAction(ISD::VP_GATHER, VT, Custom);
876         setOperationAction(ISD::VP_SCATTER, VT, Custom);
877 
878         setOperationAction(ISD::ADD, VT, Custom);
879         setOperationAction(ISD::MUL, VT, Custom);
880         setOperationAction(ISD::SUB, VT, Custom);
881         setOperationAction(ISD::AND, VT, Custom);
882         setOperationAction(ISD::OR, VT, Custom);
883         setOperationAction(ISD::XOR, VT, Custom);
884         setOperationAction(ISD::SDIV, VT, Custom);
885         setOperationAction(ISD::SREM, VT, Custom);
886         setOperationAction(ISD::UDIV, VT, Custom);
887         setOperationAction(ISD::UREM, VT, Custom);
888         setOperationAction(ISD::SHL, VT, Custom);
889         setOperationAction(ISD::SRA, VT, Custom);
890         setOperationAction(ISD::SRL, VT, Custom);
891 
892         setOperationAction(ISD::SMIN, VT, Custom);
893         setOperationAction(ISD::SMAX, VT, Custom);
894         setOperationAction(ISD::UMIN, VT, Custom);
895         setOperationAction(ISD::UMAX, VT, Custom);
896         setOperationAction(ISD::ABS,  VT, Custom);
897 
898         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
899         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
900           setOperationAction(ISD::MULHS, VT, Custom);
901           setOperationAction(ISD::MULHU, VT, Custom);
902         }
903 
904         setOperationAction(ISD::SADDSAT, VT, Custom);
905         setOperationAction(ISD::UADDSAT, VT, Custom);
906         setOperationAction(ISD::SSUBSAT, VT, Custom);
907         setOperationAction(ISD::USUBSAT, VT, Custom);
908 
909         setOperationAction(ISD::VSELECT, VT, Custom);
910         setOperationAction(ISD::SELECT_CC, VT, Expand);
911 
912         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
913         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
914         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
915 
916         // Custom-lower reduction operations to set up the corresponding custom
917         // nodes' operands.
918         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
919         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
920         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
921         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
922         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
923 
924         for (unsigned VPOpc : IntegerVPOps)
925           setOperationAction(VPOpc, VT, Custom);
926 
927         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
928         // type that can represent the value exactly.
929         if (VT.getVectorElementType() != MVT::i64) {
930           MVT FloatEltVT =
931               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
932           EVT FloatVT =
933               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
934           if (isTypeLegal(FloatVT)) {
935             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
936             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
937           }
938         }
939       }
940 
941       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
942         if (!useRVVForFixedLengthVectorVT(VT))
943           continue;
944 
945         // By default everything must be expanded.
946         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
947           setOperationAction(Op, VT, Expand);
948         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
949           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
950           setTruncStoreAction(VT, OtherVT, Expand);
951         }
952 
953         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
954         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
955         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
956 
957         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
958         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
959         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
960         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
961         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
962 
963         setOperationAction(ISD::LOAD, VT, Custom);
964         setOperationAction(ISD::STORE, VT, Custom);
965         setOperationAction(ISD::MLOAD, VT, Custom);
966         setOperationAction(ISD::MSTORE, VT, Custom);
967         setOperationAction(ISD::MGATHER, VT, Custom);
968         setOperationAction(ISD::MSCATTER, VT, Custom);
969 
970         setOperationAction(ISD::VP_LOAD, VT, Custom);
971         setOperationAction(ISD::VP_STORE, VT, Custom);
972         setOperationAction(ISD::VP_GATHER, VT, Custom);
973         setOperationAction(ISD::VP_SCATTER, VT, Custom);
974 
975         setOperationAction(ISD::FADD, VT, Custom);
976         setOperationAction(ISD::FSUB, VT, Custom);
977         setOperationAction(ISD::FMUL, VT, Custom);
978         setOperationAction(ISD::FDIV, VT, Custom);
979         setOperationAction(ISD::FNEG, VT, Custom);
980         setOperationAction(ISD::FABS, VT, Custom);
981         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
982         setOperationAction(ISD::FSQRT, VT, Custom);
983         setOperationAction(ISD::FMA, VT, Custom);
984         setOperationAction(ISD::FMINNUM, VT, Custom);
985         setOperationAction(ISD::FMAXNUM, VT, Custom);
986 
987         setOperationAction(ISD::FP_ROUND, VT, Custom);
988         setOperationAction(ISD::FP_EXTEND, VT, Custom);
989 
990         setOperationAction(ISD::FTRUNC, VT, Custom);
991         setOperationAction(ISD::FCEIL, VT, Custom);
992         setOperationAction(ISD::FFLOOR, VT, Custom);
993         setOperationAction(ISD::FROUND, VT, Custom);
994 
995         for (auto CC : VFPCCToExpand)
996           setCondCodeAction(CC, VT, Expand);
997 
998         setOperationAction(ISD::VSELECT, VT, Custom);
999         setOperationAction(ISD::SELECT, VT, Custom);
1000         setOperationAction(ISD::SELECT_CC, VT, Expand);
1001 
1002         setOperationAction(ISD::BITCAST, VT, Custom);
1003 
1004         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1005         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1006         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1007         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1008 
1009         for (unsigned VPOpc : FloatingPointVPOps)
1010           setOperationAction(VPOpc, VT, Custom);
1011       }
1012 
1013       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1014       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1015       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1016       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1017       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1018       if (Subtarget.hasStdExtZfh())
1019         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1020       if (Subtarget.hasStdExtF())
1021         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1022       if (Subtarget.hasStdExtD())
1023         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1024     }
1025   }
1026 
1027   // Function alignments.
1028   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1029   setMinFunctionAlignment(FunctionAlignment);
1030   setPrefFunctionAlignment(FunctionAlignment);
1031 
1032   setMinimumJumpTableEntries(5);
1033 
1034   // Jumps are expensive, compared to logic
1035   setJumpIsExpensive();
1036 
1037   setTargetDAGCombine(ISD::ADD);
1038   setTargetDAGCombine(ISD::SUB);
1039   setTargetDAGCombine(ISD::AND);
1040   setTargetDAGCombine(ISD::OR);
1041   setTargetDAGCombine(ISD::XOR);
1042   if (Subtarget.hasStdExtZbp()) {
1043     setTargetDAGCombine(ISD::ROTL);
1044     setTargetDAGCombine(ISD::ROTR);
1045   }
1046   if (Subtarget.hasStdExtZbkb())
1047     setTargetDAGCombine(ISD::BITREVERSE);
1048   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1049   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1050     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1051   if (Subtarget.hasStdExtF()) {
1052     setTargetDAGCombine(ISD::ZERO_EXTEND);
1053     setTargetDAGCombine(ISD::FP_TO_SINT);
1054     setTargetDAGCombine(ISD::FP_TO_UINT);
1055     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1056     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1057   }
1058   if (Subtarget.hasVInstructions()) {
1059     setTargetDAGCombine(ISD::FCOPYSIGN);
1060     setTargetDAGCombine(ISD::MGATHER);
1061     setTargetDAGCombine(ISD::MSCATTER);
1062     setTargetDAGCombine(ISD::VP_GATHER);
1063     setTargetDAGCombine(ISD::VP_SCATTER);
1064     setTargetDAGCombine(ISD::SRA);
1065     setTargetDAGCombine(ISD::SRL);
1066     setTargetDAGCombine(ISD::SHL);
1067     setTargetDAGCombine(ISD::STORE);
1068     setTargetDAGCombine(ISD::SPLAT_VECTOR);
1069   }
1070 
1071   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1072   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1073 }
1074 
1075 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1076                                             LLVMContext &Context,
1077                                             EVT VT) const {
1078   if (!VT.isVector())
1079     return getPointerTy(DL);
1080   if (Subtarget.hasVInstructions() &&
1081       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1082     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1083   return VT.changeVectorElementTypeToInteger();
1084 }
1085 
1086 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1087   return Subtarget.getXLenVT();
1088 }
1089 
1090 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1091                                              const CallInst &I,
1092                                              MachineFunction &MF,
1093                                              unsigned Intrinsic) const {
1094   auto &DL = I.getModule()->getDataLayout();
1095   switch (Intrinsic) {
1096   default:
1097     return false;
1098   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1101   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1102   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1103   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1104   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1105   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1106   case Intrinsic::riscv_masked_cmpxchg_i32:
1107     Info.opc = ISD::INTRINSIC_W_CHAIN;
1108     Info.memVT = MVT::i32;
1109     Info.ptrVal = I.getArgOperand(0);
1110     Info.offset = 0;
1111     Info.align = Align(4);
1112     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1113                  MachineMemOperand::MOVolatile;
1114     return true;
1115   case Intrinsic::riscv_masked_strided_load:
1116     Info.opc = ISD::INTRINSIC_W_CHAIN;
1117     Info.ptrVal = I.getArgOperand(1);
1118     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1119     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1120     Info.size = MemoryLocation::UnknownSize;
1121     Info.flags |= MachineMemOperand::MOLoad;
1122     return true;
1123   case Intrinsic::riscv_masked_strided_store:
1124     Info.opc = ISD::INTRINSIC_VOID;
1125     Info.ptrVal = I.getArgOperand(1);
1126     Info.memVT =
1127         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1128     Info.align = Align(
1129         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1130         8);
1131     Info.size = MemoryLocation::UnknownSize;
1132     Info.flags |= MachineMemOperand::MOStore;
1133     return true;
1134   case Intrinsic::riscv_seg2_load:
1135   case Intrinsic::riscv_seg3_load:
1136   case Intrinsic::riscv_seg4_load:
1137   case Intrinsic::riscv_seg5_load:
1138   case Intrinsic::riscv_seg6_load:
1139   case Intrinsic::riscv_seg7_load:
1140   case Intrinsic::riscv_seg8_load:
1141     Info.opc = ISD::INTRINSIC_W_CHAIN;
1142     Info.ptrVal = I.getArgOperand(0);
1143     Info.memVT =
1144         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1145     Info.align =
1146         Align(DL.getTypeSizeInBits(
1147                   I.getType()->getStructElementType(0)->getScalarType()) /
1148               8);
1149     Info.size = MemoryLocation::UnknownSize;
1150     Info.flags |= MachineMemOperand::MOLoad;
1151     return true;
1152   }
1153 }
1154 
1155 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1156                                                 const AddrMode &AM, Type *Ty,
1157                                                 unsigned AS,
1158                                                 Instruction *I) const {
1159   // No global is ever allowed as a base.
1160   if (AM.BaseGV)
1161     return false;
1162 
1163   // Require a 12-bit signed offset.
1164   if (!isInt<12>(AM.BaseOffs))
1165     return false;
1166 
1167   switch (AM.Scale) {
1168   case 0: // "r+i" or just "i", depending on HasBaseReg.
1169     break;
1170   case 1:
1171     if (!AM.HasBaseReg) // allow "r+i".
1172       break;
1173     return false; // disallow "r+r" or "r+r+i".
1174   default:
1175     return false;
1176   }
1177 
1178   return true;
1179 }
1180 
1181 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1182   return isInt<12>(Imm);
1183 }
1184 
1185 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1186   return isInt<12>(Imm);
1187 }
1188 
1189 // On RV32, 64-bit integers are split into their high and low parts and held
1190 // in two different registers, so the trunc is free since the low register can
1191 // just be used.
1192 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1193   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1194     return false;
1195   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1196   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1197   return (SrcBits == 64 && DestBits == 32);
1198 }
1199 
1200 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1201   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1202       !SrcVT.isInteger() || !DstVT.isInteger())
1203     return false;
1204   unsigned SrcBits = SrcVT.getSizeInBits();
1205   unsigned DestBits = DstVT.getSizeInBits();
1206   return (SrcBits == 64 && DestBits == 32);
1207 }
1208 
1209 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1210   // Zexts are free if they can be combined with a load.
1211   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1212   // poorly with type legalization of compares preferring sext.
1213   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1214     EVT MemVT = LD->getMemoryVT();
1215     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1216         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1217          LD->getExtensionType() == ISD::ZEXTLOAD))
1218       return true;
1219   }
1220 
1221   return TargetLowering::isZExtFree(Val, VT2);
1222 }
1223 
1224 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1225   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1226 }
1227 
1228 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1229   return Subtarget.hasStdExtZbb();
1230 }
1231 
1232 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1233   return Subtarget.hasStdExtZbb();
1234 }
1235 
1236 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1237   EVT VT = Y.getValueType();
1238 
1239   // FIXME: Support vectors once we have tests.
1240   if (VT.isVector())
1241     return false;
1242 
1243   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1244           Subtarget.hasStdExtZbkb()) &&
1245          !isa<ConstantSDNode>(Y);
1246 }
1247 
1248 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1249   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1250   auto *C = dyn_cast<ConstantSDNode>(Y);
1251   return C && C->getAPIntValue().ule(10);
1252 }
1253 
1254 /// Check if sinking \p I's operands to I's basic block is profitable, because
1255 /// the operands can be folded into a target instruction, e.g.
1256 /// splats of scalars can fold into vector instructions.
1257 bool RISCVTargetLowering::shouldSinkOperands(
1258     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1259   using namespace llvm::PatternMatch;
1260 
1261   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1262     return false;
1263 
1264   auto IsSinker = [&](Instruction *I, int Operand) {
1265     switch (I->getOpcode()) {
1266     case Instruction::Add:
1267     case Instruction::Sub:
1268     case Instruction::Mul:
1269     case Instruction::And:
1270     case Instruction::Or:
1271     case Instruction::Xor:
1272     case Instruction::FAdd:
1273     case Instruction::FSub:
1274     case Instruction::FMul:
1275     case Instruction::FDiv:
1276     case Instruction::ICmp:
1277     case Instruction::FCmp:
1278       return true;
1279     case Instruction::Shl:
1280     case Instruction::LShr:
1281     case Instruction::AShr:
1282     case Instruction::UDiv:
1283     case Instruction::SDiv:
1284     case Instruction::URem:
1285     case Instruction::SRem:
1286       return Operand == 1;
1287     case Instruction::Call:
1288       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1289         switch (II->getIntrinsicID()) {
1290         case Intrinsic::fma:
1291         case Intrinsic::vp_fma:
1292           return Operand == 0 || Operand == 1;
1293         // FIXME: Our patterns can only match vx/vf instructions when the splat
1294         // it on the RHS, because TableGen doesn't recognize our VP operations
1295         // as commutative.
1296         case Intrinsic::vp_add:
1297         case Intrinsic::vp_mul:
1298         case Intrinsic::vp_and:
1299         case Intrinsic::vp_or:
1300         case Intrinsic::vp_xor:
1301         case Intrinsic::vp_fadd:
1302         case Intrinsic::vp_fmul:
1303         case Intrinsic::vp_shl:
1304         case Intrinsic::vp_lshr:
1305         case Intrinsic::vp_ashr:
1306         case Intrinsic::vp_udiv:
1307         case Intrinsic::vp_sdiv:
1308         case Intrinsic::vp_urem:
1309         case Intrinsic::vp_srem:
1310           return Operand == 1;
1311         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1312         // explicit patterns for both LHS and RHS (as 'vr' versions).
1313         case Intrinsic::vp_sub:
1314         case Intrinsic::vp_fsub:
1315         case Intrinsic::vp_fdiv:
1316           return Operand == 0 || Operand == 1;
1317         default:
1318           return false;
1319         }
1320       }
1321       return false;
1322     default:
1323       return false;
1324     }
1325   };
1326 
1327   for (auto OpIdx : enumerate(I->operands())) {
1328     if (!IsSinker(I, OpIdx.index()))
1329       continue;
1330 
1331     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1332     // Make sure we are not already sinking this operand
1333     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1334       continue;
1335 
1336     // We are looking for a splat that can be sunk.
1337     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1338                              m_Undef(), m_ZeroMask())))
1339       continue;
1340 
1341     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1342     // and vector registers
1343     for (Use &U : Op->uses()) {
1344       Instruction *Insn = cast<Instruction>(U.getUser());
1345       if (!IsSinker(Insn, U.getOperandNo()))
1346         return false;
1347     }
1348 
1349     Ops.push_back(&Op->getOperandUse(0));
1350     Ops.push_back(&OpIdx.value());
1351   }
1352   return true;
1353 }
1354 
1355 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1356                                        bool ForCodeSize) const {
1357   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1358   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1359     return false;
1360   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1361     return false;
1362   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1363     return false;
1364   return Imm.isZero();
1365 }
1366 
1367 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1368   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1369          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1370          (VT == MVT::f64 && Subtarget.hasStdExtD());
1371 }
1372 
1373 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(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 MVT::f32;
1381 
1382   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1383 }
1384 
1385 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1386                                                            CallingConv::ID CC,
1387                                                            EVT VT) const {
1388   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1389   // We might still end up using a GPR but that will be decided based on ABI.
1390   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1391   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1392     return 1;
1393 
1394   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1395 }
1396 
1397 // Changes the condition code and swaps operands if necessary, so the SetCC
1398 // operation matches one of the comparisons supported directly by branches
1399 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1400 // with 1/-1.
1401 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1402                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1403   // Convert X > -1 to X >= 0.
1404   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1405     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1406     CC = ISD::SETGE;
1407     return;
1408   }
1409   // Convert X < 1 to 0 >= X.
1410   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1411     RHS = LHS;
1412     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1413     CC = ISD::SETGE;
1414     return;
1415   }
1416 
1417   switch (CC) {
1418   default:
1419     break;
1420   case ISD::SETGT:
1421   case ISD::SETLE:
1422   case ISD::SETUGT:
1423   case ISD::SETULE:
1424     CC = ISD::getSetCCSwappedOperands(CC);
1425     std::swap(LHS, RHS);
1426     break;
1427   }
1428 }
1429 
1430 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1431   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1432   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1433   if (VT.getVectorElementType() == MVT::i1)
1434     KnownSize *= 8;
1435 
1436   switch (KnownSize) {
1437   default:
1438     llvm_unreachable("Invalid LMUL.");
1439   case 8:
1440     return RISCVII::VLMUL::LMUL_F8;
1441   case 16:
1442     return RISCVII::VLMUL::LMUL_F4;
1443   case 32:
1444     return RISCVII::VLMUL::LMUL_F2;
1445   case 64:
1446     return RISCVII::VLMUL::LMUL_1;
1447   case 128:
1448     return RISCVII::VLMUL::LMUL_2;
1449   case 256:
1450     return RISCVII::VLMUL::LMUL_4;
1451   case 512:
1452     return RISCVII::VLMUL::LMUL_8;
1453   }
1454 }
1455 
1456 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1457   switch (LMul) {
1458   default:
1459     llvm_unreachable("Invalid LMUL.");
1460   case RISCVII::VLMUL::LMUL_F8:
1461   case RISCVII::VLMUL::LMUL_F4:
1462   case RISCVII::VLMUL::LMUL_F2:
1463   case RISCVII::VLMUL::LMUL_1:
1464     return RISCV::VRRegClassID;
1465   case RISCVII::VLMUL::LMUL_2:
1466     return RISCV::VRM2RegClassID;
1467   case RISCVII::VLMUL::LMUL_4:
1468     return RISCV::VRM4RegClassID;
1469   case RISCVII::VLMUL::LMUL_8:
1470     return RISCV::VRM8RegClassID;
1471   }
1472 }
1473 
1474 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1475   RISCVII::VLMUL LMUL = getLMUL(VT);
1476   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1477       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1478       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1479       LMUL == RISCVII::VLMUL::LMUL_1) {
1480     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1481                   "Unexpected subreg numbering");
1482     return RISCV::sub_vrm1_0 + Index;
1483   }
1484   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1485     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1486                   "Unexpected subreg numbering");
1487     return RISCV::sub_vrm2_0 + Index;
1488   }
1489   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1490     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1491                   "Unexpected subreg numbering");
1492     return RISCV::sub_vrm4_0 + Index;
1493   }
1494   llvm_unreachable("Invalid vector type.");
1495 }
1496 
1497 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1498   if (VT.getVectorElementType() == MVT::i1)
1499     return RISCV::VRRegClassID;
1500   return getRegClassIDForLMUL(getLMUL(VT));
1501 }
1502 
1503 // Attempt to decompose a subvector insert/extract between VecVT and
1504 // SubVecVT via subregister indices. Returns the subregister index that
1505 // can perform the subvector insert/extract with the given element index, as
1506 // well as the index corresponding to any leftover subvectors that must be
1507 // further inserted/extracted within the register class for SubVecVT.
1508 std::pair<unsigned, unsigned>
1509 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1510     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1511     const RISCVRegisterInfo *TRI) {
1512   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1513                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1514                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1515                 "Register classes not ordered");
1516   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1517   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1518   // Try to compose a subregister index that takes us from the incoming
1519   // LMUL>1 register class down to the outgoing one. At each step we half
1520   // the LMUL:
1521   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1522   // Note that this is not guaranteed to find a subregister index, such as
1523   // when we are extracting from one VR type to another.
1524   unsigned SubRegIdx = RISCV::NoSubRegister;
1525   for (const unsigned RCID :
1526        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1527     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1528       VecVT = VecVT.getHalfNumVectorElementsVT();
1529       bool IsHi =
1530           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1531       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1532                                             getSubregIndexByMVT(VecVT, IsHi));
1533       if (IsHi)
1534         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1535     }
1536   return {SubRegIdx, InsertExtractIdx};
1537 }
1538 
1539 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1540 // stores for those types.
1541 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1542   return !Subtarget.useRVVForFixedLengthVectors() ||
1543          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1544 }
1545 
1546 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1547   if (ScalarTy->isPointerTy())
1548     return true;
1549 
1550   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1551       ScalarTy->isIntegerTy(32))
1552     return true;
1553 
1554   if (ScalarTy->isIntegerTy(64))
1555     return Subtarget.hasVInstructionsI64();
1556 
1557   if (ScalarTy->isHalfTy())
1558     return Subtarget.hasVInstructionsF16();
1559   if (ScalarTy->isFloatTy())
1560     return Subtarget.hasVInstructionsF32();
1561   if (ScalarTy->isDoubleTy())
1562     return Subtarget.hasVInstructionsF64();
1563 
1564   return false;
1565 }
1566 
1567 static SDValue getVLOperand(SDValue Op) {
1568   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1569           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1570          "Unexpected opcode");
1571   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1572   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1573   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1574       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1575   if (!II)
1576     return SDValue();
1577   return Op.getOperand(II->VLOperand + 1 + HasChain);
1578 }
1579 
1580 static bool useRVVForFixedLengthVectorVT(MVT VT,
1581                                          const RISCVSubtarget &Subtarget) {
1582   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1583   if (!Subtarget.useRVVForFixedLengthVectors())
1584     return false;
1585 
1586   // We only support a set of vector types with a consistent maximum fixed size
1587   // across all supported vector element types to avoid legalization issues.
1588   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1589   // fixed-length vector type we support is 1024 bytes.
1590   if (VT.getFixedSizeInBits() > 1024 * 8)
1591     return false;
1592 
1593   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1594 
1595   MVT EltVT = VT.getVectorElementType();
1596 
1597   // Don't use RVV for vectors we cannot scalarize if required.
1598   switch (EltVT.SimpleTy) {
1599   // i1 is supported but has different rules.
1600   default:
1601     return false;
1602   case MVT::i1:
1603     // Masks can only use a single register.
1604     if (VT.getVectorNumElements() > MinVLen)
1605       return false;
1606     MinVLen /= 8;
1607     break;
1608   case MVT::i8:
1609   case MVT::i16:
1610   case MVT::i32:
1611     break;
1612   case MVT::i64:
1613     if (!Subtarget.hasVInstructionsI64())
1614       return false;
1615     break;
1616   case MVT::f16:
1617     if (!Subtarget.hasVInstructionsF16())
1618       return false;
1619     break;
1620   case MVT::f32:
1621     if (!Subtarget.hasVInstructionsF32())
1622       return false;
1623     break;
1624   case MVT::f64:
1625     if (!Subtarget.hasVInstructionsF64())
1626       return false;
1627     break;
1628   }
1629 
1630   // Reject elements larger than ELEN.
1631   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1632     return false;
1633 
1634   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1635   // Don't use RVV for types that don't fit.
1636   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1637     return false;
1638 
1639   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1640   // the base fixed length RVV support in place.
1641   if (!VT.isPow2VectorType())
1642     return false;
1643 
1644   return true;
1645 }
1646 
1647 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1648   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1649 }
1650 
1651 // Return the largest legal scalable vector type that matches VT's element type.
1652 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1653                                             const RISCVSubtarget &Subtarget) {
1654   // This may be called before legal types are setup.
1655   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1656           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1657          "Expected legal fixed length vector!");
1658 
1659   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1660   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1661 
1662   MVT EltVT = VT.getVectorElementType();
1663   switch (EltVT.SimpleTy) {
1664   default:
1665     llvm_unreachable("unexpected element type for RVV container");
1666   case MVT::i1:
1667   case MVT::i8:
1668   case MVT::i16:
1669   case MVT::i32:
1670   case MVT::i64:
1671   case MVT::f16:
1672   case MVT::f32:
1673   case MVT::f64: {
1674     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1675     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1676     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1677     unsigned NumElts =
1678         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1679     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1680     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1681     return MVT::getScalableVectorVT(EltVT, NumElts);
1682   }
1683   }
1684 }
1685 
1686 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1687                                             const RISCVSubtarget &Subtarget) {
1688   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1689                                           Subtarget);
1690 }
1691 
1692 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1693   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1694 }
1695 
1696 // Grow V to consume an entire RVV register.
1697 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1698                                        const RISCVSubtarget &Subtarget) {
1699   assert(VT.isScalableVector() &&
1700          "Expected to convert into a scalable vector!");
1701   assert(V.getValueType().isFixedLengthVector() &&
1702          "Expected a fixed length vector operand!");
1703   SDLoc DL(V);
1704   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1705   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1706 }
1707 
1708 // Shrink V so it's just big enough to maintain a VT's worth of data.
1709 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1710                                          const RISCVSubtarget &Subtarget) {
1711   assert(VT.isFixedLengthVector() &&
1712          "Expected to convert into a fixed length vector!");
1713   assert(V.getValueType().isScalableVector() &&
1714          "Expected a scalable vector operand!");
1715   SDLoc DL(V);
1716   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1717   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1718 }
1719 
1720 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1721 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1722 // the vector type that it is contained in.
1723 static std::pair<SDValue, SDValue>
1724 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1725                 const RISCVSubtarget &Subtarget) {
1726   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1727   MVT XLenVT = Subtarget.getXLenVT();
1728   SDValue VL = VecVT.isFixedLengthVector()
1729                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1730                    : DAG.getRegister(RISCV::X0, XLenVT);
1731   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1732   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1733   return {Mask, VL};
1734 }
1735 
1736 // As above but assuming the given type is a scalable vector type.
1737 static std::pair<SDValue, SDValue>
1738 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1739                         const RISCVSubtarget &Subtarget) {
1740   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1741   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1742 }
1743 
1744 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1745 // of either is (currently) supported. This can get us into an infinite loop
1746 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1747 // as a ..., etc.
1748 // Until either (or both) of these can reliably lower any node, reporting that
1749 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1750 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1751 // which is not desirable.
1752 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1753     EVT VT, unsigned DefinedValues) const {
1754   return false;
1755 }
1756 
1757 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1758                                   const RISCVSubtarget &Subtarget) {
1759   // RISCV FP-to-int conversions saturate to the destination register size, but
1760   // don't produce 0 for nan. We can use a conversion instruction and fix the
1761   // nan case with a compare and a select.
1762   SDValue Src = Op.getOperand(0);
1763 
1764   EVT DstVT = Op.getValueType();
1765   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1766 
1767   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1768   unsigned Opc;
1769   if (SatVT == DstVT)
1770     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1771   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1772     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1773   else
1774     return SDValue();
1775   // FIXME: Support other SatVTs by clamping before or after the conversion.
1776 
1777   SDLoc DL(Op);
1778   SDValue FpToInt = DAG.getNode(
1779       Opc, DL, DstVT, Src,
1780       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1781 
1782   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1783   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1784 }
1785 
1786 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1787 // and back. Taking care to avoid converting values that are nan or already
1788 // correct.
1789 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1790 // have FRM dependencies modeled yet.
1791 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1792   MVT VT = Op.getSimpleValueType();
1793   assert(VT.isVector() && "Unexpected type");
1794 
1795   SDLoc DL(Op);
1796 
1797   // Freeze the source since we are increasing the number of uses.
1798   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1799 
1800   // Truncate to integer and convert back to FP.
1801   MVT IntVT = VT.changeVectorElementTypeToInteger();
1802   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1803   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1804 
1805   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1806 
1807   if (Op.getOpcode() == ISD::FCEIL) {
1808     // If the truncated value is the greater than or equal to the original
1809     // value, we've computed the ceil. Otherwise, we went the wrong way and
1810     // need to increase by 1.
1811     // FIXME: This should use a masked operation. Handle here or in isel?
1812     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1813                                  DAG.getConstantFP(1.0, DL, VT));
1814     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1815     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1816   } else if (Op.getOpcode() == ISD::FFLOOR) {
1817     // If the truncated value is the less than or equal to the original value,
1818     // we've computed the floor. Otherwise, we went the wrong way and need to
1819     // decrease by 1.
1820     // FIXME: This should use a masked operation. Handle here or in isel?
1821     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1822                                  DAG.getConstantFP(1.0, DL, VT));
1823     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1824     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1825   }
1826 
1827   // Restore the original sign so that -0.0 is preserved.
1828   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1829 
1830   // Determine the largest integer that can be represented exactly. This and
1831   // values larger than it don't have any fractional bits so don't need to
1832   // be converted.
1833   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1834   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1835   APFloat MaxVal = APFloat(FltSem);
1836   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1837                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1838   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1839 
1840   // If abs(Src) was larger than MaxVal or nan, keep it.
1841   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1842   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1843   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1844 }
1845 
1846 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1847 // This mode isn't supported in vector hardware on RISCV. But as long as we
1848 // aren't compiling with trapping math, we can emulate this with
1849 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1850 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1851 // dependencies modeled yet.
1852 // FIXME: Use masked operations to avoid final merge.
1853 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1854   MVT VT = Op.getSimpleValueType();
1855   assert(VT.isVector() && "Unexpected type");
1856 
1857   SDLoc DL(Op);
1858 
1859   // Freeze the source since we are increasing the number of uses.
1860   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1861 
1862   // We do the conversion on the absolute value and fix the sign at the end.
1863   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1864 
1865   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1866   bool Ignored;
1867   APFloat Point5Pred = APFloat(0.5f);
1868   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1869   Point5Pred.next(/*nextDown*/ true);
1870 
1871   // Add the adjustment.
1872   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1873                                DAG.getConstantFP(Point5Pred, DL, VT));
1874 
1875   // Truncate to integer and convert back to fp.
1876   MVT IntVT = VT.changeVectorElementTypeToInteger();
1877   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1878   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1879 
1880   // Restore the original sign.
1881   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1882 
1883   // Determine the largest integer that can be represented exactly. This and
1884   // values larger than it don't have any fractional bits so don't need to
1885   // be converted.
1886   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1887   APFloat MaxVal = APFloat(FltSem);
1888   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1889                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1890   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1891 
1892   // If abs(Src) was larger than MaxVal or nan, keep it.
1893   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1894   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1895   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1896 }
1897 
1898 struct VIDSequence {
1899   int64_t StepNumerator;
1900   unsigned StepDenominator;
1901   int64_t Addend;
1902 };
1903 
1904 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1905 // to the (non-zero) step S and start value X. This can be then lowered as the
1906 // RVV sequence (VID * S) + X, for example.
1907 // The step S is represented as an integer numerator divided by a positive
1908 // denominator. Note that the implementation currently only identifies
1909 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1910 // cannot detect 2/3, for example.
1911 // Note that this method will also match potentially unappealing index
1912 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1913 // determine whether this is worth generating code for.
1914 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1915   unsigned NumElts = Op.getNumOperands();
1916   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1917   if (!Op.getValueType().isInteger())
1918     return None;
1919 
1920   Optional<unsigned> SeqStepDenom;
1921   Optional<int64_t> SeqStepNum, SeqAddend;
1922   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1923   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1924   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1925     // Assume undef elements match the sequence; we just have to be careful
1926     // when interpolating across them.
1927     if (Op.getOperand(Idx).isUndef())
1928       continue;
1929     // The BUILD_VECTOR must be all constants.
1930     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1931       return None;
1932 
1933     uint64_t Val = Op.getConstantOperandVal(Idx) &
1934                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1935 
1936     if (PrevElt) {
1937       // Calculate the step since the last non-undef element, and ensure
1938       // it's consistent across the entire sequence.
1939       unsigned IdxDiff = Idx - PrevElt->second;
1940       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1941 
1942       // A zero-value value difference means that we're somewhere in the middle
1943       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1944       // step change before evaluating the sequence.
1945       if (ValDiff != 0) {
1946         int64_t Remainder = ValDiff % IdxDiff;
1947         // Normalize the step if it's greater than 1.
1948         if (Remainder != ValDiff) {
1949           // The difference must cleanly divide the element span.
1950           if (Remainder != 0)
1951             return None;
1952           ValDiff /= IdxDiff;
1953           IdxDiff = 1;
1954         }
1955 
1956         if (!SeqStepNum)
1957           SeqStepNum = ValDiff;
1958         else if (ValDiff != SeqStepNum)
1959           return None;
1960 
1961         if (!SeqStepDenom)
1962           SeqStepDenom = IdxDiff;
1963         else if (IdxDiff != *SeqStepDenom)
1964           return None;
1965       }
1966     }
1967 
1968     // Record and/or check any addend.
1969     if (SeqStepNum && SeqStepDenom) {
1970       uint64_t ExpectedVal =
1971           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1972       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1973       if (!SeqAddend)
1974         SeqAddend = Addend;
1975       else if (SeqAddend != Addend)
1976         return None;
1977     }
1978 
1979     // Record this non-undef element for later.
1980     if (!PrevElt || PrevElt->first != Val)
1981       PrevElt = std::make_pair(Val, Idx);
1982   }
1983   // We need to have logged both a step and an addend for this to count as
1984   // a legal index sequence.
1985   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1986     return None;
1987 
1988   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1989 }
1990 
1991 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1992 // and lower it as a VRGATHER_VX_VL from the source vector.
1993 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1994                                   SelectionDAG &DAG,
1995                                   const RISCVSubtarget &Subtarget) {
1996   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1997     return SDValue();
1998   SDValue Vec = SplatVal.getOperand(0);
1999   // Only perform this optimization on vectors of the same size for simplicity.
2000   if (Vec.getValueType() != VT)
2001     return SDValue();
2002   SDValue Idx = SplatVal.getOperand(1);
2003   // The index must be a legal type.
2004   if (Idx.getValueType() != Subtarget.getXLenVT())
2005     return SDValue();
2006 
2007   MVT ContainerVT = VT;
2008   if (VT.isFixedLengthVector()) {
2009     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2010     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2011   }
2012 
2013   SDValue Mask, VL;
2014   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2015 
2016   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2017                                Idx, Mask, VL);
2018 
2019   if (!VT.isFixedLengthVector())
2020     return Gather;
2021 
2022   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2023 }
2024 
2025 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2026                                  const RISCVSubtarget &Subtarget) {
2027   MVT VT = Op.getSimpleValueType();
2028   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2029 
2030   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2031 
2032   SDLoc DL(Op);
2033   SDValue Mask, VL;
2034   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2035 
2036   MVT XLenVT = Subtarget.getXLenVT();
2037   unsigned NumElts = Op.getNumOperands();
2038 
2039   if (VT.getVectorElementType() == MVT::i1) {
2040     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2041       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2042       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2043     }
2044 
2045     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2046       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2047       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2048     }
2049 
2050     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2051     // scalar integer chunks whose bit-width depends on the number of mask
2052     // bits and XLEN.
2053     // First, determine the most appropriate scalar integer type to use. This
2054     // is at most XLenVT, but may be shrunk to a smaller vector element type
2055     // according to the size of the final vector - use i8 chunks rather than
2056     // XLenVT if we're producing a v8i1. This results in more consistent
2057     // codegen across RV32 and RV64.
2058     unsigned NumViaIntegerBits =
2059         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2060     NumViaIntegerBits = std::min(NumViaIntegerBits,
2061                                  Subtarget.getMaxELENForFixedLengthVectors());
2062     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2063       // If we have to use more than one INSERT_VECTOR_ELT then this
2064       // optimization is likely to increase code size; avoid peforming it in
2065       // such a case. We can use a load from a constant pool in this case.
2066       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2067         return SDValue();
2068       // Now we can create our integer vector type. Note that it may be larger
2069       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2070       MVT IntegerViaVecVT =
2071           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2072                            divideCeil(NumElts, NumViaIntegerBits));
2073 
2074       uint64_t Bits = 0;
2075       unsigned BitPos = 0, IntegerEltIdx = 0;
2076       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2077 
2078       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2079         // Once we accumulate enough bits to fill our scalar type, insert into
2080         // our vector and clear our accumulated data.
2081         if (I != 0 && I % NumViaIntegerBits == 0) {
2082           if (NumViaIntegerBits <= 32)
2083             Bits = SignExtend64(Bits, 32);
2084           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2085           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2086                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2087           Bits = 0;
2088           BitPos = 0;
2089           IntegerEltIdx++;
2090         }
2091         SDValue V = Op.getOperand(I);
2092         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2093         Bits |= ((uint64_t)BitValue << BitPos);
2094       }
2095 
2096       // Insert the (remaining) scalar value into position in our integer
2097       // vector type.
2098       if (NumViaIntegerBits <= 32)
2099         Bits = SignExtend64(Bits, 32);
2100       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2101       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2102                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2103 
2104       if (NumElts < NumViaIntegerBits) {
2105         // If we're producing a smaller vector than our minimum legal integer
2106         // type, bitcast to the equivalent (known-legal) mask type, and extract
2107         // our final mask.
2108         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2109         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2110         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2111                           DAG.getConstant(0, DL, XLenVT));
2112       } else {
2113         // Else we must have produced an integer type with the same size as the
2114         // mask type; bitcast for the final result.
2115         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2116         Vec = DAG.getBitcast(VT, Vec);
2117       }
2118 
2119       return Vec;
2120     }
2121 
2122     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2123     // vector type, we have a legal equivalently-sized i8 type, so we can use
2124     // that.
2125     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2126     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2127 
2128     SDValue WideVec;
2129     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2130       // For a splat, perform a scalar truncate before creating the wider
2131       // vector.
2132       assert(Splat.getValueType() == XLenVT &&
2133              "Unexpected type for i1 splat value");
2134       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2135                           DAG.getConstant(1, DL, XLenVT));
2136       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2137     } else {
2138       SmallVector<SDValue, 8> Ops(Op->op_values());
2139       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2140       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2141       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2142     }
2143 
2144     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2145   }
2146 
2147   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2148     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2149       return Gather;
2150     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2151                                         : RISCVISD::VMV_V_X_VL;
2152     Splat =
2153         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2154     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2155   }
2156 
2157   // Try and match index sequences, which we can lower to the vid instruction
2158   // with optional modifications. An all-undef vector is matched by
2159   // getSplatValue, above.
2160   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2161     int64_t StepNumerator = SimpleVID->StepNumerator;
2162     unsigned StepDenominator = SimpleVID->StepDenominator;
2163     int64_t Addend = SimpleVID->Addend;
2164 
2165     assert(StepNumerator != 0 && "Invalid step");
2166     bool Negate = false;
2167     int64_t SplatStepVal = StepNumerator;
2168     unsigned StepOpcode = ISD::MUL;
2169     if (StepNumerator != 1) {
2170       if (isPowerOf2_64(std::abs(StepNumerator))) {
2171         Negate = StepNumerator < 0;
2172         StepOpcode = ISD::SHL;
2173         SplatStepVal = Log2_64(std::abs(StepNumerator));
2174       }
2175     }
2176 
2177     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2178     // threshold since it's the immediate value many RVV instructions accept.
2179     // There is no vmul.vi instruction so ensure multiply constant can fit in
2180     // a single addi instruction.
2181     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2182          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2183         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2184       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2185       // Convert right out of the scalable type so we can use standard ISD
2186       // nodes for the rest of the computation. If we used scalable types with
2187       // these, we'd lose the fixed-length vector info and generate worse
2188       // vsetvli code.
2189       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2190       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2191           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2192         SDValue SplatStep = DAG.getSplatVector(
2193             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2194         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2195       }
2196       if (StepDenominator != 1) {
2197         SDValue SplatStep = DAG.getSplatVector(
2198             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2199         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2200       }
2201       if (Addend != 0 || Negate) {
2202         SDValue SplatAddend =
2203             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2204         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2205       }
2206       return VID;
2207     }
2208   }
2209 
2210   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2211   // when re-interpreted as a vector with a larger element type. For example,
2212   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2213   // could be instead splat as
2214   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2215   // TODO: This optimization could also work on non-constant splats, but it
2216   // would require bit-manipulation instructions to construct the splat value.
2217   SmallVector<SDValue> Sequence;
2218   unsigned EltBitSize = VT.getScalarSizeInBits();
2219   const auto *BV = cast<BuildVectorSDNode>(Op);
2220   if (VT.isInteger() && EltBitSize < 64 &&
2221       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2222       BV->getRepeatedSequence(Sequence) &&
2223       (Sequence.size() * EltBitSize) <= 64) {
2224     unsigned SeqLen = Sequence.size();
2225     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2226     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2227     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2228             ViaIntVT == MVT::i64) &&
2229            "Unexpected sequence type");
2230 
2231     unsigned EltIdx = 0;
2232     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2233     uint64_t SplatValue = 0;
2234     // Construct the amalgamated value which can be splatted as this larger
2235     // vector type.
2236     for (const auto &SeqV : Sequence) {
2237       if (!SeqV.isUndef())
2238         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2239                        << (EltIdx * EltBitSize));
2240       EltIdx++;
2241     }
2242 
2243     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2244     // achieve better constant materializion.
2245     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2246       SplatValue = SignExtend64(SplatValue, 32);
2247 
2248     // Since we can't introduce illegal i64 types at this stage, we can only
2249     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2250     // way we can use RVV instructions to splat.
2251     assert((ViaIntVT.bitsLE(XLenVT) ||
2252             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2253            "Unexpected bitcast sequence");
2254     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2255       SDValue ViaVL =
2256           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2257       MVT ViaContainerVT =
2258           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2259       SDValue Splat =
2260           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2261                       DAG.getUNDEF(ViaContainerVT),
2262                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2263       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2264       return DAG.getBitcast(VT, Splat);
2265     }
2266   }
2267 
2268   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2269   // which constitute a large proportion of the elements. In such cases we can
2270   // splat a vector with the dominant element and make up the shortfall with
2271   // INSERT_VECTOR_ELTs.
2272   // Note that this includes vectors of 2 elements by association. The
2273   // upper-most element is the "dominant" one, allowing us to use a splat to
2274   // "insert" the upper element, and an insert of the lower element at position
2275   // 0, which improves codegen.
2276   SDValue DominantValue;
2277   unsigned MostCommonCount = 0;
2278   DenseMap<SDValue, unsigned> ValueCounts;
2279   unsigned NumUndefElts =
2280       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2281 
2282   // Track the number of scalar loads we know we'd be inserting, estimated as
2283   // any non-zero floating-point constant. Other kinds of element are either
2284   // already in registers or are materialized on demand. The threshold at which
2285   // a vector load is more desirable than several scalar materializion and
2286   // vector-insertion instructions is not known.
2287   unsigned NumScalarLoads = 0;
2288 
2289   for (SDValue V : Op->op_values()) {
2290     if (V.isUndef())
2291       continue;
2292 
2293     ValueCounts.insert(std::make_pair(V, 0));
2294     unsigned &Count = ValueCounts[V];
2295 
2296     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2297       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2298 
2299     // Is this value dominant? In case of a tie, prefer the highest element as
2300     // it's cheaper to insert near the beginning of a vector than it is at the
2301     // end.
2302     if (++Count >= MostCommonCount) {
2303       DominantValue = V;
2304       MostCommonCount = Count;
2305     }
2306   }
2307 
2308   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2309   unsigned NumDefElts = NumElts - NumUndefElts;
2310   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2311 
2312   // Don't perform this optimization when optimizing for size, since
2313   // materializing elements and inserting them tends to cause code bloat.
2314   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2315       ((MostCommonCount > DominantValueCountThreshold) ||
2316        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2317     // Start by splatting the most common element.
2318     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2319 
2320     DenseSet<SDValue> Processed{DominantValue};
2321     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2322     for (const auto &OpIdx : enumerate(Op->ops())) {
2323       const SDValue &V = OpIdx.value();
2324       if (V.isUndef() || !Processed.insert(V).second)
2325         continue;
2326       if (ValueCounts[V] == 1) {
2327         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2328                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2329       } else {
2330         // Blend in all instances of this value using a VSELECT, using a
2331         // mask where each bit signals whether that element is the one
2332         // we're after.
2333         SmallVector<SDValue> Ops;
2334         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2335           return DAG.getConstant(V == V1, DL, XLenVT);
2336         });
2337         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2338                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2339                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2340       }
2341     }
2342 
2343     return Vec;
2344   }
2345 
2346   return SDValue();
2347 }
2348 
2349 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2350                                    SDValue Lo, SDValue Hi, SDValue VL,
2351                                    SelectionDAG &DAG) {
2352   if (!Passthru)
2353     Passthru = DAG.getUNDEF(VT);
2354   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2355     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2356     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2357     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2358     // node in order to try and match RVV vector/scalar instructions.
2359     if ((LoC >> 31) == HiC)
2360       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2361 
2362     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2363     // vmv.v.x whose EEW = 32 to lower it.
2364     auto *Const = dyn_cast<ConstantSDNode>(VL);
2365     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2366       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2367       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2368       // access the subtarget here now.
2369       auto InterVec = DAG.getNode(
2370           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2371                                   DAG.getRegister(RISCV::X0, MVT::i32));
2372       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2373     }
2374   }
2375 
2376   // Fall back to a stack store and stride x0 vector load.
2377   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2378                      Hi, VL);
2379 }
2380 
2381 // Called by type legalization to handle splat of i64 on RV32.
2382 // FIXME: We can optimize this when the type has sign or zero bits in one
2383 // of the halves.
2384 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2385                                    SDValue Scalar, SDValue VL,
2386                                    SelectionDAG &DAG) {
2387   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2388   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2389                            DAG.getConstant(0, DL, MVT::i32));
2390   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2391                            DAG.getConstant(1, DL, MVT::i32));
2392   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2393 }
2394 
2395 // This function lowers a splat of a scalar operand Splat with the vector
2396 // length VL. It ensures the final sequence is type legal, which is useful when
2397 // lowering a splat after type legalization.
2398 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2399                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2400                                 const RISCVSubtarget &Subtarget) {
2401   bool HasPassthru = Passthru && !Passthru.isUndef();
2402   if (!HasPassthru && !Passthru)
2403     Passthru = DAG.getUNDEF(VT);
2404   if (VT.isFloatingPoint()) {
2405     // If VL is 1, we could use vfmv.s.f.
2406     if (isOneConstant(VL))
2407       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2408     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2409   }
2410 
2411   MVT XLenVT = Subtarget.getXLenVT();
2412 
2413   // Simplest case is that the operand needs to be promoted to XLenVT.
2414   if (Scalar.getValueType().bitsLE(XLenVT)) {
2415     // If the operand is a constant, sign extend to increase our chances
2416     // of being able to use a .vi instruction. ANY_EXTEND would become a
2417     // a zero extend and the simm5 check in isel would fail.
2418     // FIXME: Should we ignore the upper bits in isel instead?
2419     unsigned ExtOpc =
2420         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2421     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2422     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2423     // If VL is 1 and the scalar value won't benefit from immediate, we could
2424     // use vmv.s.x.
2425     if (isOneConstant(VL) &&
2426         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2427       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2428     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2429   }
2430 
2431   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2432          "Unexpected scalar for splat lowering!");
2433 
2434   if (isOneConstant(VL) && isNullConstant(Scalar))
2435     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2436                        DAG.getConstant(0, DL, XLenVT), VL);
2437 
2438   // Otherwise use the more complicated splatting algorithm.
2439   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2440 }
2441 
2442 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2443                                 const RISCVSubtarget &Subtarget) {
2444   // We need to be able to widen elements to the next larger integer type.
2445   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2446     return false;
2447 
2448   int Size = Mask.size();
2449   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2450 
2451   int Srcs[] = {-1, -1};
2452   for (int i = 0; i != Size; ++i) {
2453     // Ignore undef elements.
2454     if (Mask[i] < 0)
2455       continue;
2456 
2457     // Is this an even or odd element.
2458     int Pol = i % 2;
2459 
2460     // Ensure we consistently use the same source for this element polarity.
2461     int Src = Mask[i] / Size;
2462     if (Srcs[Pol] < 0)
2463       Srcs[Pol] = Src;
2464     if (Srcs[Pol] != Src)
2465       return false;
2466 
2467     // Make sure the element within the source is appropriate for this element
2468     // in the destination.
2469     int Elt = Mask[i] % Size;
2470     if (Elt != i / 2)
2471       return false;
2472   }
2473 
2474   // We need to find a source for each polarity and they can't be the same.
2475   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2476     return false;
2477 
2478   // Swap the sources if the second source was in the even polarity.
2479   SwapSources = Srcs[0] > Srcs[1];
2480 
2481   return true;
2482 }
2483 
2484 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2485 /// and then extract the original number of elements from the rotated result.
2486 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2487 /// returned rotation amount is for a rotate right, where elements move from
2488 /// higher elements to lower elements. \p LoSrc indicates the first source
2489 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2490 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2491 /// 0 or 1 if a rotation is found.
2492 ///
2493 /// NOTE: We talk about rotate to the right which matches how bit shift and
2494 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2495 /// and the table below write vectors with the lowest elements on the left.
2496 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2497   int Size = Mask.size();
2498 
2499   // We need to detect various ways of spelling a rotation:
2500   //   [11, 12, 13, 14, 15,  0,  1,  2]
2501   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2502   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2503   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2504   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2505   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2506   int Rotation = 0;
2507   LoSrc = -1;
2508   HiSrc = -1;
2509   for (int i = 0; i != Size; ++i) {
2510     int M = Mask[i];
2511     if (M < 0)
2512       continue;
2513 
2514     // Determine where a rotate vector would have started.
2515     int StartIdx = i - (M % Size);
2516     // The identity rotation isn't interesting, stop.
2517     if (StartIdx == 0)
2518       return -1;
2519 
2520     // If we found the tail of a vector the rotation must be the missing
2521     // front. If we found the head of a vector, it must be how much of the
2522     // head.
2523     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2524 
2525     if (Rotation == 0)
2526       Rotation = CandidateRotation;
2527     else if (Rotation != CandidateRotation)
2528       // The rotations don't match, so we can't match this mask.
2529       return -1;
2530 
2531     // Compute which value this mask is pointing at.
2532     int MaskSrc = M < Size ? 0 : 1;
2533 
2534     // Compute which of the two target values this index should be assigned to.
2535     // This reflects whether the high elements are remaining or the low elemnts
2536     // are remaining.
2537     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2538 
2539     // Either set up this value if we've not encountered it before, or check
2540     // that it remains consistent.
2541     if (TargetSrc < 0)
2542       TargetSrc = MaskSrc;
2543     else if (TargetSrc != MaskSrc)
2544       // This may be a rotation, but it pulls from the inputs in some
2545       // unsupported interleaving.
2546       return -1;
2547   }
2548 
2549   // Check that we successfully analyzed the mask, and normalize the results.
2550   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2551   assert((LoSrc >= 0 || HiSrc >= 0) &&
2552          "Failed to find a rotated input vector!");
2553 
2554   return Rotation;
2555 }
2556 
2557 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2558                                    const RISCVSubtarget &Subtarget) {
2559   SDValue V1 = Op.getOperand(0);
2560   SDValue V2 = Op.getOperand(1);
2561   SDLoc DL(Op);
2562   MVT XLenVT = Subtarget.getXLenVT();
2563   MVT VT = Op.getSimpleValueType();
2564   unsigned NumElts = VT.getVectorNumElements();
2565   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2566 
2567   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2568 
2569   SDValue TrueMask, VL;
2570   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2571 
2572   if (SVN->isSplat()) {
2573     const int Lane = SVN->getSplatIndex();
2574     if (Lane >= 0) {
2575       MVT SVT = VT.getVectorElementType();
2576 
2577       // Turn splatted vector load into a strided load with an X0 stride.
2578       SDValue V = V1;
2579       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2580       // with undef.
2581       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2582       int Offset = Lane;
2583       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2584         int OpElements =
2585             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2586         V = V.getOperand(Offset / OpElements);
2587         Offset %= OpElements;
2588       }
2589 
2590       // We need to ensure the load isn't atomic or volatile.
2591       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2592         auto *Ld = cast<LoadSDNode>(V);
2593         Offset *= SVT.getStoreSize();
2594         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2595                                                    TypeSize::Fixed(Offset), DL);
2596 
2597         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2598         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2599           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2600           SDValue IntID =
2601               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2602           SDValue Ops[] = {Ld->getChain(),
2603                            IntID,
2604                            DAG.getUNDEF(ContainerVT),
2605                            NewAddr,
2606                            DAG.getRegister(RISCV::X0, XLenVT),
2607                            VL};
2608           SDValue NewLoad = DAG.getMemIntrinsicNode(
2609               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2610               DAG.getMachineFunction().getMachineMemOperand(
2611                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2612           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2613           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2614         }
2615 
2616         // Otherwise use a scalar load and splat. This will give the best
2617         // opportunity to fold a splat into the operation. ISel can turn it into
2618         // the x0 strided load if we aren't able to fold away the select.
2619         if (SVT.isFloatingPoint())
2620           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2621                           Ld->getPointerInfo().getWithOffset(Offset),
2622                           Ld->getOriginalAlign(),
2623                           Ld->getMemOperand()->getFlags());
2624         else
2625           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2626                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2627                              Ld->getOriginalAlign(),
2628                              Ld->getMemOperand()->getFlags());
2629         DAG.makeEquivalentMemoryOrdering(Ld, V);
2630 
2631         unsigned Opc =
2632             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2633         SDValue Splat =
2634             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2635         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2636       }
2637 
2638       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2639       assert(Lane < (int)NumElts && "Unexpected lane!");
2640       SDValue Gather =
2641           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2642                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2643       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2644     }
2645   }
2646 
2647   ArrayRef<int> Mask = SVN->getMask();
2648 
2649   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2650   // be undef which can be handled with a single SLIDEDOWN/UP.
2651   int LoSrc, HiSrc;
2652   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2653   if (Rotation > 0) {
2654     SDValue LoV, HiV;
2655     if (LoSrc >= 0) {
2656       LoV = LoSrc == 0 ? V1 : V2;
2657       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2658     }
2659     if (HiSrc >= 0) {
2660       HiV = HiSrc == 0 ? V1 : V2;
2661       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2662     }
2663 
2664     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2665     // to slide LoV up by (NumElts - Rotation).
2666     unsigned InvRotate = NumElts - Rotation;
2667 
2668     SDValue Res = DAG.getUNDEF(ContainerVT);
2669     if (HiV) {
2670       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2671       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2672       // causes multiple vsetvlis in some test cases such as lowering
2673       // reduce.mul
2674       SDValue DownVL = VL;
2675       if (LoV)
2676         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2677       Res =
2678           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2679                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2680     }
2681     if (LoV)
2682       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2683                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2684 
2685     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2686   }
2687 
2688   // Detect an interleave shuffle and lower to
2689   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2690   bool SwapSources;
2691   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2692     // Swap sources if needed.
2693     if (SwapSources)
2694       std::swap(V1, V2);
2695 
2696     // Extract the lower half of the vectors.
2697     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2698     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2699                      DAG.getConstant(0, DL, XLenVT));
2700     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2701                      DAG.getConstant(0, DL, XLenVT));
2702 
2703     // Double the element width and halve the number of elements in an int type.
2704     unsigned EltBits = VT.getScalarSizeInBits();
2705     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2706     MVT WideIntVT =
2707         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2708     // Convert this to a scalable vector. We need to base this on the
2709     // destination size to ensure there's always a type with a smaller LMUL.
2710     MVT WideIntContainerVT =
2711         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2712 
2713     // Convert sources to scalable vectors with the same element count as the
2714     // larger type.
2715     MVT HalfContainerVT = MVT::getVectorVT(
2716         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2717     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2718     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2719 
2720     // Cast sources to integer.
2721     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2722     MVT IntHalfVT =
2723         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2724     V1 = DAG.getBitcast(IntHalfVT, V1);
2725     V2 = DAG.getBitcast(IntHalfVT, V2);
2726 
2727     // Freeze V2 since we use it twice and we need to be sure that the add and
2728     // multiply see the same value.
2729     V2 = DAG.getFreeze(V2);
2730 
2731     // Recreate TrueMask using the widened type's element count.
2732     MVT MaskVT =
2733         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2734     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2735 
2736     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2737     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2738                               V2, TrueMask, VL);
2739     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2740     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2741                                      DAG.getUNDEF(IntHalfVT),
2742                                      DAG.getAllOnesConstant(DL, XLenVT));
2743     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2744                                    V2, Multiplier, TrueMask, VL);
2745     // Add the new copies to our previous addition giving us 2^eltbits copies of
2746     // V2. This is equivalent to shifting V2 left by eltbits. This should
2747     // combine with the vwmulu.vv above to form vwmaccu.vv.
2748     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2749                       TrueMask, VL);
2750     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2751     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2752     // vector VT.
2753     ContainerVT =
2754         MVT::getVectorVT(VT.getVectorElementType(),
2755                          WideIntContainerVT.getVectorElementCount() * 2);
2756     Add = DAG.getBitcast(ContainerVT, Add);
2757     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2758   }
2759 
2760   // Detect shuffles which can be re-expressed as vector selects; these are
2761   // shuffles in which each element in the destination is taken from an element
2762   // at the corresponding index in either source vectors.
2763   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2764     int MaskIndex = MaskIdx.value();
2765     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2766   });
2767 
2768   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2769 
2770   SmallVector<SDValue> MaskVals;
2771   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2772   // merged with a second vrgather.
2773   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2774 
2775   // By default we preserve the original operand order, and use a mask to
2776   // select LHS as true and RHS as false. However, since RVV vector selects may
2777   // feature splats but only on the LHS, we may choose to invert our mask and
2778   // instead select between RHS and LHS.
2779   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2780   bool InvertMask = IsSelect == SwapOps;
2781 
2782   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2783   // half.
2784   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2785 
2786   // Now construct the mask that will be used by the vselect or blended
2787   // vrgather operation. For vrgathers, construct the appropriate indices into
2788   // each vector.
2789   for (int MaskIndex : Mask) {
2790     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2791     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2792     if (!IsSelect) {
2793       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2794       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2795                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2796                                      : DAG.getUNDEF(XLenVT));
2797       GatherIndicesRHS.push_back(
2798           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2799                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2800       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2801         ++LHSIndexCounts[MaskIndex];
2802       if (!IsLHSOrUndefIndex)
2803         ++RHSIndexCounts[MaskIndex - NumElts];
2804     }
2805   }
2806 
2807   if (SwapOps) {
2808     std::swap(V1, V2);
2809     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2810   }
2811 
2812   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2813   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2814   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2815 
2816   if (IsSelect)
2817     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2818 
2819   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2820     // On such a large vector we're unable to use i8 as the index type.
2821     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2822     // may involve vector splitting if we're already at LMUL=8, or our
2823     // user-supplied maximum fixed-length LMUL.
2824     return SDValue();
2825   }
2826 
2827   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2828   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2829   MVT IndexVT = VT.changeTypeToInteger();
2830   // Since we can't introduce illegal index types at this stage, use i16 and
2831   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2832   // than XLenVT.
2833   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2834     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2835     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2836   }
2837 
2838   MVT IndexContainerVT =
2839       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2840 
2841   SDValue Gather;
2842   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2843   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2844   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2845     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2846                               Subtarget);
2847   } else {
2848     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2849     // If only one index is used, we can use a "splat" vrgather.
2850     // TODO: We can splat the most-common index and fix-up any stragglers, if
2851     // that's beneficial.
2852     if (LHSIndexCounts.size() == 1) {
2853       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2854       Gather =
2855           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2856                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2857     } else {
2858       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2859       LHSIndices =
2860           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2861 
2862       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2863                            TrueMask, VL);
2864     }
2865   }
2866 
2867   // If a second vector operand is used by this shuffle, blend it in with an
2868   // additional vrgather.
2869   if (!V2.isUndef()) {
2870     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2871     // If only one index is used, we can use a "splat" vrgather.
2872     // TODO: We can splat the most-common index and fix-up any stragglers, if
2873     // that's beneficial.
2874     if (RHSIndexCounts.size() == 1) {
2875       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2876       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2877                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2878     } else {
2879       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2880       RHSIndices =
2881           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2882       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2883                        VL);
2884     }
2885 
2886     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2887     SelectMask =
2888         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2889 
2890     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2891                          Gather, VL);
2892   }
2893 
2894   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2895 }
2896 
2897 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2898   // Support splats for any type. These should type legalize well.
2899   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2900     return true;
2901 
2902   // Only support legal VTs for other shuffles for now.
2903   if (!isTypeLegal(VT))
2904     return false;
2905 
2906   MVT SVT = VT.getSimpleVT();
2907 
2908   bool SwapSources;
2909   int LoSrc, HiSrc;
2910   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2911          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2912 }
2913 
2914 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2915                                      SDLoc DL, SelectionDAG &DAG,
2916                                      const RISCVSubtarget &Subtarget) {
2917   if (VT.isScalableVector())
2918     return DAG.getFPExtendOrRound(Op, DL, VT);
2919   assert(VT.isFixedLengthVector() &&
2920          "Unexpected value type for RVV FP extend/round lowering");
2921   SDValue Mask, VL;
2922   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2923   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2924                         ? RISCVISD::FP_EXTEND_VL
2925                         : RISCVISD::FP_ROUND_VL;
2926   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2927 }
2928 
2929 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2930 // the exponent.
2931 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2932   MVT VT = Op.getSimpleValueType();
2933   unsigned EltSize = VT.getScalarSizeInBits();
2934   SDValue Src = Op.getOperand(0);
2935   SDLoc DL(Op);
2936 
2937   // We need a FP type that can represent the value.
2938   // TODO: Use f16 for i8 when possible?
2939   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2940   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2941 
2942   // Legal types should have been checked in the RISCVTargetLowering
2943   // constructor.
2944   // TODO: Splitting may make sense in some cases.
2945   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2946          "Expected legal float type!");
2947 
2948   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2949   // The trailing zero count is equal to log2 of this single bit value.
2950   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2951     SDValue Neg =
2952         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2953     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2954   }
2955 
2956   // We have a legal FP type, convert to it.
2957   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2958   // Bitcast to integer and shift the exponent to the LSB.
2959   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2960   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2961   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2962   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2963                               DAG.getConstant(ShiftAmt, DL, IntVT));
2964   // Truncate back to original type to allow vnsrl.
2965   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2966   // The exponent contains log2 of the value in biased form.
2967   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2968 
2969   // For trailing zeros, we just need to subtract the bias.
2970   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2971     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2972                        DAG.getConstant(ExponentBias, DL, VT));
2973 
2974   // For leading zeros, we need to remove the bias and convert from log2 to
2975   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2976   unsigned Adjust = ExponentBias + (EltSize - 1);
2977   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2978 }
2979 
2980 // While RVV has alignment restrictions, we should always be able to load as a
2981 // legal equivalently-sized byte-typed vector instead. This method is
2982 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2983 // the load is already correctly-aligned, it returns SDValue().
2984 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2985                                                     SelectionDAG &DAG) const {
2986   auto *Load = cast<LoadSDNode>(Op);
2987   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2988 
2989   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2990                                      Load->getMemoryVT(),
2991                                      *Load->getMemOperand()))
2992     return SDValue();
2993 
2994   SDLoc DL(Op);
2995   MVT VT = Op.getSimpleValueType();
2996   unsigned EltSizeBits = VT.getScalarSizeInBits();
2997   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2998          "Unexpected unaligned RVV load type");
2999   MVT NewVT =
3000       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3001   assert(NewVT.isValid() &&
3002          "Expecting equally-sized RVV vector types to be legal");
3003   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3004                           Load->getPointerInfo(), Load->getOriginalAlign(),
3005                           Load->getMemOperand()->getFlags());
3006   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3007 }
3008 
3009 // While RVV has alignment restrictions, we should always be able to store as a
3010 // legal equivalently-sized byte-typed vector instead. This method is
3011 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3012 // returns SDValue() if the store is already correctly aligned.
3013 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3014                                                      SelectionDAG &DAG) const {
3015   auto *Store = cast<StoreSDNode>(Op);
3016   assert(Store && Store->getValue().getValueType().isVector() &&
3017          "Expected vector store");
3018 
3019   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3020                                      Store->getMemoryVT(),
3021                                      *Store->getMemOperand()))
3022     return SDValue();
3023 
3024   SDLoc DL(Op);
3025   SDValue StoredVal = Store->getValue();
3026   MVT VT = StoredVal.getSimpleValueType();
3027   unsigned EltSizeBits = VT.getScalarSizeInBits();
3028   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3029          "Unexpected unaligned RVV store type");
3030   MVT NewVT =
3031       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3032   assert(NewVT.isValid() &&
3033          "Expecting equally-sized RVV vector types to be legal");
3034   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3035   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3036                       Store->getPointerInfo(), Store->getOriginalAlign(),
3037                       Store->getMemOperand()->getFlags());
3038 }
3039 
3040 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3041                                             SelectionDAG &DAG) const {
3042   switch (Op.getOpcode()) {
3043   default:
3044     report_fatal_error("unimplemented operand");
3045   case ISD::GlobalAddress:
3046     return lowerGlobalAddress(Op, DAG);
3047   case ISD::BlockAddress:
3048     return lowerBlockAddress(Op, DAG);
3049   case ISD::ConstantPool:
3050     return lowerConstantPool(Op, DAG);
3051   case ISD::JumpTable:
3052     return lowerJumpTable(Op, DAG);
3053   case ISD::GlobalTLSAddress:
3054     return lowerGlobalTLSAddress(Op, DAG);
3055   case ISD::SELECT:
3056     return lowerSELECT(Op, DAG);
3057   case ISD::BRCOND:
3058     return lowerBRCOND(Op, DAG);
3059   case ISD::VASTART:
3060     return lowerVASTART(Op, DAG);
3061   case ISD::FRAMEADDR:
3062     return lowerFRAMEADDR(Op, DAG);
3063   case ISD::RETURNADDR:
3064     return lowerRETURNADDR(Op, DAG);
3065   case ISD::SHL_PARTS:
3066     return lowerShiftLeftParts(Op, DAG);
3067   case ISD::SRA_PARTS:
3068     return lowerShiftRightParts(Op, DAG, true);
3069   case ISD::SRL_PARTS:
3070     return lowerShiftRightParts(Op, DAG, false);
3071   case ISD::BITCAST: {
3072     SDLoc DL(Op);
3073     EVT VT = Op.getValueType();
3074     SDValue Op0 = Op.getOperand(0);
3075     EVT Op0VT = Op0.getValueType();
3076     MVT XLenVT = Subtarget.getXLenVT();
3077     if (VT.isFixedLengthVector()) {
3078       // We can handle fixed length vector bitcasts with a simple replacement
3079       // in isel.
3080       if (Op0VT.isFixedLengthVector())
3081         return Op;
3082       // When bitcasting from scalar to fixed-length vector, insert the scalar
3083       // into a one-element vector of the result type, and perform a vector
3084       // bitcast.
3085       if (!Op0VT.isVector()) {
3086         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3087         if (!isTypeLegal(BVT))
3088           return SDValue();
3089         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3090                                               DAG.getUNDEF(BVT), Op0,
3091                                               DAG.getConstant(0, DL, XLenVT)));
3092       }
3093       return SDValue();
3094     }
3095     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3096     // thus: bitcast the vector to a one-element vector type whose element type
3097     // is the same as the result type, and extract the first element.
3098     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3099       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3100       if (!isTypeLegal(BVT))
3101         return SDValue();
3102       SDValue BVec = DAG.getBitcast(BVT, Op0);
3103       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3104                          DAG.getConstant(0, DL, XLenVT));
3105     }
3106     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3107       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3108       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3109       return FPConv;
3110     }
3111     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3112         Subtarget.hasStdExtF()) {
3113       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3114       SDValue FPConv =
3115           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3116       return FPConv;
3117     }
3118     return SDValue();
3119   }
3120   case ISD::INTRINSIC_WO_CHAIN:
3121     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3122   case ISD::INTRINSIC_W_CHAIN:
3123     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3124   case ISD::INTRINSIC_VOID:
3125     return LowerINTRINSIC_VOID(Op, DAG);
3126   case ISD::BSWAP:
3127   case ISD::BITREVERSE: {
3128     MVT VT = Op.getSimpleValueType();
3129     SDLoc DL(Op);
3130     if (Subtarget.hasStdExtZbp()) {
3131       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3132       // Start with the maximum immediate value which is the bitwidth - 1.
3133       unsigned Imm = VT.getSizeInBits() - 1;
3134       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3135       if (Op.getOpcode() == ISD::BSWAP)
3136         Imm &= ~0x7U;
3137       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3138                          DAG.getConstant(Imm, DL, VT));
3139     }
3140     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3141     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3142     // Expand bitreverse to a bswap(rev8) followed by brev8.
3143     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3144     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3145     // as brev8 by an isel pattern.
3146     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3147                        DAG.getConstant(7, DL, VT));
3148   }
3149   case ISD::FSHL:
3150   case ISD::FSHR: {
3151     MVT VT = Op.getSimpleValueType();
3152     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3153     SDLoc DL(Op);
3154     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3155     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3156     // accidentally setting the extra bit.
3157     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3158     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3159                                 DAG.getConstant(ShAmtWidth, DL, VT));
3160     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3161     // instruction use different orders. fshl will return its first operand for
3162     // shift of zero, fshr will return its second operand. fsl and fsr both
3163     // return rs1 so the ISD nodes need to have different operand orders.
3164     // Shift amount is in rs2.
3165     SDValue Op0 = Op.getOperand(0);
3166     SDValue Op1 = Op.getOperand(1);
3167     unsigned Opc = RISCVISD::FSL;
3168     if (Op.getOpcode() == ISD::FSHR) {
3169       std::swap(Op0, Op1);
3170       Opc = RISCVISD::FSR;
3171     }
3172     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3173   }
3174   case ISD::TRUNCATE: {
3175     SDLoc DL(Op);
3176     MVT VT = Op.getSimpleValueType();
3177     // Only custom-lower vector truncates
3178     if (!VT.isVector())
3179       return Op;
3180 
3181     // Truncates to mask types are handled differently
3182     if (VT.getVectorElementType() == MVT::i1)
3183       return lowerVectorMaskTrunc(Op, DAG);
3184 
3185     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3186     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3187     // truncate by one power of two at a time.
3188     MVT DstEltVT = VT.getVectorElementType();
3189 
3190     SDValue Src = Op.getOperand(0);
3191     MVT SrcVT = Src.getSimpleValueType();
3192     MVT SrcEltVT = SrcVT.getVectorElementType();
3193 
3194     assert(DstEltVT.bitsLT(SrcEltVT) &&
3195            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3196            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3197            "Unexpected vector truncate lowering");
3198 
3199     MVT ContainerVT = SrcVT;
3200     if (SrcVT.isFixedLengthVector()) {
3201       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3202       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3203     }
3204 
3205     SDValue Result = Src;
3206     SDValue Mask, VL;
3207     std::tie(Mask, VL) =
3208         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3209     LLVMContext &Context = *DAG.getContext();
3210     const ElementCount Count = ContainerVT.getVectorElementCount();
3211     do {
3212       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3213       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3214       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3215                            Mask, VL);
3216     } while (SrcEltVT != DstEltVT);
3217 
3218     if (SrcVT.isFixedLengthVector())
3219       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3220 
3221     return Result;
3222   }
3223   case ISD::ANY_EXTEND:
3224   case ISD::ZERO_EXTEND:
3225     if (Op.getOperand(0).getValueType().isVector() &&
3226         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3227       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3228     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3229   case ISD::SIGN_EXTEND:
3230     if (Op.getOperand(0).getValueType().isVector() &&
3231         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3232       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3233     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3234   case ISD::SPLAT_VECTOR_PARTS:
3235     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3236   case ISD::INSERT_VECTOR_ELT:
3237     return lowerINSERT_VECTOR_ELT(Op, DAG);
3238   case ISD::EXTRACT_VECTOR_ELT:
3239     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3240   case ISD::VSCALE: {
3241     MVT VT = Op.getSimpleValueType();
3242     SDLoc DL(Op);
3243     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3244     // We define our scalable vector types for lmul=1 to use a 64 bit known
3245     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3246     // vscale as VLENB / 8.
3247     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3248     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3249       report_fatal_error("Support for VLEN==32 is incomplete.");
3250     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3251       // We assume VLENB is a multiple of 8. We manually choose the best shift
3252       // here because SimplifyDemandedBits isn't always able to simplify it.
3253       uint64_t Val = Op.getConstantOperandVal(0);
3254       if (isPowerOf2_64(Val)) {
3255         uint64_t Log2 = Log2_64(Val);
3256         if (Log2 < 3)
3257           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3258                              DAG.getConstant(3 - Log2, DL, VT));
3259         if (Log2 > 3)
3260           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3261                              DAG.getConstant(Log2 - 3, DL, VT));
3262         return VLENB;
3263       }
3264       // If the multiplier is a multiple of 8, scale it down to avoid needing
3265       // to shift the VLENB value.
3266       if ((Val % 8) == 0)
3267         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3268                            DAG.getConstant(Val / 8, DL, VT));
3269     }
3270 
3271     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3272                                  DAG.getConstant(3, DL, VT));
3273     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3274   }
3275   case ISD::FPOWI: {
3276     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3277     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3278     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3279         Op.getOperand(1).getValueType() == MVT::i32) {
3280       SDLoc DL(Op);
3281       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3282       SDValue Powi =
3283           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3284       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3285                          DAG.getIntPtrConstant(0, DL));
3286     }
3287     return SDValue();
3288   }
3289   case ISD::FP_EXTEND: {
3290     // RVV can only do fp_extend to types double the size as the source. We
3291     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3292     // via f32.
3293     SDLoc DL(Op);
3294     MVT VT = Op.getSimpleValueType();
3295     SDValue Src = Op.getOperand(0);
3296     MVT SrcVT = Src.getSimpleValueType();
3297 
3298     // Prepare any fixed-length vector operands.
3299     MVT ContainerVT = VT;
3300     if (SrcVT.isFixedLengthVector()) {
3301       ContainerVT = getContainerForFixedLengthVector(VT);
3302       MVT SrcContainerVT =
3303           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3304       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3305     }
3306 
3307     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3308         SrcVT.getVectorElementType() != MVT::f16) {
3309       // For scalable vectors, we only need to close the gap between
3310       // vXf16->vXf64.
3311       if (!VT.isFixedLengthVector())
3312         return Op;
3313       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3314       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3315       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3316     }
3317 
3318     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3319     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3320     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3321         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3322 
3323     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3324                                            DL, DAG, Subtarget);
3325     if (VT.isFixedLengthVector())
3326       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3327     return Extend;
3328   }
3329   case ISD::FP_ROUND: {
3330     // RVV can only do fp_round to types half the size as the source. We
3331     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3332     // conversion instruction.
3333     SDLoc DL(Op);
3334     MVT VT = Op.getSimpleValueType();
3335     SDValue Src = Op.getOperand(0);
3336     MVT SrcVT = Src.getSimpleValueType();
3337 
3338     // Prepare any fixed-length vector operands.
3339     MVT ContainerVT = VT;
3340     if (VT.isFixedLengthVector()) {
3341       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3342       ContainerVT =
3343           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3344       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3345     }
3346 
3347     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3348         SrcVT.getVectorElementType() != MVT::f64) {
3349       // For scalable vectors, we only need to close the gap between
3350       // vXf64<->vXf16.
3351       if (!VT.isFixedLengthVector())
3352         return Op;
3353       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3354       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3355       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3356     }
3357 
3358     SDValue Mask, VL;
3359     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3360 
3361     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3362     SDValue IntermediateRound =
3363         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3364     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3365                                           DL, DAG, Subtarget);
3366 
3367     if (VT.isFixedLengthVector())
3368       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3369     return Round;
3370   }
3371   case ISD::FP_TO_SINT:
3372   case ISD::FP_TO_UINT:
3373   case ISD::SINT_TO_FP:
3374   case ISD::UINT_TO_FP: {
3375     // RVV can only do fp<->int conversions to types half/double the size as
3376     // the source. We custom-lower any conversions that do two hops into
3377     // sequences.
3378     MVT VT = Op.getSimpleValueType();
3379     if (!VT.isVector())
3380       return Op;
3381     SDLoc DL(Op);
3382     SDValue Src = Op.getOperand(0);
3383     MVT EltVT = VT.getVectorElementType();
3384     MVT SrcVT = Src.getSimpleValueType();
3385     MVT SrcEltVT = SrcVT.getVectorElementType();
3386     unsigned EltSize = EltVT.getSizeInBits();
3387     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3388     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3389            "Unexpected vector element types");
3390 
3391     bool IsInt2FP = SrcEltVT.isInteger();
3392     // Widening conversions
3393     if (EltSize > (2 * SrcEltSize)) {
3394       if (IsInt2FP) {
3395         // Do a regular integer sign/zero extension then convert to float.
3396         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3397                                       VT.getVectorElementCount());
3398         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3399                                  ? ISD::ZERO_EXTEND
3400                                  : ISD::SIGN_EXTEND;
3401         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3402         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3403       }
3404       // FP2Int
3405       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3406       // Do one doubling fp_extend then complete the operation by converting
3407       // to int.
3408       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3409       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3410       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3411     }
3412 
3413     // Narrowing conversions
3414     if (SrcEltSize > (2 * EltSize)) {
3415       if (IsInt2FP) {
3416         // One narrowing int_to_fp, then an fp_round.
3417         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3418         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3419         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3420         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3421       }
3422       // FP2Int
3423       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3424       // representable by the integer, the result is poison.
3425       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3426                                     VT.getVectorElementCount());
3427       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3428       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3429     }
3430 
3431     // Scalable vectors can exit here. Patterns will handle equally-sized
3432     // conversions halving/doubling ones.
3433     if (!VT.isFixedLengthVector())
3434       return Op;
3435 
3436     // For fixed-length vectors we lower to a custom "VL" node.
3437     unsigned RVVOpc = 0;
3438     switch (Op.getOpcode()) {
3439     default:
3440       llvm_unreachable("Impossible opcode");
3441     case ISD::FP_TO_SINT:
3442       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3443       break;
3444     case ISD::FP_TO_UINT:
3445       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3446       break;
3447     case ISD::SINT_TO_FP:
3448       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3449       break;
3450     case ISD::UINT_TO_FP:
3451       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3452       break;
3453     }
3454 
3455     MVT ContainerVT, SrcContainerVT;
3456     // Derive the reference container type from the larger vector type.
3457     if (SrcEltSize > EltSize) {
3458       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3459       ContainerVT =
3460           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3461     } else {
3462       ContainerVT = getContainerForFixedLengthVector(VT);
3463       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3464     }
3465 
3466     SDValue Mask, VL;
3467     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3468 
3469     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3470     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3471     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3472   }
3473   case ISD::FP_TO_SINT_SAT:
3474   case ISD::FP_TO_UINT_SAT:
3475     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3476   case ISD::FTRUNC:
3477   case ISD::FCEIL:
3478   case ISD::FFLOOR:
3479     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3480   case ISD::FROUND:
3481     return lowerFROUND(Op, DAG);
3482   case ISD::VECREDUCE_ADD:
3483   case ISD::VECREDUCE_UMAX:
3484   case ISD::VECREDUCE_SMAX:
3485   case ISD::VECREDUCE_UMIN:
3486   case ISD::VECREDUCE_SMIN:
3487     return lowerVECREDUCE(Op, DAG);
3488   case ISD::VECREDUCE_AND:
3489   case ISD::VECREDUCE_OR:
3490   case ISD::VECREDUCE_XOR:
3491     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3492       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3493     return lowerVECREDUCE(Op, DAG);
3494   case ISD::VECREDUCE_FADD:
3495   case ISD::VECREDUCE_SEQ_FADD:
3496   case ISD::VECREDUCE_FMIN:
3497   case ISD::VECREDUCE_FMAX:
3498     return lowerFPVECREDUCE(Op, DAG);
3499   case ISD::VP_REDUCE_ADD:
3500   case ISD::VP_REDUCE_UMAX:
3501   case ISD::VP_REDUCE_SMAX:
3502   case ISD::VP_REDUCE_UMIN:
3503   case ISD::VP_REDUCE_SMIN:
3504   case ISD::VP_REDUCE_FADD:
3505   case ISD::VP_REDUCE_SEQ_FADD:
3506   case ISD::VP_REDUCE_FMIN:
3507   case ISD::VP_REDUCE_FMAX:
3508     return lowerVPREDUCE(Op, DAG);
3509   case ISD::VP_REDUCE_AND:
3510   case ISD::VP_REDUCE_OR:
3511   case ISD::VP_REDUCE_XOR:
3512     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3513       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3514     return lowerVPREDUCE(Op, DAG);
3515   case ISD::INSERT_SUBVECTOR:
3516     return lowerINSERT_SUBVECTOR(Op, DAG);
3517   case ISD::EXTRACT_SUBVECTOR:
3518     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3519   case ISD::STEP_VECTOR:
3520     return lowerSTEP_VECTOR(Op, DAG);
3521   case ISD::VECTOR_REVERSE:
3522     return lowerVECTOR_REVERSE(Op, DAG);
3523   case ISD::VECTOR_SPLICE:
3524     return lowerVECTOR_SPLICE(Op, DAG);
3525   case ISD::BUILD_VECTOR:
3526     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3527   case ISD::SPLAT_VECTOR:
3528     if (Op.getValueType().getVectorElementType() == MVT::i1)
3529       return lowerVectorMaskSplat(Op, DAG);
3530     return SDValue();
3531   case ISD::VECTOR_SHUFFLE:
3532     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3533   case ISD::CONCAT_VECTORS: {
3534     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3535     // better than going through the stack, as the default expansion does.
3536     SDLoc DL(Op);
3537     MVT VT = Op.getSimpleValueType();
3538     unsigned NumOpElts =
3539         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3540     SDValue Vec = DAG.getUNDEF(VT);
3541     for (const auto &OpIdx : enumerate(Op->ops())) {
3542       SDValue SubVec = OpIdx.value();
3543       // Don't insert undef subvectors.
3544       if (SubVec.isUndef())
3545         continue;
3546       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3547                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3548     }
3549     return Vec;
3550   }
3551   case ISD::LOAD:
3552     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3553       return V;
3554     if (Op.getValueType().isFixedLengthVector())
3555       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3556     return Op;
3557   case ISD::STORE:
3558     if (auto V = expandUnalignedRVVStore(Op, DAG))
3559       return V;
3560     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3561       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3562     return Op;
3563   case ISD::MLOAD:
3564   case ISD::VP_LOAD:
3565     return lowerMaskedLoad(Op, DAG);
3566   case ISD::MSTORE:
3567   case ISD::VP_STORE:
3568     return lowerMaskedStore(Op, DAG);
3569   case ISD::SETCC:
3570     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3571   case ISD::ADD:
3572     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3573   case ISD::SUB:
3574     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3575   case ISD::MUL:
3576     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3577   case ISD::MULHS:
3578     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3579   case ISD::MULHU:
3580     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3581   case ISD::AND:
3582     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3583                                               RISCVISD::AND_VL);
3584   case ISD::OR:
3585     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3586                                               RISCVISD::OR_VL);
3587   case ISD::XOR:
3588     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3589                                               RISCVISD::XOR_VL);
3590   case ISD::SDIV:
3591     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3592   case ISD::SREM:
3593     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3594   case ISD::UDIV:
3595     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3596   case ISD::UREM:
3597     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3598   case ISD::SHL:
3599   case ISD::SRA:
3600   case ISD::SRL:
3601     if (Op.getSimpleValueType().isFixedLengthVector())
3602       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3603     // This can be called for an i32 shift amount that needs to be promoted.
3604     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3605            "Unexpected custom legalisation");
3606     return SDValue();
3607   case ISD::SADDSAT:
3608     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3609   case ISD::UADDSAT:
3610     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3611   case ISD::SSUBSAT:
3612     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3613   case ISD::USUBSAT:
3614     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3615   case ISD::FADD:
3616     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3617   case ISD::FSUB:
3618     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3619   case ISD::FMUL:
3620     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3621   case ISD::FDIV:
3622     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3623   case ISD::FNEG:
3624     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3625   case ISD::FABS:
3626     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3627   case ISD::FSQRT:
3628     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3629   case ISD::FMA:
3630     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3631   case ISD::SMIN:
3632     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3633   case ISD::SMAX:
3634     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3635   case ISD::UMIN:
3636     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3637   case ISD::UMAX:
3638     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3639   case ISD::FMINNUM:
3640     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3641   case ISD::FMAXNUM:
3642     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3643   case ISD::ABS:
3644     return lowerABS(Op, DAG);
3645   case ISD::CTLZ_ZERO_UNDEF:
3646   case ISD::CTTZ_ZERO_UNDEF:
3647     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3648   case ISD::VSELECT:
3649     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3650   case ISD::FCOPYSIGN:
3651     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3652   case ISD::MGATHER:
3653   case ISD::VP_GATHER:
3654     return lowerMaskedGather(Op, DAG);
3655   case ISD::MSCATTER:
3656   case ISD::VP_SCATTER:
3657     return lowerMaskedScatter(Op, DAG);
3658   case ISD::FLT_ROUNDS_:
3659     return lowerGET_ROUNDING(Op, DAG);
3660   case ISD::SET_ROUNDING:
3661     return lowerSET_ROUNDING(Op, DAG);
3662   case ISD::VP_SELECT:
3663     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3664   case ISD::VP_MERGE:
3665     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3666   case ISD::VP_ADD:
3667     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3668   case ISD::VP_SUB:
3669     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3670   case ISD::VP_MUL:
3671     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3672   case ISD::VP_SDIV:
3673     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3674   case ISD::VP_UDIV:
3675     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3676   case ISD::VP_SREM:
3677     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3678   case ISD::VP_UREM:
3679     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3680   case ISD::VP_AND:
3681     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3682   case ISD::VP_OR:
3683     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3684   case ISD::VP_XOR:
3685     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3686   case ISD::VP_ASHR:
3687     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3688   case ISD::VP_LSHR:
3689     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3690   case ISD::VP_SHL:
3691     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3692   case ISD::VP_FADD:
3693     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3694   case ISD::VP_FSUB:
3695     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3696   case ISD::VP_FMUL:
3697     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3698   case ISD::VP_FDIV:
3699     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3700   case ISD::VP_FNEG:
3701     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3702   case ISD::VP_FMA:
3703     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3704   case ISD::VP_FPTOSI:
3705     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3706   case ISD::VP_SITOFP:
3707     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3708   }
3709 }
3710 
3711 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3712                              SelectionDAG &DAG, unsigned Flags) {
3713   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3714 }
3715 
3716 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3717                              SelectionDAG &DAG, unsigned Flags) {
3718   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3719                                    Flags);
3720 }
3721 
3722 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3723                              SelectionDAG &DAG, unsigned Flags) {
3724   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3725                                    N->getOffset(), Flags);
3726 }
3727 
3728 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3729                              SelectionDAG &DAG, unsigned Flags) {
3730   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3731 }
3732 
3733 template <class NodeTy>
3734 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3735                                      bool IsLocal) const {
3736   SDLoc DL(N);
3737   EVT Ty = getPointerTy(DAG.getDataLayout());
3738 
3739   if (isPositionIndependent()) {
3740     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3741     if (IsLocal)
3742       // Use PC-relative addressing to access the symbol. This generates the
3743       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3744       // %pcrel_lo(auipc)).
3745       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3746 
3747     // Use PC-relative addressing to access the GOT for this symbol, then load
3748     // the address from the GOT. This generates the pattern (PseudoLA sym),
3749     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3750     SDValue Load =
3751         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3752     MachineFunction &MF = DAG.getMachineFunction();
3753     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3754         MachinePointerInfo::getGOT(MF),
3755         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3756             MachineMemOperand::MOInvariant,
3757         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3758     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3759     return Load;
3760   }
3761 
3762   switch (getTargetMachine().getCodeModel()) {
3763   default:
3764     report_fatal_error("Unsupported code model for lowering");
3765   case CodeModel::Small: {
3766     // Generate a sequence for accessing addresses within the first 2 GiB of
3767     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3768     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3769     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3770     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3771     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3772   }
3773   case CodeModel::Medium: {
3774     // Generate a sequence for accessing addresses within any 2GiB range within
3775     // the address space. This generates the pattern (PseudoLLA sym), which
3776     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3777     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3778     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3779   }
3780   }
3781 }
3782 
3783 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3784     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3785 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3786     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3787 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3788     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3789 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3790     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3791 
3792 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3793                                                 SelectionDAG &DAG) const {
3794   SDLoc DL(Op);
3795   EVT Ty = Op.getValueType();
3796   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3797   int64_t Offset = N->getOffset();
3798   MVT XLenVT = Subtarget.getXLenVT();
3799 
3800   const GlobalValue *GV = N->getGlobal();
3801   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3802   SDValue Addr = getAddr(N, DAG, IsLocal);
3803 
3804   // In order to maximise the opportunity for common subexpression elimination,
3805   // emit a separate ADD node for the global address offset instead of folding
3806   // it in the global address node. Later peephole optimisations may choose to
3807   // fold it back in when profitable.
3808   if (Offset != 0)
3809     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3810                        DAG.getConstant(Offset, DL, XLenVT));
3811   return Addr;
3812 }
3813 
3814 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3815                                                SelectionDAG &DAG) const {
3816   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3817 
3818   return getAddr(N, DAG);
3819 }
3820 
3821 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3822                                                SelectionDAG &DAG) const {
3823   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3824 
3825   return getAddr(N, DAG);
3826 }
3827 
3828 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3829                                             SelectionDAG &DAG) const {
3830   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3831 
3832   return getAddr(N, DAG);
3833 }
3834 
3835 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3836                                               SelectionDAG &DAG,
3837                                               bool UseGOT) const {
3838   SDLoc DL(N);
3839   EVT Ty = getPointerTy(DAG.getDataLayout());
3840   const GlobalValue *GV = N->getGlobal();
3841   MVT XLenVT = Subtarget.getXLenVT();
3842 
3843   if (UseGOT) {
3844     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3845     // load the address from the GOT and add the thread pointer. This generates
3846     // the pattern (PseudoLA_TLS_IE sym), which expands to
3847     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3848     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3849     SDValue Load =
3850         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3851     MachineFunction &MF = DAG.getMachineFunction();
3852     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3853         MachinePointerInfo::getGOT(MF),
3854         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3855             MachineMemOperand::MOInvariant,
3856         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3857     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3858 
3859     // Add the thread pointer.
3860     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3861     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3862   }
3863 
3864   // Generate a sequence for accessing the address relative to the thread
3865   // pointer, with the appropriate adjustment for the thread pointer offset.
3866   // This generates the pattern
3867   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3868   SDValue AddrHi =
3869       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3870   SDValue AddrAdd =
3871       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3872   SDValue AddrLo =
3873       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3874 
3875   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3876   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3877   SDValue MNAdd = SDValue(
3878       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3879       0);
3880   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3881 }
3882 
3883 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3884                                                SelectionDAG &DAG) const {
3885   SDLoc DL(N);
3886   EVT Ty = getPointerTy(DAG.getDataLayout());
3887   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3888   const GlobalValue *GV = N->getGlobal();
3889 
3890   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3891   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3892   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3893   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3894   SDValue Load =
3895       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3896 
3897   // Prepare argument list to generate call.
3898   ArgListTy Args;
3899   ArgListEntry Entry;
3900   Entry.Node = Load;
3901   Entry.Ty = CallTy;
3902   Args.push_back(Entry);
3903 
3904   // Setup call to __tls_get_addr.
3905   TargetLowering::CallLoweringInfo CLI(DAG);
3906   CLI.setDebugLoc(DL)
3907       .setChain(DAG.getEntryNode())
3908       .setLibCallee(CallingConv::C, CallTy,
3909                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3910                     std::move(Args));
3911 
3912   return LowerCallTo(CLI).first;
3913 }
3914 
3915 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3916                                                    SelectionDAG &DAG) const {
3917   SDLoc DL(Op);
3918   EVT Ty = Op.getValueType();
3919   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3920   int64_t Offset = N->getOffset();
3921   MVT XLenVT = Subtarget.getXLenVT();
3922 
3923   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3924 
3925   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3926       CallingConv::GHC)
3927     report_fatal_error("In GHC calling convention TLS is not supported");
3928 
3929   SDValue Addr;
3930   switch (Model) {
3931   case TLSModel::LocalExec:
3932     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3933     break;
3934   case TLSModel::InitialExec:
3935     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3936     break;
3937   case TLSModel::LocalDynamic:
3938   case TLSModel::GeneralDynamic:
3939     Addr = getDynamicTLSAddr(N, DAG);
3940     break;
3941   }
3942 
3943   // In order to maximise the opportunity for common subexpression elimination,
3944   // emit a separate ADD node for the global address offset instead of folding
3945   // it in the global address node. Later peephole optimisations may choose to
3946   // fold it back in when profitable.
3947   if (Offset != 0)
3948     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3949                        DAG.getConstant(Offset, DL, XLenVT));
3950   return Addr;
3951 }
3952 
3953 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3954   SDValue CondV = Op.getOperand(0);
3955   SDValue TrueV = Op.getOperand(1);
3956   SDValue FalseV = Op.getOperand(2);
3957   SDLoc DL(Op);
3958   MVT VT = Op.getSimpleValueType();
3959   MVT XLenVT = Subtarget.getXLenVT();
3960 
3961   // Lower vector SELECTs to VSELECTs by splatting the condition.
3962   if (VT.isVector()) {
3963     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3964     SDValue CondSplat = VT.isScalableVector()
3965                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3966                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3967     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3968   }
3969 
3970   // If the result type is XLenVT and CondV is the output of a SETCC node
3971   // which also operated on XLenVT inputs, then merge the SETCC node into the
3972   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3973   // compare+branch instructions. i.e.:
3974   // (select (setcc lhs, rhs, cc), truev, falsev)
3975   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3976   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3977       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3978     SDValue LHS = CondV.getOperand(0);
3979     SDValue RHS = CondV.getOperand(1);
3980     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3981     ISD::CondCode CCVal = CC->get();
3982 
3983     // Special case for a select of 2 constants that have a diffence of 1.
3984     // Normally this is done by DAGCombine, but if the select is introduced by
3985     // type legalization or op legalization, we miss it. Restricting to SETLT
3986     // case for now because that is what signed saturating add/sub need.
3987     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3988     // but we would probably want to swap the true/false values if the condition
3989     // is SETGE/SETLE to avoid an XORI.
3990     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3991         CCVal == ISD::SETLT) {
3992       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3993       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3994       if (TrueVal - 1 == FalseVal)
3995         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3996       if (TrueVal + 1 == FalseVal)
3997         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3998     }
3999 
4000     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4001 
4002     SDValue TargetCC = DAG.getCondCode(CCVal);
4003     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
4004     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4005   }
4006 
4007   // Otherwise:
4008   // (select condv, truev, falsev)
4009   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
4010   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4011   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
4012 
4013   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
4014 
4015   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4016 }
4017 
4018 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4019   SDValue CondV = Op.getOperand(1);
4020   SDLoc DL(Op);
4021   MVT XLenVT = Subtarget.getXLenVT();
4022 
4023   if (CondV.getOpcode() == ISD::SETCC &&
4024       CondV.getOperand(0).getValueType() == XLenVT) {
4025     SDValue LHS = CondV.getOperand(0);
4026     SDValue RHS = CondV.getOperand(1);
4027     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4028 
4029     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4030 
4031     SDValue TargetCC = DAG.getCondCode(CCVal);
4032     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4033                        LHS, RHS, TargetCC, Op.getOperand(2));
4034   }
4035 
4036   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4037                      CondV, DAG.getConstant(0, DL, XLenVT),
4038                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4039 }
4040 
4041 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4042   MachineFunction &MF = DAG.getMachineFunction();
4043   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4044 
4045   SDLoc DL(Op);
4046   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4047                                  getPointerTy(MF.getDataLayout()));
4048 
4049   // vastart just stores the address of the VarArgsFrameIndex slot into the
4050   // memory location argument.
4051   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4052   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4053                       MachinePointerInfo(SV));
4054 }
4055 
4056 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4057                                             SelectionDAG &DAG) const {
4058   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4059   MachineFunction &MF = DAG.getMachineFunction();
4060   MachineFrameInfo &MFI = MF.getFrameInfo();
4061   MFI.setFrameAddressIsTaken(true);
4062   Register FrameReg = RI.getFrameRegister(MF);
4063   int XLenInBytes = Subtarget.getXLen() / 8;
4064 
4065   EVT VT = Op.getValueType();
4066   SDLoc DL(Op);
4067   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4068   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4069   while (Depth--) {
4070     int Offset = -(XLenInBytes * 2);
4071     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4072                               DAG.getIntPtrConstant(Offset, DL));
4073     FrameAddr =
4074         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4075   }
4076   return FrameAddr;
4077 }
4078 
4079 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4080                                              SelectionDAG &DAG) const {
4081   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4082   MachineFunction &MF = DAG.getMachineFunction();
4083   MachineFrameInfo &MFI = MF.getFrameInfo();
4084   MFI.setReturnAddressIsTaken(true);
4085   MVT XLenVT = Subtarget.getXLenVT();
4086   int XLenInBytes = Subtarget.getXLen() / 8;
4087 
4088   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4089     return SDValue();
4090 
4091   EVT VT = Op.getValueType();
4092   SDLoc DL(Op);
4093   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4094   if (Depth) {
4095     int Off = -XLenInBytes;
4096     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4097     SDValue Offset = DAG.getConstant(Off, DL, VT);
4098     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4099                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4100                        MachinePointerInfo());
4101   }
4102 
4103   // Return the value of the return address register, marking it an implicit
4104   // live-in.
4105   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4106   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4107 }
4108 
4109 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4110                                                  SelectionDAG &DAG) const {
4111   SDLoc DL(Op);
4112   SDValue Lo = Op.getOperand(0);
4113   SDValue Hi = Op.getOperand(1);
4114   SDValue Shamt = Op.getOperand(2);
4115   EVT VT = Lo.getValueType();
4116 
4117   // if Shamt-XLEN < 0: // Shamt < XLEN
4118   //   Lo = Lo << Shamt
4119   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4120   // else:
4121   //   Lo = 0
4122   //   Hi = Lo << (Shamt-XLEN)
4123 
4124   SDValue Zero = DAG.getConstant(0, DL, VT);
4125   SDValue One = DAG.getConstant(1, DL, VT);
4126   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4127   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4128   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4129   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4130 
4131   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4132   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4133   SDValue ShiftRightLo =
4134       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4135   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4136   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4137   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4138 
4139   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4140 
4141   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4142   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4143 
4144   SDValue Parts[2] = {Lo, Hi};
4145   return DAG.getMergeValues(Parts, DL);
4146 }
4147 
4148 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4149                                                   bool IsSRA) const {
4150   SDLoc DL(Op);
4151   SDValue Lo = Op.getOperand(0);
4152   SDValue Hi = Op.getOperand(1);
4153   SDValue Shamt = Op.getOperand(2);
4154   EVT VT = Lo.getValueType();
4155 
4156   // SRA expansion:
4157   //   if Shamt-XLEN < 0: // Shamt < XLEN
4158   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4159   //     Hi = Hi >>s Shamt
4160   //   else:
4161   //     Lo = Hi >>s (Shamt-XLEN);
4162   //     Hi = Hi >>s (XLEN-1)
4163   //
4164   // SRL expansion:
4165   //   if Shamt-XLEN < 0: // Shamt < XLEN
4166   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4167   //     Hi = Hi >>u Shamt
4168   //   else:
4169   //     Lo = Hi >>u (Shamt-XLEN);
4170   //     Hi = 0;
4171 
4172   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4173 
4174   SDValue Zero = DAG.getConstant(0, DL, VT);
4175   SDValue One = DAG.getConstant(1, DL, VT);
4176   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4177   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4178   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4179   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4180 
4181   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4182   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4183   SDValue ShiftLeftHi =
4184       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4185   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4186   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4187   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4188   SDValue HiFalse =
4189       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4190 
4191   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4192 
4193   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4194   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4195 
4196   SDValue Parts[2] = {Lo, Hi};
4197   return DAG.getMergeValues(Parts, DL);
4198 }
4199 
4200 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4201 // legal equivalently-sized i8 type, so we can use that as a go-between.
4202 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4203                                                   SelectionDAG &DAG) const {
4204   SDLoc DL(Op);
4205   MVT VT = Op.getSimpleValueType();
4206   SDValue SplatVal = Op.getOperand(0);
4207   // All-zeros or all-ones splats are handled specially.
4208   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4209     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4210     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4211   }
4212   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4213     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4214     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4215   }
4216   MVT XLenVT = Subtarget.getXLenVT();
4217   assert(SplatVal.getValueType() == XLenVT &&
4218          "Unexpected type for i1 splat value");
4219   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4220   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4221                          DAG.getConstant(1, DL, XLenVT));
4222   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4223   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4224   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4225 }
4226 
4227 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4228 // illegal (currently only vXi64 RV32).
4229 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4230 // them to VMV_V_X_VL.
4231 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4232                                                      SelectionDAG &DAG) const {
4233   SDLoc DL(Op);
4234   MVT VecVT = Op.getSimpleValueType();
4235   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4236          "Unexpected SPLAT_VECTOR_PARTS lowering");
4237 
4238   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4239   SDValue Lo = Op.getOperand(0);
4240   SDValue Hi = Op.getOperand(1);
4241 
4242   if (VecVT.isFixedLengthVector()) {
4243     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4244     SDLoc DL(Op);
4245     SDValue Mask, VL;
4246     std::tie(Mask, VL) =
4247         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4248 
4249     SDValue Res =
4250         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4251     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4252   }
4253 
4254   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4255     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4256     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4257     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4258     // node in order to try and match RVV vector/scalar instructions.
4259     if ((LoC >> 31) == HiC)
4260       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4261                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4262   }
4263 
4264   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4265   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4266       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4267       Hi.getConstantOperandVal(1) == 31)
4268     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4269                        DAG.getRegister(RISCV::X0, MVT::i32));
4270 
4271   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4272   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4273                      DAG.getUNDEF(VecVT), Lo, Hi,
4274                      DAG.getRegister(RISCV::X0, MVT::i32));
4275 }
4276 
4277 // Custom-lower extensions from mask vectors by using a vselect either with 1
4278 // for zero/any-extension or -1 for sign-extension:
4279 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4280 // Note that any-extension is lowered identically to zero-extension.
4281 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4282                                                 int64_t ExtTrueVal) const {
4283   SDLoc DL(Op);
4284   MVT VecVT = Op.getSimpleValueType();
4285   SDValue Src = Op.getOperand(0);
4286   // Only custom-lower extensions from mask types
4287   assert(Src.getValueType().isVector() &&
4288          Src.getValueType().getVectorElementType() == MVT::i1);
4289 
4290   if (VecVT.isScalableVector()) {
4291     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4292     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
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   MVT XLenVT = Subtarget.getXLenVT();
4306   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4307   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4308 
4309   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4310                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4311   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4312                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4313   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4314                                SplatTrueVal, SplatZero, VL);
4315 
4316   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4317 }
4318 
4319 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4320     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4321   MVT ExtVT = Op.getSimpleValueType();
4322   // Only custom-lower extensions from fixed-length vector types.
4323   if (!ExtVT.isFixedLengthVector())
4324     return Op;
4325   MVT VT = Op.getOperand(0).getSimpleValueType();
4326   // Grab the canonical container type for the extended type. Infer the smaller
4327   // type from that to ensure the same number of vector elements, as we know
4328   // the LMUL will be sufficient to hold the smaller type.
4329   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4330   // Get the extended container type manually to ensure the same number of
4331   // vector elements between source and dest.
4332   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4333                                      ContainerExtVT.getVectorElementCount());
4334 
4335   SDValue Op1 =
4336       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4337 
4338   SDLoc DL(Op);
4339   SDValue Mask, VL;
4340   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4341 
4342   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4343 
4344   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4345 }
4346 
4347 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4348 // setcc operation:
4349 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4350 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4351                                                   SelectionDAG &DAG) const {
4352   SDLoc DL(Op);
4353   EVT MaskVT = Op.getValueType();
4354   // Only expect to custom-lower truncations to mask types
4355   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4356          "Unexpected type for vector mask lowering");
4357   SDValue Src = Op.getOperand(0);
4358   MVT VecVT = Src.getSimpleValueType();
4359 
4360   // If this is a fixed vector, we need to convert it to a scalable vector.
4361   MVT ContainerVT = VecVT;
4362   if (VecVT.isFixedLengthVector()) {
4363     ContainerVT = getContainerForFixedLengthVector(VecVT);
4364     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4365   }
4366 
4367   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4368   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4369 
4370   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4371                          DAG.getUNDEF(ContainerVT), SplatOne);
4372   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4373                           DAG.getUNDEF(ContainerVT), SplatZero);
4374 
4375   if (VecVT.isScalableVector()) {
4376     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4377     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4378   }
4379 
4380   SDValue Mask, VL;
4381   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4382 
4383   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4384   SDValue Trunc =
4385       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4386   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4387                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4388   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4389 }
4390 
4391 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4392 // first position of a vector, and that vector is slid up to the insert index.
4393 // By limiting the active vector length to index+1 and merging with the
4394 // original vector (with an undisturbed tail policy for elements >= VL), we
4395 // achieve the desired result of leaving all elements untouched except the one
4396 // at VL-1, which is replaced with the desired value.
4397 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4398                                                     SelectionDAG &DAG) const {
4399   SDLoc DL(Op);
4400   MVT VecVT = Op.getSimpleValueType();
4401   SDValue Vec = Op.getOperand(0);
4402   SDValue Val = Op.getOperand(1);
4403   SDValue Idx = Op.getOperand(2);
4404 
4405   if (VecVT.getVectorElementType() == MVT::i1) {
4406     // FIXME: For now we just promote to an i8 vector and insert into that,
4407     // but this is probably not optimal.
4408     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4409     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4410     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4411     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4412   }
4413 
4414   MVT ContainerVT = VecVT;
4415   // If the operand is a fixed-length vector, convert to a scalable one.
4416   if (VecVT.isFixedLengthVector()) {
4417     ContainerVT = getContainerForFixedLengthVector(VecVT);
4418     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4419   }
4420 
4421   MVT XLenVT = Subtarget.getXLenVT();
4422 
4423   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4424   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4425   // Even i64-element vectors on RV32 can be lowered without scalar
4426   // legalization if the most-significant 32 bits of the value are not affected
4427   // by the sign-extension of the lower 32 bits.
4428   // TODO: We could also catch sign extensions of a 32-bit value.
4429   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4430     const auto *CVal = cast<ConstantSDNode>(Val);
4431     if (isInt<32>(CVal->getSExtValue())) {
4432       IsLegalInsert = true;
4433       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4434     }
4435   }
4436 
4437   SDValue Mask, VL;
4438   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4439 
4440   SDValue ValInVec;
4441 
4442   if (IsLegalInsert) {
4443     unsigned Opc =
4444         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4445     if (isNullConstant(Idx)) {
4446       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4447       if (!VecVT.isFixedLengthVector())
4448         return Vec;
4449       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4450     }
4451     ValInVec =
4452         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4453   } else {
4454     // On RV32, i64-element vectors must be specially handled to place the
4455     // value at element 0, by using two vslide1up instructions in sequence on
4456     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4457     // this.
4458     SDValue One = DAG.getConstant(1, DL, XLenVT);
4459     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4460     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4461     MVT I32ContainerVT =
4462         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4463     SDValue I32Mask =
4464         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4465     // Limit the active VL to two.
4466     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4467     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4468     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4469     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4470                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4471     // First slide in the hi value, then the lo in underneath it.
4472     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4473                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4474                            I32Mask, InsertI64VL);
4475     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4476                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4477                            I32Mask, InsertI64VL);
4478     // Bitcast back to the right container type.
4479     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4480   }
4481 
4482   // Now that the value is in a vector, slide it into position.
4483   SDValue InsertVL =
4484       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4485   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4486                                 ValInVec, Idx, Mask, InsertVL);
4487   if (!VecVT.isFixedLengthVector())
4488     return Slideup;
4489   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4490 }
4491 
4492 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4493 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4494 // types this is done using VMV_X_S to allow us to glean information about the
4495 // sign bits of the result.
4496 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4497                                                      SelectionDAG &DAG) const {
4498   SDLoc DL(Op);
4499   SDValue Idx = Op.getOperand(1);
4500   SDValue Vec = Op.getOperand(0);
4501   EVT EltVT = Op.getValueType();
4502   MVT VecVT = Vec.getSimpleValueType();
4503   MVT XLenVT = Subtarget.getXLenVT();
4504 
4505   if (VecVT.getVectorElementType() == MVT::i1) {
4506     if (VecVT.isFixedLengthVector()) {
4507       unsigned NumElts = VecVT.getVectorNumElements();
4508       if (NumElts >= 8) {
4509         MVT WideEltVT;
4510         unsigned WidenVecLen;
4511         SDValue ExtractElementIdx;
4512         SDValue ExtractBitIdx;
4513         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4514         MVT LargestEltVT = MVT::getIntegerVT(
4515             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4516         if (NumElts <= LargestEltVT.getSizeInBits()) {
4517           assert(isPowerOf2_32(NumElts) &&
4518                  "the number of elements should be power of 2");
4519           WideEltVT = MVT::getIntegerVT(NumElts);
4520           WidenVecLen = 1;
4521           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4522           ExtractBitIdx = Idx;
4523         } else {
4524           WideEltVT = LargestEltVT;
4525           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4526           // extract element index = index / element width
4527           ExtractElementIdx = DAG.getNode(
4528               ISD::SRL, DL, XLenVT, Idx,
4529               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4530           // mask bit index = index % element width
4531           ExtractBitIdx = DAG.getNode(
4532               ISD::AND, DL, XLenVT, Idx,
4533               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4534         }
4535         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4536         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4537         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4538                                          Vec, ExtractElementIdx);
4539         // Extract the bit from GPR.
4540         SDValue ShiftRight =
4541             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4542         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4543                            DAG.getConstant(1, DL, XLenVT));
4544       }
4545     }
4546     // Otherwise, promote to an i8 vector and extract from that.
4547     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4548     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4549     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4550   }
4551 
4552   // If this is a fixed vector, we need to convert it to a scalable vector.
4553   MVT ContainerVT = VecVT;
4554   if (VecVT.isFixedLengthVector()) {
4555     ContainerVT = getContainerForFixedLengthVector(VecVT);
4556     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4557   }
4558 
4559   // If the index is 0, the vector is already in the right position.
4560   if (!isNullConstant(Idx)) {
4561     // Use a VL of 1 to avoid processing more elements than we need.
4562     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4563     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4564     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4565     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4566                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4567   }
4568 
4569   if (!EltVT.isInteger()) {
4570     // Floating-point extracts are handled in TableGen.
4571     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4572                        DAG.getConstant(0, DL, XLenVT));
4573   }
4574 
4575   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4576   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4577 }
4578 
4579 // Some RVV intrinsics may claim that they want an integer operand to be
4580 // promoted or expanded.
4581 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4582                                            const RISCVSubtarget &Subtarget) {
4583   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4584           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4585          "Unexpected opcode");
4586 
4587   if (!Subtarget.hasVInstructions())
4588     return SDValue();
4589 
4590   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4591   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4592   SDLoc DL(Op);
4593 
4594   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4595       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4596   if (!II || !II->hasScalarOperand())
4597     return SDValue();
4598 
4599   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4600   assert(SplatOp < Op.getNumOperands());
4601 
4602   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4603   SDValue &ScalarOp = Operands[SplatOp];
4604   MVT OpVT = ScalarOp.getSimpleValueType();
4605   MVT XLenVT = Subtarget.getXLenVT();
4606 
4607   // If this isn't a scalar, or its type is XLenVT we're done.
4608   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4609     return SDValue();
4610 
4611   // Simplest case is that the operand needs to be promoted to XLenVT.
4612   if (OpVT.bitsLT(XLenVT)) {
4613     // If the operand is a constant, sign extend to increase our chances
4614     // of being able to use a .vi instruction. ANY_EXTEND would become a
4615     // a zero extend and the simm5 check in isel would fail.
4616     // FIXME: Should we ignore the upper bits in isel instead?
4617     unsigned ExtOpc =
4618         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4619     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4620     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4621   }
4622 
4623   // Use the previous operand to get the vXi64 VT. The result might be a mask
4624   // VT for compares. Using the previous operand assumes that the previous
4625   // operand will never have a smaller element size than a scalar operand and
4626   // that a widening operation never uses SEW=64.
4627   // NOTE: If this fails the below assert, we can probably just find the
4628   // element count from any operand or result and use it to construct the VT.
4629   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4630   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4631 
4632   // The more complex case is when the scalar is larger than XLenVT.
4633   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4634          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4635 
4636   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4637   // instruction to sign-extend since SEW>XLEN.
4638   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4639     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4640     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4641   }
4642 
4643   switch (IntNo) {
4644   case Intrinsic::riscv_vslide1up:
4645   case Intrinsic::riscv_vslide1down:
4646   case Intrinsic::riscv_vslide1up_mask:
4647   case Intrinsic::riscv_vslide1down_mask: {
4648     // We need to special case these when the scalar is larger than XLen.
4649     unsigned NumOps = Op.getNumOperands();
4650     bool IsMasked = NumOps == 7;
4651 
4652     // Convert the vector source to the equivalent nxvXi32 vector.
4653     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4654     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4655 
4656     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4657                                    DAG.getConstant(0, DL, XLenVT));
4658     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4659                                    DAG.getConstant(1, DL, XLenVT));
4660 
4661     // Double the VL since we halved SEW.
4662     SDValue AVL = getVLOperand(Op);
4663     SDValue I32VL;
4664 
4665     // Optimize for constant AVL
4666     if (isa<ConstantSDNode>(AVL)) {
4667       unsigned EltSize = VT.getScalarSizeInBits();
4668       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4669 
4670       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4671       unsigned MaxVLMAX =
4672           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4673 
4674       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4675       unsigned MinVLMAX =
4676           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4677 
4678       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4679       if (AVLInt <= MinVLMAX) {
4680         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4681       } else if (AVLInt >= 2 * MaxVLMAX) {
4682         // Just set vl to VLMAX in this situation
4683         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4684         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4685         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4686         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4687         SDValue SETVLMAX = DAG.getTargetConstant(
4688             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4689         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4690                             LMUL);
4691       } else {
4692         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4693         // is related to the hardware implementation.
4694         // So let the following code handle
4695       }
4696     }
4697     if (!I32VL) {
4698       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4699       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4700       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4701       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4702       SDValue SETVL =
4703           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4704       // Using vsetvli instruction to get actually used length which related to
4705       // the hardware implementation
4706       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4707                                SEW, LMUL);
4708       I32VL =
4709           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4710     }
4711 
4712     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4713     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4714 
4715     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4716     // instructions.
4717     SDValue Passthru;
4718     if (IsMasked)
4719       Passthru = DAG.getUNDEF(I32VT);
4720     else
4721       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4722 
4723     if (IntNo == Intrinsic::riscv_vslide1up ||
4724         IntNo == Intrinsic::riscv_vslide1up_mask) {
4725       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4726                         ScalarHi, I32Mask, I32VL);
4727       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4728                         ScalarLo, I32Mask, I32VL);
4729     } else {
4730       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4731                         ScalarLo, I32Mask, I32VL);
4732       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4733                         ScalarHi, I32Mask, I32VL);
4734     }
4735 
4736     // Convert back to nxvXi64.
4737     Vec = DAG.getBitcast(VT, Vec);
4738 
4739     if (!IsMasked)
4740       return Vec;
4741     // Apply mask after the operation.
4742     SDValue Mask = Operands[NumOps - 3];
4743     SDValue MaskedOff = Operands[1];
4744     // Assume Policy operand is the last operand.
4745     uint64_t Policy =
4746         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4747     // We don't need to select maskedoff if it's undef.
4748     if (MaskedOff.isUndef())
4749       return Vec;
4750     // TAMU
4751     if (Policy == RISCVII::TAIL_AGNOSTIC)
4752       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4753                          AVL);
4754     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4755     // It's fine because vmerge does not care mask policy.
4756     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4757                        AVL);
4758   }
4759   }
4760 
4761   // We need to convert the scalar to a splat vector.
4762   SDValue VL = getVLOperand(Op);
4763   assert(VL.getValueType() == XLenVT);
4764   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4765   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4766 }
4767 
4768 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4769                                                      SelectionDAG &DAG) const {
4770   unsigned IntNo = Op.getConstantOperandVal(0);
4771   SDLoc DL(Op);
4772   MVT XLenVT = Subtarget.getXLenVT();
4773 
4774   switch (IntNo) {
4775   default:
4776     break; // Don't custom lower most intrinsics.
4777   case Intrinsic::thread_pointer: {
4778     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4779     return DAG.getRegister(RISCV::X4, PtrVT);
4780   }
4781   case Intrinsic::riscv_orc_b:
4782   case Intrinsic::riscv_brev8: {
4783     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4784     unsigned Opc =
4785         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4786     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4787                        DAG.getConstant(7, DL, XLenVT));
4788   }
4789   case Intrinsic::riscv_grev:
4790   case Intrinsic::riscv_gorc: {
4791     unsigned Opc =
4792         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4793     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4794   }
4795   case Intrinsic::riscv_zip:
4796   case Intrinsic::riscv_unzip: {
4797     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4798     // For i32 the immediate is 15. For i64 the immediate is 31.
4799     unsigned Opc =
4800         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4801     unsigned BitWidth = Op.getValueSizeInBits();
4802     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4803     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4804                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4805   }
4806   case Intrinsic::riscv_shfl:
4807   case Intrinsic::riscv_unshfl: {
4808     unsigned Opc =
4809         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4810     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4811   }
4812   case Intrinsic::riscv_bcompress:
4813   case Intrinsic::riscv_bdecompress: {
4814     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4815                                                        : RISCVISD::BDECOMPRESS;
4816     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4817   }
4818   case Intrinsic::riscv_bfp:
4819     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4820                        Op.getOperand(2));
4821   case Intrinsic::riscv_fsl:
4822     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4823                        Op.getOperand(2), Op.getOperand(3));
4824   case Intrinsic::riscv_fsr:
4825     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4826                        Op.getOperand(2), Op.getOperand(3));
4827   case Intrinsic::riscv_vmv_x_s:
4828     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4829     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4830                        Op.getOperand(1));
4831   case Intrinsic::riscv_vmv_v_x:
4832     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4833                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4834                             Subtarget);
4835   case Intrinsic::riscv_vfmv_v_f:
4836     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4837                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4838   case Intrinsic::riscv_vmv_s_x: {
4839     SDValue Scalar = Op.getOperand(2);
4840 
4841     if (Scalar.getValueType().bitsLE(XLenVT)) {
4842       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4843       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4844                          Op.getOperand(1), Scalar, Op.getOperand(3));
4845     }
4846 
4847     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4848 
4849     // This is an i64 value that lives in two scalar registers. We have to
4850     // insert this in a convoluted way. First we build vXi64 splat containing
4851     // the two values that we assemble using some bit math. Next we'll use
4852     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4853     // to merge element 0 from our splat into the source vector.
4854     // FIXME: This is probably not the best way to do this, but it is
4855     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4856     // point.
4857     //   sw lo, (a0)
4858     //   sw hi, 4(a0)
4859     //   vlse vX, (a0)
4860     //
4861     //   vid.v      vVid
4862     //   vmseq.vx   mMask, vVid, 0
4863     //   vmerge.vvm vDest, vSrc, vVal, mMask
4864     MVT VT = Op.getSimpleValueType();
4865     SDValue Vec = Op.getOperand(1);
4866     SDValue VL = getVLOperand(Op);
4867 
4868     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4869     if (Op.getOperand(1).isUndef())
4870       return SplattedVal;
4871     SDValue SplattedIdx =
4872         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4873                     DAG.getConstant(0, DL, MVT::i32), VL);
4874 
4875     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4876     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4877     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4878     SDValue SelectCond =
4879         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4880                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4881     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4882                        Vec, VL);
4883   }
4884   }
4885 
4886   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4887 }
4888 
4889 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4890                                                     SelectionDAG &DAG) const {
4891   unsigned IntNo = Op.getConstantOperandVal(1);
4892   switch (IntNo) {
4893   default:
4894     break;
4895   case Intrinsic::riscv_masked_strided_load: {
4896     SDLoc DL(Op);
4897     MVT XLenVT = Subtarget.getXLenVT();
4898 
4899     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4900     // the selection of the masked intrinsics doesn't do this for us.
4901     SDValue Mask = Op.getOperand(5);
4902     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4903 
4904     MVT VT = Op->getSimpleValueType(0);
4905     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4906 
4907     SDValue PassThru = Op.getOperand(2);
4908     if (!IsUnmasked) {
4909       MVT MaskVT =
4910           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4911       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4912       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4913     }
4914 
4915     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4916 
4917     SDValue IntID = DAG.getTargetConstant(
4918         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4919         XLenVT);
4920 
4921     auto *Load = cast<MemIntrinsicSDNode>(Op);
4922     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4923     if (IsUnmasked)
4924       Ops.push_back(DAG.getUNDEF(ContainerVT));
4925     else
4926       Ops.push_back(PassThru);
4927     Ops.push_back(Op.getOperand(3)); // Ptr
4928     Ops.push_back(Op.getOperand(4)); // Stride
4929     if (!IsUnmasked)
4930       Ops.push_back(Mask);
4931     Ops.push_back(VL);
4932     if (!IsUnmasked) {
4933       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4934       Ops.push_back(Policy);
4935     }
4936 
4937     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4938     SDValue Result =
4939         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4940                                 Load->getMemoryVT(), Load->getMemOperand());
4941     SDValue Chain = Result.getValue(1);
4942     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4943     return DAG.getMergeValues({Result, Chain}, DL);
4944   }
4945   case Intrinsic::riscv_seg2_load:
4946   case Intrinsic::riscv_seg3_load:
4947   case Intrinsic::riscv_seg4_load:
4948   case Intrinsic::riscv_seg5_load:
4949   case Intrinsic::riscv_seg6_load:
4950   case Intrinsic::riscv_seg7_load:
4951   case Intrinsic::riscv_seg8_load: {
4952     SDLoc DL(Op);
4953     static const Intrinsic::ID VlsegInts[7] = {
4954         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4955         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4956         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4957         Intrinsic::riscv_vlseg8};
4958     unsigned NF = Op->getNumValues() - 1;
4959     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4960     MVT XLenVT = Subtarget.getXLenVT();
4961     MVT VT = Op->getSimpleValueType(0);
4962     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4963 
4964     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4965     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4966     auto *Load = cast<MemIntrinsicSDNode>(Op);
4967     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4968     ContainerVTs.push_back(MVT::Other);
4969     SDVTList VTs = DAG.getVTList(ContainerVTs);
4970     SDValue Result =
4971         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4972                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4973                                 Load->getMemoryVT(), Load->getMemOperand());
4974     SmallVector<SDValue, 9> Results;
4975     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4976       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4977                                                   DAG, Subtarget));
4978     Results.push_back(Result.getValue(NF));
4979     return DAG.getMergeValues(Results, DL);
4980   }
4981   }
4982 
4983   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4984 }
4985 
4986 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4987                                                  SelectionDAG &DAG) const {
4988   unsigned IntNo = Op.getConstantOperandVal(1);
4989   switch (IntNo) {
4990   default:
4991     break;
4992   case Intrinsic::riscv_masked_strided_store: {
4993     SDLoc DL(Op);
4994     MVT XLenVT = Subtarget.getXLenVT();
4995 
4996     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4997     // the selection of the masked intrinsics doesn't do this for us.
4998     SDValue Mask = Op.getOperand(5);
4999     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5000 
5001     SDValue Val = Op.getOperand(2);
5002     MVT VT = Val.getSimpleValueType();
5003     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5004 
5005     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5006     if (!IsUnmasked) {
5007       MVT MaskVT =
5008           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5009       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5010     }
5011 
5012     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5013 
5014     SDValue IntID = DAG.getTargetConstant(
5015         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5016         XLenVT);
5017 
5018     auto *Store = cast<MemIntrinsicSDNode>(Op);
5019     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5020     Ops.push_back(Val);
5021     Ops.push_back(Op.getOperand(3)); // Ptr
5022     Ops.push_back(Op.getOperand(4)); // Stride
5023     if (!IsUnmasked)
5024       Ops.push_back(Mask);
5025     Ops.push_back(VL);
5026 
5027     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5028                                    Ops, Store->getMemoryVT(),
5029                                    Store->getMemOperand());
5030   }
5031   }
5032 
5033   return SDValue();
5034 }
5035 
5036 static MVT getLMUL1VT(MVT VT) {
5037   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5038          "Unexpected vector MVT");
5039   return MVT::getScalableVectorVT(
5040       VT.getVectorElementType(),
5041       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5042 }
5043 
5044 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5045   switch (ISDOpcode) {
5046   default:
5047     llvm_unreachable("Unhandled reduction");
5048   case ISD::VECREDUCE_ADD:
5049     return RISCVISD::VECREDUCE_ADD_VL;
5050   case ISD::VECREDUCE_UMAX:
5051     return RISCVISD::VECREDUCE_UMAX_VL;
5052   case ISD::VECREDUCE_SMAX:
5053     return RISCVISD::VECREDUCE_SMAX_VL;
5054   case ISD::VECREDUCE_UMIN:
5055     return RISCVISD::VECREDUCE_UMIN_VL;
5056   case ISD::VECREDUCE_SMIN:
5057     return RISCVISD::VECREDUCE_SMIN_VL;
5058   case ISD::VECREDUCE_AND:
5059     return RISCVISD::VECREDUCE_AND_VL;
5060   case ISD::VECREDUCE_OR:
5061     return RISCVISD::VECREDUCE_OR_VL;
5062   case ISD::VECREDUCE_XOR:
5063     return RISCVISD::VECREDUCE_XOR_VL;
5064   }
5065 }
5066 
5067 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5068                                                          SelectionDAG &DAG,
5069                                                          bool IsVP) const {
5070   SDLoc DL(Op);
5071   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5072   MVT VecVT = Vec.getSimpleValueType();
5073   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5074           Op.getOpcode() == ISD::VECREDUCE_OR ||
5075           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5076           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5077           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5078           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5079          "Unexpected reduction lowering");
5080 
5081   MVT XLenVT = Subtarget.getXLenVT();
5082   assert(Op.getValueType() == XLenVT &&
5083          "Expected reduction output to be legalized to XLenVT");
5084 
5085   MVT ContainerVT = VecVT;
5086   if (VecVT.isFixedLengthVector()) {
5087     ContainerVT = getContainerForFixedLengthVector(VecVT);
5088     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5089   }
5090 
5091   SDValue Mask, VL;
5092   if (IsVP) {
5093     Mask = Op.getOperand(2);
5094     VL = Op.getOperand(3);
5095   } else {
5096     std::tie(Mask, VL) =
5097         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5098   }
5099 
5100   unsigned BaseOpc;
5101   ISD::CondCode CC;
5102   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5103 
5104   switch (Op.getOpcode()) {
5105   default:
5106     llvm_unreachable("Unhandled reduction");
5107   case ISD::VECREDUCE_AND:
5108   case ISD::VP_REDUCE_AND: {
5109     // vcpop ~x == 0
5110     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5111     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5112     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5113     CC = ISD::SETEQ;
5114     BaseOpc = ISD::AND;
5115     break;
5116   }
5117   case ISD::VECREDUCE_OR:
5118   case ISD::VP_REDUCE_OR:
5119     // vcpop x != 0
5120     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5121     CC = ISD::SETNE;
5122     BaseOpc = ISD::OR;
5123     break;
5124   case ISD::VECREDUCE_XOR:
5125   case ISD::VP_REDUCE_XOR: {
5126     // ((vcpop x) & 1) != 0
5127     SDValue One = DAG.getConstant(1, DL, XLenVT);
5128     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5129     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5130     CC = ISD::SETNE;
5131     BaseOpc = ISD::XOR;
5132     break;
5133   }
5134   }
5135 
5136   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5137 
5138   if (!IsVP)
5139     return SetCC;
5140 
5141   // Now include the start value in the operation.
5142   // Note that we must return the start value when no elements are operated
5143   // upon. The vcpop instructions we've emitted in each case above will return
5144   // 0 for an inactive vector, and so we've already received the neutral value:
5145   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5146   // can simply include the start value.
5147   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5148 }
5149 
5150 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5151                                             SelectionDAG &DAG) const {
5152   SDLoc DL(Op);
5153   SDValue Vec = Op.getOperand(0);
5154   EVT VecEVT = Vec.getValueType();
5155 
5156   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5157 
5158   // Due to ordering in legalize types we may have a vector type that needs to
5159   // be split. Do that manually so we can get down to a legal type.
5160   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5161          TargetLowering::TypeSplitVector) {
5162     SDValue Lo, Hi;
5163     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5164     VecEVT = Lo.getValueType();
5165     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5166   }
5167 
5168   // TODO: The type may need to be widened rather than split. Or widened before
5169   // it can be split.
5170   if (!isTypeLegal(VecEVT))
5171     return SDValue();
5172 
5173   MVT VecVT = VecEVT.getSimpleVT();
5174   MVT VecEltVT = VecVT.getVectorElementType();
5175   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5176 
5177   MVT ContainerVT = VecVT;
5178   if (VecVT.isFixedLengthVector()) {
5179     ContainerVT = getContainerForFixedLengthVector(VecVT);
5180     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5181   }
5182 
5183   MVT M1VT = getLMUL1VT(ContainerVT);
5184   MVT XLenVT = Subtarget.getXLenVT();
5185 
5186   SDValue Mask, VL;
5187   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5188 
5189   SDValue NeutralElem =
5190       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5191   SDValue IdentitySplat =
5192       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5193                        M1VT, DL, DAG, Subtarget);
5194   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5195                                   IdentitySplat, Mask, VL);
5196   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5197                              DAG.getConstant(0, DL, XLenVT));
5198   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5199 }
5200 
5201 // Given a reduction op, this function returns the matching reduction opcode,
5202 // the vector SDValue and the scalar SDValue required to lower this to a
5203 // RISCVISD node.
5204 static std::tuple<unsigned, SDValue, SDValue>
5205 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5206   SDLoc DL(Op);
5207   auto Flags = Op->getFlags();
5208   unsigned Opcode = Op.getOpcode();
5209   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5210   switch (Opcode) {
5211   default:
5212     llvm_unreachable("Unhandled reduction");
5213   case ISD::VECREDUCE_FADD: {
5214     // Use positive zero if we can. It is cheaper to materialize.
5215     SDValue Zero =
5216         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5217     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5218   }
5219   case ISD::VECREDUCE_SEQ_FADD:
5220     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5221                            Op.getOperand(0));
5222   case ISD::VECREDUCE_FMIN:
5223     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5224                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5225   case ISD::VECREDUCE_FMAX:
5226     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5227                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5228   }
5229 }
5230 
5231 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5232                                               SelectionDAG &DAG) const {
5233   SDLoc DL(Op);
5234   MVT VecEltVT = Op.getSimpleValueType();
5235 
5236   unsigned RVVOpcode;
5237   SDValue VectorVal, ScalarVal;
5238   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5239       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5240   MVT VecVT = VectorVal.getSimpleValueType();
5241 
5242   MVT ContainerVT = VecVT;
5243   if (VecVT.isFixedLengthVector()) {
5244     ContainerVT = getContainerForFixedLengthVector(VecVT);
5245     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5246   }
5247 
5248   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5249   MVT XLenVT = Subtarget.getXLenVT();
5250 
5251   SDValue Mask, VL;
5252   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5253 
5254   SDValue ScalarSplat =
5255       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5256                        M1VT, DL, DAG, Subtarget);
5257   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5258                                   VectorVal, ScalarSplat, Mask, VL);
5259   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5260                      DAG.getConstant(0, DL, XLenVT));
5261 }
5262 
5263 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5264   switch (ISDOpcode) {
5265   default:
5266     llvm_unreachable("Unhandled reduction");
5267   case ISD::VP_REDUCE_ADD:
5268     return RISCVISD::VECREDUCE_ADD_VL;
5269   case ISD::VP_REDUCE_UMAX:
5270     return RISCVISD::VECREDUCE_UMAX_VL;
5271   case ISD::VP_REDUCE_SMAX:
5272     return RISCVISD::VECREDUCE_SMAX_VL;
5273   case ISD::VP_REDUCE_UMIN:
5274     return RISCVISD::VECREDUCE_UMIN_VL;
5275   case ISD::VP_REDUCE_SMIN:
5276     return RISCVISD::VECREDUCE_SMIN_VL;
5277   case ISD::VP_REDUCE_AND:
5278     return RISCVISD::VECREDUCE_AND_VL;
5279   case ISD::VP_REDUCE_OR:
5280     return RISCVISD::VECREDUCE_OR_VL;
5281   case ISD::VP_REDUCE_XOR:
5282     return RISCVISD::VECREDUCE_XOR_VL;
5283   case ISD::VP_REDUCE_FADD:
5284     return RISCVISD::VECREDUCE_FADD_VL;
5285   case ISD::VP_REDUCE_SEQ_FADD:
5286     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5287   case ISD::VP_REDUCE_FMAX:
5288     return RISCVISD::VECREDUCE_FMAX_VL;
5289   case ISD::VP_REDUCE_FMIN:
5290     return RISCVISD::VECREDUCE_FMIN_VL;
5291   }
5292 }
5293 
5294 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5295                                            SelectionDAG &DAG) const {
5296   SDLoc DL(Op);
5297   SDValue Vec = Op.getOperand(1);
5298   EVT VecEVT = Vec.getValueType();
5299 
5300   // TODO: The type may need to be widened rather than split. Or widened before
5301   // it can be split.
5302   if (!isTypeLegal(VecEVT))
5303     return SDValue();
5304 
5305   MVT VecVT = VecEVT.getSimpleVT();
5306   MVT VecEltVT = VecVT.getVectorElementType();
5307   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5308 
5309   MVT ContainerVT = VecVT;
5310   if (VecVT.isFixedLengthVector()) {
5311     ContainerVT = getContainerForFixedLengthVector(VecVT);
5312     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5313   }
5314 
5315   SDValue VL = Op.getOperand(3);
5316   SDValue Mask = Op.getOperand(2);
5317 
5318   MVT M1VT = getLMUL1VT(ContainerVT);
5319   MVT XLenVT = Subtarget.getXLenVT();
5320   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5321 
5322   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5323                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5324                                         DL, DAG, Subtarget);
5325   SDValue Reduction =
5326       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5327   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5328                              DAG.getConstant(0, DL, XLenVT));
5329   if (!VecVT.isInteger())
5330     return Elt0;
5331   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5332 }
5333 
5334 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5335                                                    SelectionDAG &DAG) const {
5336   SDValue Vec = Op.getOperand(0);
5337   SDValue SubVec = Op.getOperand(1);
5338   MVT VecVT = Vec.getSimpleValueType();
5339   MVT SubVecVT = SubVec.getSimpleValueType();
5340 
5341   SDLoc DL(Op);
5342   MVT XLenVT = Subtarget.getXLenVT();
5343   unsigned OrigIdx = Op.getConstantOperandVal(2);
5344   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5345 
5346   // We don't have the ability to slide mask vectors up indexed by their i1
5347   // elements; the smallest we can do is i8. Often we are able to bitcast to
5348   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5349   // into a scalable one, we might not necessarily have enough scalable
5350   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5351   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5352       (OrigIdx != 0 || !Vec.isUndef())) {
5353     if (VecVT.getVectorMinNumElements() >= 8 &&
5354         SubVecVT.getVectorMinNumElements() >= 8) {
5355       assert(OrigIdx % 8 == 0 && "Invalid index");
5356       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5357              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5358              "Unexpected mask vector lowering");
5359       OrigIdx /= 8;
5360       SubVecVT =
5361           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5362                            SubVecVT.isScalableVector());
5363       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5364                                VecVT.isScalableVector());
5365       Vec = DAG.getBitcast(VecVT, Vec);
5366       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5367     } else {
5368       // We can't slide this mask vector up indexed by its i1 elements.
5369       // This poses a problem when we wish to insert a scalable vector which
5370       // can't be re-expressed as a larger type. Just choose the slow path and
5371       // extend to a larger type, then truncate back down.
5372       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5373       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5374       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5375       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5376       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5377                         Op.getOperand(2));
5378       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5379       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5380     }
5381   }
5382 
5383   // If the subvector vector is a fixed-length type, we cannot use subregister
5384   // manipulation to simplify the codegen; we don't know which register of a
5385   // LMUL group contains the specific subvector as we only know the minimum
5386   // register size. Therefore we must slide the vector group up the full
5387   // amount.
5388   if (SubVecVT.isFixedLengthVector()) {
5389     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5390       return Op;
5391     MVT ContainerVT = VecVT;
5392     if (VecVT.isFixedLengthVector()) {
5393       ContainerVT = getContainerForFixedLengthVector(VecVT);
5394       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5395     }
5396     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5397                          DAG.getUNDEF(ContainerVT), SubVec,
5398                          DAG.getConstant(0, DL, XLenVT));
5399     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5400       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5401       return DAG.getBitcast(Op.getValueType(), SubVec);
5402     }
5403     SDValue Mask =
5404         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5405     // Set the vector length to only the number of elements we care about. Note
5406     // that for slideup this includes the offset.
5407     SDValue VL =
5408         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5409     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5410     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5411                                   SubVec, SlideupAmt, Mask, VL);
5412     if (VecVT.isFixedLengthVector())
5413       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5414     return DAG.getBitcast(Op.getValueType(), Slideup);
5415   }
5416 
5417   unsigned SubRegIdx, RemIdx;
5418   std::tie(SubRegIdx, RemIdx) =
5419       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5420           VecVT, SubVecVT, OrigIdx, TRI);
5421 
5422   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5423   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5424                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5425                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5426 
5427   // 1. If the Idx has been completely eliminated and this subvector's size is
5428   // a vector register or a multiple thereof, or the surrounding elements are
5429   // undef, then this is a subvector insert which naturally aligns to a vector
5430   // register. These can easily be handled using subregister manipulation.
5431   // 2. If the subvector is smaller than a vector register, then the insertion
5432   // must preserve the undisturbed elements of the register. We do this by
5433   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5434   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5435   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5436   // LMUL=1 type back into the larger vector (resolving to another subregister
5437   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5438   // to avoid allocating a large register group to hold our subvector.
5439   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5440     return Op;
5441 
5442   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5443   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5444   // (in our case undisturbed). This means we can set up a subvector insertion
5445   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5446   // size of the subvector.
5447   MVT InterSubVT = VecVT;
5448   SDValue AlignedExtract = Vec;
5449   unsigned AlignedIdx = OrigIdx - RemIdx;
5450   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5451     InterSubVT = getLMUL1VT(VecVT);
5452     // Extract a subvector equal to the nearest full vector register type. This
5453     // should resolve to a EXTRACT_SUBREG instruction.
5454     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5455                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5456   }
5457 
5458   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5459   // For scalable vectors this must be further multiplied by vscale.
5460   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5461 
5462   SDValue Mask, VL;
5463   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5464 
5465   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5466   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5467   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5468   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5469 
5470   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5471                        DAG.getUNDEF(InterSubVT), SubVec,
5472                        DAG.getConstant(0, DL, XLenVT));
5473 
5474   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5475                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5476 
5477   // If required, insert this subvector back into the correct vector register.
5478   // This should resolve to an INSERT_SUBREG instruction.
5479   if (VecVT.bitsGT(InterSubVT))
5480     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5481                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5482 
5483   // We might have bitcast from a mask type: cast back to the original type if
5484   // required.
5485   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5486 }
5487 
5488 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5489                                                     SelectionDAG &DAG) const {
5490   SDValue Vec = Op.getOperand(0);
5491   MVT SubVecVT = Op.getSimpleValueType();
5492   MVT VecVT = Vec.getSimpleValueType();
5493 
5494   SDLoc DL(Op);
5495   MVT XLenVT = Subtarget.getXLenVT();
5496   unsigned OrigIdx = Op.getConstantOperandVal(1);
5497   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5498 
5499   // We don't have the ability to slide mask vectors down indexed by their i1
5500   // elements; the smallest we can do is i8. Often we are able to bitcast to
5501   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5502   // from a scalable one, we might not necessarily have enough scalable
5503   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5504   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5505     if (VecVT.getVectorMinNumElements() >= 8 &&
5506         SubVecVT.getVectorMinNumElements() >= 8) {
5507       assert(OrigIdx % 8 == 0 && "Invalid index");
5508       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5509              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5510              "Unexpected mask vector lowering");
5511       OrigIdx /= 8;
5512       SubVecVT =
5513           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5514                            SubVecVT.isScalableVector());
5515       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5516                                VecVT.isScalableVector());
5517       Vec = DAG.getBitcast(VecVT, Vec);
5518     } else {
5519       // We can't slide this mask vector down, indexed by its i1 elements.
5520       // This poses a problem when we wish to extract a scalable vector which
5521       // can't be re-expressed as a larger type. Just choose the slow path and
5522       // extend to a larger type, then truncate back down.
5523       // TODO: We could probably improve this when extracting certain fixed
5524       // from fixed, where we can extract as i8 and shift the correct element
5525       // right to reach the desired subvector?
5526       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5527       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5528       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5529       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5530                         Op.getOperand(1));
5531       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5532       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5533     }
5534   }
5535 
5536   // If the subvector vector is a fixed-length type, we cannot use subregister
5537   // manipulation to simplify the codegen; we don't know which register of a
5538   // LMUL group contains the specific subvector as we only know the minimum
5539   // register size. Therefore we must slide the vector group down the full
5540   // amount.
5541   if (SubVecVT.isFixedLengthVector()) {
5542     // With an index of 0 this is a cast-like subvector, which can be performed
5543     // with subregister operations.
5544     if (OrigIdx == 0)
5545       return Op;
5546     MVT ContainerVT = VecVT;
5547     if (VecVT.isFixedLengthVector()) {
5548       ContainerVT = getContainerForFixedLengthVector(VecVT);
5549       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5550     }
5551     SDValue Mask =
5552         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5553     // Set the vector length to only the number of elements we care about. This
5554     // avoids sliding down elements we're going to discard straight away.
5555     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5556     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5557     SDValue Slidedown =
5558         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5559                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5560     // Now we can use a cast-like subvector extract to get the result.
5561     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5562                             DAG.getConstant(0, DL, XLenVT));
5563     return DAG.getBitcast(Op.getValueType(), Slidedown);
5564   }
5565 
5566   unsigned SubRegIdx, RemIdx;
5567   std::tie(SubRegIdx, RemIdx) =
5568       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5569           VecVT, SubVecVT, OrigIdx, TRI);
5570 
5571   // If the Idx has been completely eliminated then this is a subvector extract
5572   // which naturally aligns to a vector register. These can easily be handled
5573   // using subregister manipulation.
5574   if (RemIdx == 0)
5575     return Op;
5576 
5577   // Else we must shift our vector register directly to extract the subvector.
5578   // Do this using VSLIDEDOWN.
5579 
5580   // If the vector type is an LMUL-group type, extract a subvector equal to the
5581   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5582   // instruction.
5583   MVT InterSubVT = VecVT;
5584   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5585     InterSubVT = getLMUL1VT(VecVT);
5586     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5587                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5588   }
5589 
5590   // Slide this vector register down by the desired number of elements in order
5591   // to place the desired subvector starting at element 0.
5592   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5593   // For scalable vectors this must be further multiplied by vscale.
5594   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5595 
5596   SDValue Mask, VL;
5597   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5598   SDValue Slidedown =
5599       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5600                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5601 
5602   // Now the vector is in the right position, extract our final subvector. This
5603   // should resolve to a COPY.
5604   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5605                           DAG.getConstant(0, DL, XLenVT));
5606 
5607   // We might have bitcast from a mask type: cast back to the original type if
5608   // required.
5609   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5610 }
5611 
5612 // Lower step_vector to the vid instruction. Any non-identity step value must
5613 // be accounted for my manual expansion.
5614 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5615                                               SelectionDAG &DAG) const {
5616   SDLoc DL(Op);
5617   MVT VT = Op.getSimpleValueType();
5618   MVT XLenVT = Subtarget.getXLenVT();
5619   SDValue Mask, VL;
5620   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5621   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5622   uint64_t StepValImm = Op.getConstantOperandVal(0);
5623   if (StepValImm != 1) {
5624     if (isPowerOf2_64(StepValImm)) {
5625       SDValue StepVal =
5626           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5627                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5628       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5629     } else {
5630       SDValue StepVal = lowerScalarSplat(
5631           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5632           VL, VT, DL, DAG, Subtarget);
5633       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5634     }
5635   }
5636   return StepVec;
5637 }
5638 
5639 // Implement vector_reverse using vrgather.vv with indices determined by
5640 // subtracting the id of each element from (VLMAX-1). This will convert
5641 // the indices like so:
5642 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5643 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5644 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5645                                                  SelectionDAG &DAG) const {
5646   SDLoc DL(Op);
5647   MVT VecVT = Op.getSimpleValueType();
5648   unsigned EltSize = VecVT.getScalarSizeInBits();
5649   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5650 
5651   unsigned MaxVLMAX = 0;
5652   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5653   if (VectorBitsMax != 0)
5654     MaxVLMAX =
5655         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5656 
5657   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5658   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5659 
5660   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5661   // to use vrgatherei16.vv.
5662   // TODO: It's also possible to use vrgatherei16.vv for other types to
5663   // decrease register width for the index calculation.
5664   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5665     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5666     // Reverse each half, then reassemble them in reverse order.
5667     // NOTE: It's also possible that after splitting that VLMAX no longer
5668     // requires vrgatherei16.vv.
5669     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5670       SDValue Lo, Hi;
5671       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5672       EVT LoVT, HiVT;
5673       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5674       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5675       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5676       // Reassemble the low and high pieces reversed.
5677       // FIXME: This is a CONCAT_VECTORS.
5678       SDValue Res =
5679           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5680                       DAG.getIntPtrConstant(0, DL));
5681       return DAG.getNode(
5682           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5683           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5684     }
5685 
5686     // Just promote the int type to i16 which will double the LMUL.
5687     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5688     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5689   }
5690 
5691   MVT XLenVT = Subtarget.getXLenVT();
5692   SDValue Mask, VL;
5693   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5694 
5695   // Calculate VLMAX-1 for the desired SEW.
5696   unsigned MinElts = VecVT.getVectorMinNumElements();
5697   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5698                               DAG.getConstant(MinElts, DL, XLenVT));
5699   SDValue VLMinus1 =
5700       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5701 
5702   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5703   bool IsRV32E64 =
5704       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5705   SDValue SplatVL;
5706   if (!IsRV32E64)
5707     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5708   else
5709     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5710                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5711 
5712   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5713   SDValue Indices =
5714       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5715 
5716   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5717 }
5718 
5719 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5720                                                 SelectionDAG &DAG) const {
5721   SDLoc DL(Op);
5722   SDValue V1 = Op.getOperand(0);
5723   SDValue V2 = Op.getOperand(1);
5724   MVT XLenVT = Subtarget.getXLenVT();
5725   MVT VecVT = Op.getSimpleValueType();
5726 
5727   unsigned MinElts = VecVT.getVectorMinNumElements();
5728   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5729                               DAG.getConstant(MinElts, DL, XLenVT));
5730 
5731   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5732   SDValue DownOffset, UpOffset;
5733   if (ImmValue >= 0) {
5734     // The operand is a TargetConstant, we need to rebuild it as a regular
5735     // constant.
5736     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5737     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5738   } else {
5739     // The operand is a TargetConstant, we need to rebuild it as a regular
5740     // constant rather than negating the original operand.
5741     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5742     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5743   }
5744 
5745   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5746   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5747 
5748   SDValue SlideDown =
5749       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5750                   DownOffset, TrueMask, UpOffset);
5751   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5752                      TrueMask,
5753                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5754 }
5755 
5756 SDValue
5757 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5758                                                      SelectionDAG &DAG) const {
5759   SDLoc DL(Op);
5760   auto *Load = cast<LoadSDNode>(Op);
5761 
5762   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5763                                         Load->getMemoryVT(),
5764                                         *Load->getMemOperand()) &&
5765          "Expecting a correctly-aligned load");
5766 
5767   MVT VT = Op.getSimpleValueType();
5768   MVT XLenVT = Subtarget.getXLenVT();
5769   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5770 
5771   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5772 
5773   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5774   SDValue IntID = DAG.getTargetConstant(
5775       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5776   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5777   if (!IsMaskOp)
5778     Ops.push_back(DAG.getUNDEF(ContainerVT));
5779   Ops.push_back(Load->getBasePtr());
5780   Ops.push_back(VL);
5781   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5782   SDValue NewLoad =
5783       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5784                               Load->getMemoryVT(), Load->getMemOperand());
5785 
5786   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5787   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5788 }
5789 
5790 SDValue
5791 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5792                                                       SelectionDAG &DAG) const {
5793   SDLoc DL(Op);
5794   auto *Store = cast<StoreSDNode>(Op);
5795 
5796   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5797                                         Store->getMemoryVT(),
5798                                         *Store->getMemOperand()) &&
5799          "Expecting a correctly-aligned store");
5800 
5801   SDValue StoreVal = Store->getValue();
5802   MVT VT = StoreVal.getSimpleValueType();
5803   MVT XLenVT = Subtarget.getXLenVT();
5804 
5805   // If the size less than a byte, we need to pad with zeros to make a byte.
5806   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5807     VT = MVT::v8i1;
5808     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5809                            DAG.getConstant(0, DL, VT), StoreVal,
5810                            DAG.getIntPtrConstant(0, DL));
5811   }
5812 
5813   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5814 
5815   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5816 
5817   SDValue NewValue =
5818       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5819 
5820   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5821   SDValue IntID = DAG.getTargetConstant(
5822       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5823   return DAG.getMemIntrinsicNode(
5824       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5825       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5826       Store->getMemoryVT(), Store->getMemOperand());
5827 }
5828 
5829 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5830                                              SelectionDAG &DAG) const {
5831   SDLoc DL(Op);
5832   MVT VT = Op.getSimpleValueType();
5833 
5834   const auto *MemSD = cast<MemSDNode>(Op);
5835   EVT MemVT = MemSD->getMemoryVT();
5836   MachineMemOperand *MMO = MemSD->getMemOperand();
5837   SDValue Chain = MemSD->getChain();
5838   SDValue BasePtr = MemSD->getBasePtr();
5839 
5840   SDValue Mask, PassThru, VL;
5841   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5842     Mask = VPLoad->getMask();
5843     PassThru = DAG.getUNDEF(VT);
5844     VL = VPLoad->getVectorLength();
5845   } else {
5846     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5847     Mask = MLoad->getMask();
5848     PassThru = MLoad->getPassThru();
5849   }
5850 
5851   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5852 
5853   MVT XLenVT = Subtarget.getXLenVT();
5854 
5855   MVT ContainerVT = VT;
5856   if (VT.isFixedLengthVector()) {
5857     ContainerVT = getContainerForFixedLengthVector(VT);
5858     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5859     if (!IsUnmasked) {
5860       MVT MaskVT =
5861           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5862       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5863     }
5864   }
5865 
5866   if (!VL)
5867     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5868 
5869   unsigned IntID =
5870       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5871   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5872   if (IsUnmasked)
5873     Ops.push_back(DAG.getUNDEF(ContainerVT));
5874   else
5875     Ops.push_back(PassThru);
5876   Ops.push_back(BasePtr);
5877   if (!IsUnmasked)
5878     Ops.push_back(Mask);
5879   Ops.push_back(VL);
5880   if (!IsUnmasked)
5881     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5882 
5883   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5884 
5885   SDValue Result =
5886       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5887   Chain = Result.getValue(1);
5888 
5889   if (VT.isFixedLengthVector())
5890     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5891 
5892   return DAG.getMergeValues({Result, Chain}, DL);
5893 }
5894 
5895 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5896                                               SelectionDAG &DAG) const {
5897   SDLoc DL(Op);
5898 
5899   const auto *MemSD = cast<MemSDNode>(Op);
5900   EVT MemVT = MemSD->getMemoryVT();
5901   MachineMemOperand *MMO = MemSD->getMemOperand();
5902   SDValue Chain = MemSD->getChain();
5903   SDValue BasePtr = MemSD->getBasePtr();
5904   SDValue Val, Mask, VL;
5905 
5906   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5907     Val = VPStore->getValue();
5908     Mask = VPStore->getMask();
5909     VL = VPStore->getVectorLength();
5910   } else {
5911     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5912     Val = MStore->getValue();
5913     Mask = MStore->getMask();
5914   }
5915 
5916   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5917 
5918   MVT VT = Val.getSimpleValueType();
5919   MVT XLenVT = Subtarget.getXLenVT();
5920 
5921   MVT ContainerVT = VT;
5922   if (VT.isFixedLengthVector()) {
5923     ContainerVT = getContainerForFixedLengthVector(VT);
5924 
5925     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5926     if (!IsUnmasked) {
5927       MVT MaskVT =
5928           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5929       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5930     }
5931   }
5932 
5933   if (!VL)
5934     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5935 
5936   unsigned IntID =
5937       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5938   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5939   Ops.push_back(Val);
5940   Ops.push_back(BasePtr);
5941   if (!IsUnmasked)
5942     Ops.push_back(Mask);
5943   Ops.push_back(VL);
5944 
5945   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5946                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5947 }
5948 
5949 SDValue
5950 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5951                                                       SelectionDAG &DAG) const {
5952   MVT InVT = Op.getOperand(0).getSimpleValueType();
5953   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5954 
5955   MVT VT = Op.getSimpleValueType();
5956 
5957   SDValue Op1 =
5958       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5959   SDValue Op2 =
5960       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5961 
5962   SDLoc DL(Op);
5963   SDValue VL =
5964       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5965 
5966   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5967   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5968 
5969   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5970                             Op.getOperand(2), Mask, VL);
5971 
5972   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5973 }
5974 
5975 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5976     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5977   MVT VT = Op.getSimpleValueType();
5978 
5979   if (VT.getVectorElementType() == MVT::i1)
5980     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5981 
5982   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5983 }
5984 
5985 SDValue
5986 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5987                                                       SelectionDAG &DAG) const {
5988   unsigned Opc;
5989   switch (Op.getOpcode()) {
5990   default: llvm_unreachable("Unexpected opcode!");
5991   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5992   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5993   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5994   }
5995 
5996   return lowerToScalableOp(Op, DAG, Opc);
5997 }
5998 
5999 // Lower vector ABS to smax(X, sub(0, X)).
6000 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6001   SDLoc DL(Op);
6002   MVT VT = Op.getSimpleValueType();
6003   SDValue X = Op.getOperand(0);
6004 
6005   assert(VT.isFixedLengthVector() && "Unexpected type");
6006 
6007   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6008   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6009 
6010   SDValue Mask, VL;
6011   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6012 
6013   SDValue SplatZero = DAG.getNode(
6014       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6015       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6016   SDValue NegX =
6017       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6018   SDValue Max =
6019       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6020 
6021   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6022 }
6023 
6024 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6025     SDValue Op, SelectionDAG &DAG) const {
6026   SDLoc DL(Op);
6027   MVT VT = Op.getSimpleValueType();
6028   SDValue Mag = Op.getOperand(0);
6029   SDValue Sign = Op.getOperand(1);
6030   assert(Mag.getValueType() == Sign.getValueType() &&
6031          "Can only handle COPYSIGN with matching types.");
6032 
6033   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6034   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6035   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6036 
6037   SDValue Mask, VL;
6038   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6039 
6040   SDValue CopySign =
6041       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6042 
6043   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6044 }
6045 
6046 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6047     SDValue Op, SelectionDAG &DAG) const {
6048   MVT VT = Op.getSimpleValueType();
6049   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6050 
6051   MVT I1ContainerVT =
6052       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6053 
6054   SDValue CC =
6055       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6056   SDValue Op1 =
6057       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6058   SDValue Op2 =
6059       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6060 
6061   SDLoc DL(Op);
6062   SDValue Mask, VL;
6063   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6064 
6065   SDValue Select =
6066       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6067 
6068   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6069 }
6070 
6071 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6072                                                unsigned NewOpc,
6073                                                bool HasMask) const {
6074   MVT VT = Op.getSimpleValueType();
6075   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6076 
6077   // Create list of operands by converting existing ones to scalable types.
6078   SmallVector<SDValue, 6> Ops;
6079   for (const SDValue &V : Op->op_values()) {
6080     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6081 
6082     // Pass through non-vector operands.
6083     if (!V.getValueType().isVector()) {
6084       Ops.push_back(V);
6085       continue;
6086     }
6087 
6088     // "cast" fixed length vector to a scalable vector.
6089     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6090            "Only fixed length vectors are supported!");
6091     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6092   }
6093 
6094   SDLoc DL(Op);
6095   SDValue Mask, VL;
6096   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6097   if (HasMask)
6098     Ops.push_back(Mask);
6099   Ops.push_back(VL);
6100 
6101   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6102   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6103 }
6104 
6105 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6106 // * Operands of each node are assumed to be in the same order.
6107 // * The EVL operand is promoted from i32 to i64 on RV64.
6108 // * Fixed-length vectors are converted to their scalable-vector container
6109 //   types.
6110 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6111                                        unsigned RISCVISDOpc) const {
6112   SDLoc DL(Op);
6113   MVT VT = Op.getSimpleValueType();
6114   SmallVector<SDValue, 4> Ops;
6115 
6116   for (const auto &OpIdx : enumerate(Op->ops())) {
6117     SDValue V = OpIdx.value();
6118     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6119     // Pass through operands which aren't fixed-length vectors.
6120     if (!V.getValueType().isFixedLengthVector()) {
6121       Ops.push_back(V);
6122       continue;
6123     }
6124     // "cast" fixed length vector to a scalable vector.
6125     MVT OpVT = V.getSimpleValueType();
6126     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6127     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6128            "Only fixed length vectors are supported!");
6129     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6130   }
6131 
6132   if (!VT.isFixedLengthVector())
6133     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6134 
6135   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6136 
6137   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6138 
6139   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6140 }
6141 
6142 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6143 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6144                                                 unsigned RISCVISDOpc) const {
6145   SDLoc DL(Op);
6146 
6147   SDValue Src = Op.getOperand(0);
6148   SDValue Mask = Op.getOperand(1);
6149   SDValue VL = Op.getOperand(2);
6150 
6151   MVT DstVT = Op.getSimpleValueType();
6152   MVT SrcVT = Src.getSimpleValueType();
6153   if (DstVT.isFixedLengthVector()) {
6154     DstVT = getContainerForFixedLengthVector(DstVT);
6155     SrcVT = getContainerForFixedLengthVector(SrcVT);
6156     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6157     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6158     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6159   }
6160 
6161   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6162                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6163                                 ? RISCVISD::VSEXT_VL
6164                                 : RISCVISD::VZEXT_VL;
6165 
6166   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6167   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6168 
6169   SDValue Result;
6170   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6171     if (SrcVT.isInteger()) {
6172       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6173 
6174       // Do we need to do any pre-widening before converting?
6175       if (SrcEltSize == 1) {
6176         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6177         MVT XLenVT = Subtarget.getXLenVT();
6178         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6179         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6180                                         DAG.getUNDEF(IntVT), Zero, VL);
6181         SDValue One = DAG.getConstant(
6182             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6183         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6184                                        DAG.getUNDEF(IntVT), One, VL);
6185         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6186                           ZeroSplat, VL);
6187       } else if (DstEltSize > (2 * SrcEltSize)) {
6188         // Widen before converting.
6189         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6190                                      DstVT.getVectorElementCount());
6191         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, {Src, Mask, VL});
6192       }
6193 
6194       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, {Src, Mask, VL});
6195     } else {
6196       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6197              "Wrong input/output vector types");
6198 
6199       // Convert f16 to f32 then convert f32 to i64.
6200       if (DstEltSize > (2 * SrcEltSize)) {
6201         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6202         MVT InterimFVT =
6203             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6204         Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT,
6205                           {Src, Mask, VL});
6206       }
6207 
6208       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, {Src, Mask, VL});
6209     }
6210   } else { // Narrowing + Conversion
6211     if (SrcVT.isInteger()) {
6212       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6213       // First do a narrowing convert to an FP type half the size, then round
6214       // the FP type to a small FP type if needed.
6215 
6216       MVT InterimFVT = DstVT;
6217       if (SrcEltSize > (2 * DstEltSize)) {
6218         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6219         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6220         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6221       }
6222 
6223       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, {Src, Mask, VL});
6224 
6225       if (InterimFVT != DstVT) {
6226         Src = Result;
6227         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, {Src, Mask, VL});
6228       }
6229     } else {
6230       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6231              "Wrong input/output vector types");
6232       // First do a narrowing conversion to an integer half the size, then
6233       // truncate if needed.
6234 
6235       // TODO: Handle mask vectors
6236       assert(DstVT.getVectorElementType() != MVT::i1 &&
6237              "Don't know how to handle masks yet!");
6238       MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6239                                         DstVT.getVectorElementCount());
6240 
6241       Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, {Src, Mask, VL});
6242 
6243       while (InterimIVT != DstVT) {
6244         SrcEltSize /= 2;
6245         Src = Result;
6246         InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6247                                       DstVT.getVectorElementCount());
6248         Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6249                              {Src, Mask, VL});
6250       }
6251     }
6252   }
6253 
6254   MVT VT = Op.getSimpleValueType();
6255   if (!VT.isFixedLengthVector())
6256     return Result;
6257   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6258 }
6259 
6260 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6261                                             unsigned MaskOpc,
6262                                             unsigned VecOpc) const {
6263   MVT VT = Op.getSimpleValueType();
6264   if (VT.getVectorElementType() != MVT::i1)
6265     return lowerVPOp(Op, DAG, VecOpc);
6266 
6267   // It is safe to drop mask parameter as masked-off elements are undef.
6268   SDValue Op1 = Op->getOperand(0);
6269   SDValue Op2 = Op->getOperand(1);
6270   SDValue VL = Op->getOperand(3);
6271 
6272   MVT ContainerVT = VT;
6273   const bool IsFixed = VT.isFixedLengthVector();
6274   if (IsFixed) {
6275     ContainerVT = getContainerForFixedLengthVector(VT);
6276     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6277     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6278   }
6279 
6280   SDLoc DL(Op);
6281   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6282   if (!IsFixed)
6283     return Val;
6284   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6285 }
6286 
6287 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6288 // matched to a RVV indexed load. The RVV indexed load instructions only
6289 // support the "unsigned unscaled" addressing mode; indices are implicitly
6290 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6291 // signed or scaled indexing is extended to the XLEN value type and scaled
6292 // accordingly.
6293 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6294                                                SelectionDAG &DAG) const {
6295   SDLoc DL(Op);
6296   MVT VT = Op.getSimpleValueType();
6297 
6298   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6299   EVT MemVT = MemSD->getMemoryVT();
6300   MachineMemOperand *MMO = MemSD->getMemOperand();
6301   SDValue Chain = MemSD->getChain();
6302   SDValue BasePtr = MemSD->getBasePtr();
6303 
6304   ISD::LoadExtType LoadExtType;
6305   SDValue Index, Mask, PassThru, VL;
6306 
6307   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6308     Index = VPGN->getIndex();
6309     Mask = VPGN->getMask();
6310     PassThru = DAG.getUNDEF(VT);
6311     VL = VPGN->getVectorLength();
6312     // VP doesn't support extending loads.
6313     LoadExtType = ISD::NON_EXTLOAD;
6314   } else {
6315     // Else it must be a MGATHER.
6316     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6317     Index = MGN->getIndex();
6318     Mask = MGN->getMask();
6319     PassThru = MGN->getPassThru();
6320     LoadExtType = MGN->getExtensionType();
6321   }
6322 
6323   MVT IndexVT = Index.getSimpleValueType();
6324   MVT XLenVT = Subtarget.getXLenVT();
6325 
6326   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6327          "Unexpected VTs!");
6328   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6329   // Targets have to explicitly opt-in for extending vector loads.
6330   assert(LoadExtType == ISD::NON_EXTLOAD &&
6331          "Unexpected extending MGATHER/VP_GATHER");
6332   (void)LoadExtType;
6333 
6334   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6335   // the selection of the masked intrinsics doesn't do this for us.
6336   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6337 
6338   MVT ContainerVT = VT;
6339   if (VT.isFixedLengthVector()) {
6340     // We need to use the larger of the result and index type to determine the
6341     // scalable type to use so we don't increase LMUL for any operand/result.
6342     if (VT.bitsGE(IndexVT)) {
6343       ContainerVT = getContainerForFixedLengthVector(VT);
6344       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6345                                  ContainerVT.getVectorElementCount());
6346     } else {
6347       IndexVT = getContainerForFixedLengthVector(IndexVT);
6348       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6349                                      IndexVT.getVectorElementCount());
6350     }
6351 
6352     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6353 
6354     if (!IsUnmasked) {
6355       MVT MaskVT =
6356           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6357       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6358       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6359     }
6360   }
6361 
6362   if (!VL)
6363     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6364 
6365   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6366     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6367     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6368                                    VL);
6369     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6370                         TrueMask, VL);
6371   }
6372 
6373   unsigned IntID =
6374       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6375   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6376   if (IsUnmasked)
6377     Ops.push_back(DAG.getUNDEF(ContainerVT));
6378   else
6379     Ops.push_back(PassThru);
6380   Ops.push_back(BasePtr);
6381   Ops.push_back(Index);
6382   if (!IsUnmasked)
6383     Ops.push_back(Mask);
6384   Ops.push_back(VL);
6385   if (!IsUnmasked)
6386     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6387 
6388   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6389   SDValue Result =
6390       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6391   Chain = Result.getValue(1);
6392 
6393   if (VT.isFixedLengthVector())
6394     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6395 
6396   return DAG.getMergeValues({Result, Chain}, DL);
6397 }
6398 
6399 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6400 // matched to a RVV indexed store. The RVV indexed store instructions only
6401 // support the "unsigned unscaled" addressing mode; indices are implicitly
6402 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6403 // signed or scaled indexing is extended to the XLEN value type and scaled
6404 // accordingly.
6405 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6406                                                 SelectionDAG &DAG) const {
6407   SDLoc DL(Op);
6408   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6409   EVT MemVT = MemSD->getMemoryVT();
6410   MachineMemOperand *MMO = MemSD->getMemOperand();
6411   SDValue Chain = MemSD->getChain();
6412   SDValue BasePtr = MemSD->getBasePtr();
6413 
6414   bool IsTruncatingStore = false;
6415   SDValue Index, Mask, Val, VL;
6416 
6417   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6418     Index = VPSN->getIndex();
6419     Mask = VPSN->getMask();
6420     Val = VPSN->getValue();
6421     VL = VPSN->getVectorLength();
6422     // VP doesn't support truncating stores.
6423     IsTruncatingStore = false;
6424   } else {
6425     // Else it must be a MSCATTER.
6426     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6427     Index = MSN->getIndex();
6428     Mask = MSN->getMask();
6429     Val = MSN->getValue();
6430     IsTruncatingStore = MSN->isTruncatingStore();
6431   }
6432 
6433   MVT VT = Val.getSimpleValueType();
6434   MVT IndexVT = Index.getSimpleValueType();
6435   MVT XLenVT = Subtarget.getXLenVT();
6436 
6437   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6438          "Unexpected VTs!");
6439   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6440   // Targets have to explicitly opt-in for extending vector loads and
6441   // truncating vector stores.
6442   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6443   (void)IsTruncatingStore;
6444 
6445   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6446   // the selection of the masked intrinsics doesn't do this for us.
6447   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6448 
6449   MVT ContainerVT = VT;
6450   if (VT.isFixedLengthVector()) {
6451     // We need to use the larger of the value and index type to determine the
6452     // scalable type to use so we don't increase LMUL for any operand/result.
6453     if (VT.bitsGE(IndexVT)) {
6454       ContainerVT = getContainerForFixedLengthVector(VT);
6455       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6456                                  ContainerVT.getVectorElementCount());
6457     } else {
6458       IndexVT = getContainerForFixedLengthVector(IndexVT);
6459       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6460                                      IndexVT.getVectorElementCount());
6461     }
6462 
6463     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6464     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6465 
6466     if (!IsUnmasked) {
6467       MVT MaskVT =
6468           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6469       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6470     }
6471   }
6472 
6473   if (!VL)
6474     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6475 
6476   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6477     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6478     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6479                                    VL);
6480     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6481                         TrueMask, VL);
6482   }
6483 
6484   unsigned IntID =
6485       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6486   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6487   Ops.push_back(Val);
6488   Ops.push_back(BasePtr);
6489   Ops.push_back(Index);
6490   if (!IsUnmasked)
6491     Ops.push_back(Mask);
6492   Ops.push_back(VL);
6493 
6494   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6495                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6496 }
6497 
6498 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6499                                                SelectionDAG &DAG) const {
6500   const MVT XLenVT = Subtarget.getXLenVT();
6501   SDLoc DL(Op);
6502   SDValue Chain = Op->getOperand(0);
6503   SDValue SysRegNo = DAG.getTargetConstant(
6504       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6505   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6506   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6507 
6508   // Encoding used for rounding mode in RISCV differs from that used in
6509   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6510   // table, which consists of a sequence of 4-bit fields, each representing
6511   // corresponding FLT_ROUNDS mode.
6512   static const int Table =
6513       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6514       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6515       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6516       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6517       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6518 
6519   SDValue Shift =
6520       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6521   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6522                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6523   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6524                                DAG.getConstant(7, DL, XLenVT));
6525 
6526   return DAG.getMergeValues({Masked, Chain}, DL);
6527 }
6528 
6529 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6530                                                SelectionDAG &DAG) const {
6531   const MVT XLenVT = Subtarget.getXLenVT();
6532   SDLoc DL(Op);
6533   SDValue Chain = Op->getOperand(0);
6534   SDValue RMValue = Op->getOperand(1);
6535   SDValue SysRegNo = DAG.getTargetConstant(
6536       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6537 
6538   // Encoding used for rounding mode in RISCV differs from that used in
6539   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6540   // a table, which consists of a sequence of 4-bit fields, each representing
6541   // corresponding RISCV mode.
6542   static const unsigned Table =
6543       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6544       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6545       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6546       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6547       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6548 
6549   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6550                               DAG.getConstant(2, DL, XLenVT));
6551   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6552                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6553   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6554                         DAG.getConstant(0x7, DL, XLenVT));
6555   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6556                      RMValue);
6557 }
6558 
6559 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6560   switch (IntNo) {
6561   default:
6562     llvm_unreachable("Unexpected Intrinsic");
6563   case Intrinsic::riscv_bcompress:
6564     return RISCVISD::BCOMPRESSW;
6565   case Intrinsic::riscv_bdecompress:
6566     return RISCVISD::BDECOMPRESSW;
6567   case Intrinsic::riscv_bfp:
6568     return RISCVISD::BFPW;
6569   case Intrinsic::riscv_fsl:
6570     return RISCVISD::FSLW;
6571   case Intrinsic::riscv_fsr:
6572     return RISCVISD::FSRW;
6573   }
6574 }
6575 
6576 // Converts the given intrinsic to a i64 operation with any extension.
6577 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6578                                          unsigned IntNo) {
6579   SDLoc DL(N);
6580   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6581   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6582   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6583   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6584   // ReplaceNodeResults requires we maintain the same type for the return value.
6585   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6586 }
6587 
6588 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6589 // form of the given Opcode.
6590 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6591   switch (Opcode) {
6592   default:
6593     llvm_unreachable("Unexpected opcode");
6594   case ISD::SHL:
6595     return RISCVISD::SLLW;
6596   case ISD::SRA:
6597     return RISCVISD::SRAW;
6598   case ISD::SRL:
6599     return RISCVISD::SRLW;
6600   case ISD::SDIV:
6601     return RISCVISD::DIVW;
6602   case ISD::UDIV:
6603     return RISCVISD::DIVUW;
6604   case ISD::UREM:
6605     return RISCVISD::REMUW;
6606   case ISD::ROTL:
6607     return RISCVISD::ROLW;
6608   case ISD::ROTR:
6609     return RISCVISD::RORW;
6610   }
6611 }
6612 
6613 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6614 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6615 // otherwise be promoted to i64, making it difficult to select the
6616 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6617 // type i8/i16/i32 is lost.
6618 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6619                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6620   SDLoc DL(N);
6621   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6622   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6623   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6624   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6625   // ReplaceNodeResults requires we maintain the same type for the return value.
6626   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6627 }
6628 
6629 // Converts the given 32-bit operation to a i64 operation with signed extension
6630 // semantic to reduce the signed extension instructions.
6631 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6632   SDLoc DL(N);
6633   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6634   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6635   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6636   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6637                                DAG.getValueType(MVT::i32));
6638   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6639 }
6640 
6641 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6642                                              SmallVectorImpl<SDValue> &Results,
6643                                              SelectionDAG &DAG) const {
6644   SDLoc DL(N);
6645   switch (N->getOpcode()) {
6646   default:
6647     llvm_unreachable("Don't know how to custom type legalize this operation!");
6648   case ISD::STRICT_FP_TO_SINT:
6649   case ISD::STRICT_FP_TO_UINT:
6650   case ISD::FP_TO_SINT:
6651   case ISD::FP_TO_UINT: {
6652     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6653            "Unexpected custom legalisation");
6654     bool IsStrict = N->isStrictFPOpcode();
6655     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6656                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6657     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6658     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6659         TargetLowering::TypeSoftenFloat) {
6660       if (!isTypeLegal(Op0.getValueType()))
6661         return;
6662       if (IsStrict) {
6663         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6664                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6665         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6666         SDValue Res = DAG.getNode(
6667             Opc, DL, VTs, N->getOperand(0), Op0,
6668             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6669         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6670         Results.push_back(Res.getValue(1));
6671         return;
6672       }
6673       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6674       SDValue Res =
6675           DAG.getNode(Opc, DL, MVT::i64, Op0,
6676                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6677       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6678       return;
6679     }
6680     // If the FP type needs to be softened, emit a library call using the 'si'
6681     // version. If we left it to default legalization we'd end up with 'di'. If
6682     // the FP type doesn't need to be softened just let generic type
6683     // legalization promote the result type.
6684     RTLIB::Libcall LC;
6685     if (IsSigned)
6686       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6687     else
6688       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6689     MakeLibCallOptions CallOptions;
6690     EVT OpVT = Op0.getValueType();
6691     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6692     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6693     SDValue Result;
6694     std::tie(Result, Chain) =
6695         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6696     Results.push_back(Result);
6697     if (IsStrict)
6698       Results.push_back(Chain);
6699     break;
6700   }
6701   case ISD::READCYCLECOUNTER: {
6702     assert(!Subtarget.is64Bit() &&
6703            "READCYCLECOUNTER only has custom type legalization on riscv32");
6704 
6705     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6706     SDValue RCW =
6707         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6708 
6709     Results.push_back(
6710         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6711     Results.push_back(RCW.getValue(2));
6712     break;
6713   }
6714   case ISD::MUL: {
6715     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6716     unsigned XLen = Subtarget.getXLen();
6717     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6718     if (Size > XLen) {
6719       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6720       SDValue LHS = N->getOperand(0);
6721       SDValue RHS = N->getOperand(1);
6722       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6723 
6724       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6725       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6726       // We need exactly one side to be unsigned.
6727       if (LHSIsU == RHSIsU)
6728         return;
6729 
6730       auto MakeMULPair = [&](SDValue S, SDValue U) {
6731         MVT XLenVT = Subtarget.getXLenVT();
6732         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6733         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6734         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6735         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6736         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6737       };
6738 
6739       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6740       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6741 
6742       // The other operand should be signed, but still prefer MULH when
6743       // possible.
6744       if (RHSIsU && LHSIsS && !RHSIsS)
6745         Results.push_back(MakeMULPair(LHS, RHS));
6746       else if (LHSIsU && RHSIsS && !LHSIsS)
6747         Results.push_back(MakeMULPair(RHS, LHS));
6748 
6749       return;
6750     }
6751     LLVM_FALLTHROUGH;
6752   }
6753   case ISD::ADD:
6754   case ISD::SUB:
6755     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6756            "Unexpected custom legalisation");
6757     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6758     break;
6759   case ISD::SHL:
6760   case ISD::SRA:
6761   case ISD::SRL:
6762     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6763            "Unexpected custom legalisation");
6764     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6765       Results.push_back(customLegalizeToWOp(N, DAG));
6766       break;
6767     }
6768 
6769     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6770     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6771     // shift amount.
6772     if (N->getOpcode() == ISD::SHL) {
6773       SDLoc DL(N);
6774       SDValue NewOp0 =
6775           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6776       SDValue NewOp1 =
6777           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6778       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6779       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6780                                    DAG.getValueType(MVT::i32));
6781       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6782     }
6783 
6784     break;
6785   case ISD::ROTL:
6786   case ISD::ROTR:
6787     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6788            "Unexpected custom legalisation");
6789     Results.push_back(customLegalizeToWOp(N, DAG));
6790     break;
6791   case ISD::CTTZ:
6792   case ISD::CTTZ_ZERO_UNDEF:
6793   case ISD::CTLZ:
6794   case ISD::CTLZ_ZERO_UNDEF: {
6795     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6796            "Unexpected custom legalisation");
6797 
6798     SDValue NewOp0 =
6799         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6800     bool IsCTZ =
6801         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6802     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6803     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6804     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6805     return;
6806   }
6807   case ISD::SDIV:
6808   case ISD::UDIV:
6809   case ISD::UREM: {
6810     MVT VT = N->getSimpleValueType(0);
6811     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6812            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6813            "Unexpected custom legalisation");
6814     // Don't promote division/remainder by constant since we should expand those
6815     // to multiply by magic constant.
6816     // FIXME: What if the expansion is disabled for minsize.
6817     if (N->getOperand(1).getOpcode() == ISD::Constant)
6818       return;
6819 
6820     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6821     // the upper 32 bits. For other types we need to sign or zero extend
6822     // based on the opcode.
6823     unsigned ExtOpc = ISD::ANY_EXTEND;
6824     if (VT != MVT::i32)
6825       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6826                                            : ISD::ZERO_EXTEND;
6827 
6828     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6829     break;
6830   }
6831   case ISD::UADDO:
6832   case ISD::USUBO: {
6833     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6834            "Unexpected custom legalisation");
6835     bool IsAdd = N->getOpcode() == ISD::UADDO;
6836     // Create an ADDW or SUBW.
6837     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6838     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6839     SDValue Res =
6840         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6841     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6842                       DAG.getValueType(MVT::i32));
6843 
6844     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6845     // Since the inputs are sign extended from i32, this is equivalent to
6846     // comparing the lower 32 bits.
6847     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6848     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6849                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6850 
6851     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6852     Results.push_back(Overflow);
6853     return;
6854   }
6855   case ISD::UADDSAT:
6856   case ISD::USUBSAT: {
6857     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6858            "Unexpected custom legalisation");
6859     if (Subtarget.hasStdExtZbb()) {
6860       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6861       // sign extend allows overflow of the lower 32 bits to be detected on
6862       // the promoted size.
6863       SDValue LHS =
6864           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6865       SDValue RHS =
6866           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6867       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6868       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6869       return;
6870     }
6871 
6872     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6873     // promotion for UADDO/USUBO.
6874     Results.push_back(expandAddSubSat(N, DAG));
6875     return;
6876   }
6877   case ISD::ABS: {
6878     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6879            "Unexpected custom legalisation");
6880           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6881 
6882     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6883 
6884     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6885 
6886     // Freeze the source so we can increase it's use count.
6887     Src = DAG.getFreeze(Src);
6888 
6889     // Copy sign bit to all bits using the sraiw pattern.
6890     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6891                                    DAG.getValueType(MVT::i32));
6892     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6893                            DAG.getConstant(31, DL, MVT::i64));
6894 
6895     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6896     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6897 
6898     // NOTE: The result is only required to be anyextended, but sext is
6899     // consistent with type legalization of sub.
6900     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6901                          DAG.getValueType(MVT::i32));
6902     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6903     return;
6904   }
6905   case ISD::BITCAST: {
6906     EVT VT = N->getValueType(0);
6907     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6908     SDValue Op0 = N->getOperand(0);
6909     EVT Op0VT = Op0.getValueType();
6910     MVT XLenVT = Subtarget.getXLenVT();
6911     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6912       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6913       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6914     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6915                Subtarget.hasStdExtF()) {
6916       SDValue FPConv =
6917           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6918       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6919     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6920                isTypeLegal(Op0VT)) {
6921       // Custom-legalize bitcasts from fixed-length vector types to illegal
6922       // scalar types in order to improve codegen. Bitcast the vector to a
6923       // one-element vector type whose element type is the same as the result
6924       // type, and extract the first element.
6925       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6926       if (isTypeLegal(BVT)) {
6927         SDValue BVec = DAG.getBitcast(BVT, Op0);
6928         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6929                                       DAG.getConstant(0, DL, XLenVT)));
6930       }
6931     }
6932     break;
6933   }
6934   case RISCVISD::GREV:
6935   case RISCVISD::GORC:
6936   case RISCVISD::SHFL: {
6937     MVT VT = N->getSimpleValueType(0);
6938     MVT XLenVT = Subtarget.getXLenVT();
6939     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
6940            "Unexpected custom legalisation");
6941     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6942     assert((Subtarget.hasStdExtZbp() ||
6943             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
6944              N->getConstantOperandVal(1) == 7)) &&
6945            "Unexpected extension");
6946     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6947     SDValue NewOp1 =
6948         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
6949     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
6950     // ReplaceNodeResults requires we maintain the same type for the return
6951     // value.
6952     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
6953     break;
6954   }
6955   case ISD::BSWAP:
6956   case ISD::BITREVERSE: {
6957     MVT VT = N->getSimpleValueType(0);
6958     MVT XLenVT = Subtarget.getXLenVT();
6959     assert((VT == MVT::i8 || VT == MVT::i16 ||
6960             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6961            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6962     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6963     unsigned Imm = VT.getSizeInBits() - 1;
6964     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6965     if (N->getOpcode() == ISD::BSWAP)
6966       Imm &= ~0x7U;
6967     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
6968                                 DAG.getConstant(Imm, DL, XLenVT));
6969     // ReplaceNodeResults requires we maintain the same type for the return
6970     // value.
6971     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6972     break;
6973   }
6974   case ISD::FSHL:
6975   case ISD::FSHR: {
6976     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6977            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6978     SDValue NewOp0 =
6979         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6980     SDValue NewOp1 =
6981         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6982     SDValue NewShAmt =
6983         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6984     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6985     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6986     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6987                            DAG.getConstant(0x1f, DL, MVT::i64));
6988     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6989     // instruction use different orders. fshl will return its first operand for
6990     // shift of zero, fshr will return its second operand. fsl and fsr both
6991     // return rs1 so the ISD nodes need to have different operand orders.
6992     // Shift amount is in rs2.
6993     unsigned Opc = RISCVISD::FSLW;
6994     if (N->getOpcode() == ISD::FSHR) {
6995       std::swap(NewOp0, NewOp1);
6996       Opc = RISCVISD::FSRW;
6997     }
6998     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6999     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7000     break;
7001   }
7002   case ISD::EXTRACT_VECTOR_ELT: {
7003     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7004     // type is illegal (currently only vXi64 RV32).
7005     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7006     // transferred to the destination register. We issue two of these from the
7007     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7008     // first element.
7009     SDValue Vec = N->getOperand(0);
7010     SDValue Idx = N->getOperand(1);
7011 
7012     // The vector type hasn't been legalized yet so we can't issue target
7013     // specific nodes if it needs legalization.
7014     // FIXME: We would manually legalize if it's important.
7015     if (!isTypeLegal(Vec.getValueType()))
7016       return;
7017 
7018     MVT VecVT = Vec.getSimpleValueType();
7019 
7020     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7021            VecVT.getVectorElementType() == MVT::i64 &&
7022            "Unexpected EXTRACT_VECTOR_ELT legalization");
7023 
7024     // If this is a fixed vector, we need to convert it to a scalable vector.
7025     MVT ContainerVT = VecVT;
7026     if (VecVT.isFixedLengthVector()) {
7027       ContainerVT = getContainerForFixedLengthVector(VecVT);
7028       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7029     }
7030 
7031     MVT XLenVT = Subtarget.getXLenVT();
7032 
7033     // Use a VL of 1 to avoid processing more elements than we need.
7034     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7035     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7036     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7037 
7038     // Unless the index is known to be 0, we must slide the vector down to get
7039     // the desired element into index 0.
7040     if (!isNullConstant(Idx)) {
7041       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7042                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7043     }
7044 
7045     // Extract the lower XLEN bits of the correct vector element.
7046     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7047 
7048     // To extract the upper XLEN bits of the vector element, shift the first
7049     // element right by 32 bits and re-extract the lower XLEN bits.
7050     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7051                                      DAG.getUNDEF(ContainerVT),
7052                                      DAG.getConstant(32, DL, XLenVT), VL);
7053     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7054                                  ThirtyTwoV, Mask, VL);
7055 
7056     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7057 
7058     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7059     break;
7060   }
7061   case ISD::INTRINSIC_WO_CHAIN: {
7062     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7063     switch (IntNo) {
7064     default:
7065       llvm_unreachable(
7066           "Don't know how to custom type legalize this intrinsic!");
7067     case Intrinsic::riscv_grev:
7068     case Intrinsic::riscv_gorc: {
7069       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7070              "Unexpected custom legalisation");
7071       SDValue NewOp1 =
7072           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7073       SDValue NewOp2 =
7074           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7075       unsigned Opc =
7076           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7077       // If the control is a constant, promote the node by clearing any extra
7078       // bits bits in the control. isel will form greviw/gorciw if the result is
7079       // sign extended.
7080       if (isa<ConstantSDNode>(NewOp2)) {
7081         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7082                              DAG.getConstant(0x1f, DL, MVT::i64));
7083         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7084       }
7085       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7086       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7087       break;
7088     }
7089     case Intrinsic::riscv_bcompress:
7090     case Intrinsic::riscv_bdecompress:
7091     case Intrinsic::riscv_bfp: {
7092       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7093              "Unexpected custom legalisation");
7094       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7095       break;
7096     }
7097     case Intrinsic::riscv_fsl:
7098     case Intrinsic::riscv_fsr: {
7099       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7100              "Unexpected custom legalisation");
7101       SDValue NewOp1 =
7102           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7103       SDValue NewOp2 =
7104           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7105       SDValue NewOp3 =
7106           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
7107       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
7108       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
7109       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7110       break;
7111     }
7112     case Intrinsic::riscv_orc_b: {
7113       // Lower to the GORCI encoding for orc.b with the operand extended.
7114       SDValue NewOp =
7115           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7116       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7117                                 DAG.getConstant(7, DL, MVT::i64));
7118       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7119       return;
7120     }
7121     case Intrinsic::riscv_shfl:
7122     case Intrinsic::riscv_unshfl: {
7123       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7124              "Unexpected custom legalisation");
7125       SDValue NewOp1 =
7126           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7127       SDValue NewOp2 =
7128           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7129       unsigned Opc =
7130           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7131       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7132       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7133       // will be shuffled the same way as the lower 32 bit half, but the two
7134       // halves won't cross.
7135       if (isa<ConstantSDNode>(NewOp2)) {
7136         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7137                              DAG.getConstant(0xf, DL, MVT::i64));
7138         Opc =
7139             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7140       }
7141       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7142       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7143       break;
7144     }
7145     case Intrinsic::riscv_vmv_x_s: {
7146       EVT VT = N->getValueType(0);
7147       MVT XLenVT = Subtarget.getXLenVT();
7148       if (VT.bitsLT(XLenVT)) {
7149         // Simple case just extract using vmv.x.s and truncate.
7150         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7151                                       Subtarget.getXLenVT(), N->getOperand(1));
7152         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7153         return;
7154       }
7155 
7156       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7157              "Unexpected custom legalization");
7158 
7159       // We need to do the move in two steps.
7160       SDValue Vec = N->getOperand(1);
7161       MVT VecVT = Vec.getSimpleValueType();
7162 
7163       // First extract the lower XLEN bits of the element.
7164       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7165 
7166       // To extract the upper XLEN bits of the vector element, shift the first
7167       // element right by 32 bits and re-extract the lower XLEN bits.
7168       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7169       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7170       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7171       SDValue ThirtyTwoV =
7172           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7173                       DAG.getConstant(32, DL, XLenVT), VL);
7174       SDValue LShr32 =
7175           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7176       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7177 
7178       Results.push_back(
7179           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7180       break;
7181     }
7182     }
7183     break;
7184   }
7185   case ISD::VECREDUCE_ADD:
7186   case ISD::VECREDUCE_AND:
7187   case ISD::VECREDUCE_OR:
7188   case ISD::VECREDUCE_XOR:
7189   case ISD::VECREDUCE_SMAX:
7190   case ISD::VECREDUCE_UMAX:
7191   case ISD::VECREDUCE_SMIN:
7192   case ISD::VECREDUCE_UMIN:
7193     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7194       Results.push_back(V);
7195     break;
7196   case ISD::VP_REDUCE_ADD:
7197   case ISD::VP_REDUCE_AND:
7198   case ISD::VP_REDUCE_OR:
7199   case ISD::VP_REDUCE_XOR:
7200   case ISD::VP_REDUCE_SMAX:
7201   case ISD::VP_REDUCE_UMAX:
7202   case ISD::VP_REDUCE_SMIN:
7203   case ISD::VP_REDUCE_UMIN:
7204     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7205       Results.push_back(V);
7206     break;
7207   case ISD::FLT_ROUNDS_: {
7208     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7209     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7210     Results.push_back(Res.getValue(0));
7211     Results.push_back(Res.getValue(1));
7212     break;
7213   }
7214   }
7215 }
7216 
7217 // A structure to hold one of the bit-manipulation patterns below. Together, a
7218 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7219 //   (or (and (shl x, 1), 0xAAAAAAAA),
7220 //       (and (srl x, 1), 0x55555555))
7221 struct RISCVBitmanipPat {
7222   SDValue Op;
7223   unsigned ShAmt;
7224   bool IsSHL;
7225 
7226   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7227     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7228   }
7229 };
7230 
7231 // Matches patterns of the form
7232 //   (and (shl x, C2), (C1 << C2))
7233 //   (and (srl x, C2), C1)
7234 //   (shl (and x, C1), C2)
7235 //   (srl (and x, (C1 << C2)), C2)
7236 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7237 // The expected masks for each shift amount are specified in BitmanipMasks where
7238 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7239 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7240 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7241 // XLen is 64.
7242 static Optional<RISCVBitmanipPat>
7243 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7244   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7245          "Unexpected number of masks");
7246   Optional<uint64_t> Mask;
7247   // Optionally consume a mask around the shift operation.
7248   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7249     Mask = Op.getConstantOperandVal(1);
7250     Op = Op.getOperand(0);
7251   }
7252   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7253     return None;
7254   bool IsSHL = Op.getOpcode() == ISD::SHL;
7255 
7256   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7257     return None;
7258   uint64_t ShAmt = Op.getConstantOperandVal(1);
7259 
7260   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7261   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7262     return None;
7263   // If we don't have enough masks for 64 bit, then we must be trying to
7264   // match SHFL so we're only allowed to shift 1/4 of the width.
7265   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7266     return None;
7267 
7268   SDValue Src = Op.getOperand(0);
7269 
7270   // The expected mask is shifted left when the AND is found around SHL
7271   // patterns.
7272   //   ((x >> 1) & 0x55555555)
7273   //   ((x << 1) & 0xAAAAAAAA)
7274   bool SHLExpMask = IsSHL;
7275 
7276   if (!Mask) {
7277     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7278     // the mask is all ones: consume that now.
7279     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7280       Mask = Src.getConstantOperandVal(1);
7281       Src = Src.getOperand(0);
7282       // The expected mask is now in fact shifted left for SRL, so reverse the
7283       // decision.
7284       //   ((x & 0xAAAAAAAA) >> 1)
7285       //   ((x & 0x55555555) << 1)
7286       SHLExpMask = !SHLExpMask;
7287     } else {
7288       // Use a default shifted mask of all-ones if there's no AND, truncated
7289       // down to the expected width. This simplifies the logic later on.
7290       Mask = maskTrailingOnes<uint64_t>(Width);
7291       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7292     }
7293   }
7294 
7295   unsigned MaskIdx = Log2_32(ShAmt);
7296   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7297 
7298   if (SHLExpMask)
7299     ExpMask <<= ShAmt;
7300 
7301   if (Mask != ExpMask)
7302     return None;
7303 
7304   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7305 }
7306 
7307 // Matches any of the following bit-manipulation patterns:
7308 //   (and (shl x, 1), (0x55555555 << 1))
7309 //   (and (srl x, 1), 0x55555555)
7310 //   (shl (and x, 0x55555555), 1)
7311 //   (srl (and x, (0x55555555 << 1)), 1)
7312 // where the shift amount and mask may vary thus:
7313 //   [1]  = 0x55555555 / 0xAAAAAAAA
7314 //   [2]  = 0x33333333 / 0xCCCCCCCC
7315 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7316 //   [8]  = 0x00FF00FF / 0xFF00FF00
7317 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7318 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7319 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7320   // These are the unshifted masks which we use to match bit-manipulation
7321   // patterns. They may be shifted left in certain circumstances.
7322   static const uint64_t BitmanipMasks[] = {
7323       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7324       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7325 
7326   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7327 }
7328 
7329 // Match the following pattern as a GREVI(W) operation
7330 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7331 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7332                                const RISCVSubtarget &Subtarget) {
7333   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7334   EVT VT = Op.getValueType();
7335 
7336   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7337     auto LHS = matchGREVIPat(Op.getOperand(0));
7338     auto RHS = matchGREVIPat(Op.getOperand(1));
7339     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7340       SDLoc DL(Op);
7341       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7342                          DAG.getConstant(LHS->ShAmt, DL, VT));
7343     }
7344   }
7345   return SDValue();
7346 }
7347 
7348 // Matches any the following pattern as a GORCI(W) operation
7349 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7350 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7351 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7352 // Note that with the variant of 3.,
7353 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7354 // the inner pattern will first be matched as GREVI and then the outer
7355 // pattern will be matched to GORC via the first rule above.
7356 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7357 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7358                                const RISCVSubtarget &Subtarget) {
7359   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7360   EVT VT = Op.getValueType();
7361 
7362   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7363     SDLoc DL(Op);
7364     SDValue Op0 = Op.getOperand(0);
7365     SDValue Op1 = Op.getOperand(1);
7366 
7367     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7368       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7369           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7370           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7371         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7372       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7373       if ((Reverse.getOpcode() == ISD::ROTL ||
7374            Reverse.getOpcode() == ISD::ROTR) &&
7375           Reverse.getOperand(0) == X &&
7376           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7377         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7378         if (RotAmt == (VT.getSizeInBits() / 2))
7379           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7380                              DAG.getConstant(RotAmt, DL, VT));
7381       }
7382       return SDValue();
7383     };
7384 
7385     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7386     if (SDValue V = MatchOROfReverse(Op0, Op1))
7387       return V;
7388     if (SDValue V = MatchOROfReverse(Op1, Op0))
7389       return V;
7390 
7391     // OR is commutable so canonicalize its OR operand to the left
7392     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7393       std::swap(Op0, Op1);
7394     if (Op0.getOpcode() != ISD::OR)
7395       return SDValue();
7396     SDValue OrOp0 = Op0.getOperand(0);
7397     SDValue OrOp1 = Op0.getOperand(1);
7398     auto LHS = matchGREVIPat(OrOp0);
7399     // OR is commutable so swap the operands and try again: x might have been
7400     // on the left
7401     if (!LHS) {
7402       std::swap(OrOp0, OrOp1);
7403       LHS = matchGREVIPat(OrOp0);
7404     }
7405     auto RHS = matchGREVIPat(Op1);
7406     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7407       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7408                          DAG.getConstant(LHS->ShAmt, DL, VT));
7409     }
7410   }
7411   return SDValue();
7412 }
7413 
7414 // Matches any of the following bit-manipulation patterns:
7415 //   (and (shl x, 1), (0x22222222 << 1))
7416 //   (and (srl x, 1), 0x22222222)
7417 //   (shl (and x, 0x22222222), 1)
7418 //   (srl (and x, (0x22222222 << 1)), 1)
7419 // where the shift amount and mask may vary thus:
7420 //   [1]  = 0x22222222 / 0x44444444
7421 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7422 //   [4]  = 0x00F000F0 / 0x0F000F00
7423 //   [8]  = 0x0000FF00 / 0x00FF0000
7424 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7425 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7426   // These are the unshifted masks which we use to match bit-manipulation
7427   // patterns. They may be shifted left in certain circumstances.
7428   static const uint64_t BitmanipMasks[] = {
7429       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7430       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7431 
7432   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7433 }
7434 
7435 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7436 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7437                                const RISCVSubtarget &Subtarget) {
7438   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7439   EVT VT = Op.getValueType();
7440 
7441   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7442     return SDValue();
7443 
7444   SDValue Op0 = Op.getOperand(0);
7445   SDValue Op1 = Op.getOperand(1);
7446 
7447   // Or is commutable so canonicalize the second OR to the LHS.
7448   if (Op0.getOpcode() != ISD::OR)
7449     std::swap(Op0, Op1);
7450   if (Op0.getOpcode() != ISD::OR)
7451     return SDValue();
7452 
7453   // We found an inner OR, so our operands are the operands of the inner OR
7454   // and the other operand of the outer OR.
7455   SDValue A = Op0.getOperand(0);
7456   SDValue B = Op0.getOperand(1);
7457   SDValue C = Op1;
7458 
7459   auto Match1 = matchSHFLPat(A);
7460   auto Match2 = matchSHFLPat(B);
7461 
7462   // If neither matched, we failed.
7463   if (!Match1 && !Match2)
7464     return SDValue();
7465 
7466   // We had at least one match. if one failed, try the remaining C operand.
7467   if (!Match1) {
7468     std::swap(A, C);
7469     Match1 = matchSHFLPat(A);
7470     if (!Match1)
7471       return SDValue();
7472   } else if (!Match2) {
7473     std::swap(B, C);
7474     Match2 = matchSHFLPat(B);
7475     if (!Match2)
7476       return SDValue();
7477   }
7478   assert(Match1 && Match2);
7479 
7480   // Make sure our matches pair up.
7481   if (!Match1->formsPairWith(*Match2))
7482     return SDValue();
7483 
7484   // All the remains is to make sure C is an AND with the same input, that masks
7485   // out the bits that are being shuffled.
7486   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7487       C.getOperand(0) != Match1->Op)
7488     return SDValue();
7489 
7490   uint64_t Mask = C.getConstantOperandVal(1);
7491 
7492   static const uint64_t BitmanipMasks[] = {
7493       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7494       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7495   };
7496 
7497   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7498   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7499   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7500 
7501   if (Mask != ExpMask)
7502     return SDValue();
7503 
7504   SDLoc DL(Op);
7505   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7506                      DAG.getConstant(Match1->ShAmt, DL, VT));
7507 }
7508 
7509 // Optimize (add (shl x, c0), (shl y, c1)) ->
7510 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7511 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7512                                   const RISCVSubtarget &Subtarget) {
7513   // Perform this optimization only in the zba extension.
7514   if (!Subtarget.hasStdExtZba())
7515     return SDValue();
7516 
7517   // Skip for vector types and larger types.
7518   EVT VT = N->getValueType(0);
7519   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7520     return SDValue();
7521 
7522   // The two operand nodes must be SHL and have no other use.
7523   SDValue N0 = N->getOperand(0);
7524   SDValue N1 = N->getOperand(1);
7525   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7526       !N0->hasOneUse() || !N1->hasOneUse())
7527     return SDValue();
7528 
7529   // Check c0 and c1.
7530   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7531   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7532   if (!N0C || !N1C)
7533     return SDValue();
7534   int64_t C0 = N0C->getSExtValue();
7535   int64_t C1 = N1C->getSExtValue();
7536   if (C0 <= 0 || C1 <= 0)
7537     return SDValue();
7538 
7539   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7540   int64_t Bits = std::min(C0, C1);
7541   int64_t Diff = std::abs(C0 - C1);
7542   if (Diff != 1 && Diff != 2 && Diff != 3)
7543     return SDValue();
7544 
7545   // Build nodes.
7546   SDLoc DL(N);
7547   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7548   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7549   SDValue NA0 =
7550       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7551   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7552   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7553 }
7554 
7555 // Combine
7556 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7557 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7558 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7559 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7560 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7561 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7562 // The grev patterns represents BSWAP.
7563 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7564 // off the grev.
7565 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7566                                           const RISCVSubtarget &Subtarget) {
7567   bool IsWInstruction =
7568       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7569   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7570           IsWInstruction) &&
7571          "Unexpected opcode!");
7572   SDValue Src = N->getOperand(0);
7573   EVT VT = N->getValueType(0);
7574   SDLoc DL(N);
7575 
7576   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7577     return SDValue();
7578 
7579   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7580       !isa<ConstantSDNode>(Src.getOperand(1)))
7581     return SDValue();
7582 
7583   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7584   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7585 
7586   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7587   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7588   unsigned ShAmt1 = N->getConstantOperandVal(1);
7589   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7590   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7591     return SDValue();
7592 
7593   Src = Src.getOperand(0);
7594 
7595   // Toggle bit the MSB of the shift.
7596   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7597   if (CombinedShAmt == 0)
7598     return Src;
7599 
7600   SDValue Res = DAG.getNode(
7601       RISCVISD::GREV, DL, VT, Src,
7602       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7603   if (!IsWInstruction)
7604     return Res;
7605 
7606   // Sign extend the result to match the behavior of the rotate. This will be
7607   // selected to GREVIW in isel.
7608   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7609                      DAG.getValueType(MVT::i32));
7610 }
7611 
7612 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7613 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7614 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7615 // not undo itself, but they are redundant.
7616 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7617   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7618   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7619   SDValue Src = N->getOperand(0);
7620 
7621   if (Src.getOpcode() != N->getOpcode())
7622     return SDValue();
7623 
7624   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7625       !isa<ConstantSDNode>(Src.getOperand(1)))
7626     return SDValue();
7627 
7628   unsigned ShAmt1 = N->getConstantOperandVal(1);
7629   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7630   Src = Src.getOperand(0);
7631 
7632   unsigned CombinedShAmt;
7633   if (IsGORC)
7634     CombinedShAmt = ShAmt1 | ShAmt2;
7635   else
7636     CombinedShAmt = ShAmt1 ^ ShAmt2;
7637 
7638   if (CombinedShAmt == 0)
7639     return Src;
7640 
7641   SDLoc DL(N);
7642   return DAG.getNode(
7643       N->getOpcode(), DL, N->getValueType(0), Src,
7644       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7645 }
7646 
7647 // Combine a constant select operand into its use:
7648 //
7649 // (and (select cond, -1, c), x)
7650 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7651 // (or  (select cond, 0, c), x)
7652 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7653 // (xor (select cond, 0, c), x)
7654 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7655 // (add (select cond, 0, c), x)
7656 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7657 // (sub x, (select cond, 0, c))
7658 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7659 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7660                                    SelectionDAG &DAG, bool AllOnes) {
7661   EVT VT = N->getValueType(0);
7662 
7663   // Skip vectors.
7664   if (VT.isVector())
7665     return SDValue();
7666 
7667   if ((Slct.getOpcode() != ISD::SELECT &&
7668        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7669       !Slct.hasOneUse())
7670     return SDValue();
7671 
7672   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7673     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7674   };
7675 
7676   bool SwapSelectOps;
7677   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7678   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7679   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7680   SDValue NonConstantVal;
7681   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7682     SwapSelectOps = false;
7683     NonConstantVal = FalseVal;
7684   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7685     SwapSelectOps = true;
7686     NonConstantVal = TrueVal;
7687   } else
7688     return SDValue();
7689 
7690   // Slct is now know to be the desired identity constant when CC is true.
7691   TrueVal = OtherOp;
7692   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7693   // Unless SwapSelectOps says the condition should be false.
7694   if (SwapSelectOps)
7695     std::swap(TrueVal, FalseVal);
7696 
7697   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7698     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7699                        {Slct.getOperand(0), Slct.getOperand(1),
7700                         Slct.getOperand(2), TrueVal, FalseVal});
7701 
7702   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7703                      {Slct.getOperand(0), TrueVal, FalseVal});
7704 }
7705 
7706 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7707 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7708                                               bool AllOnes) {
7709   SDValue N0 = N->getOperand(0);
7710   SDValue N1 = N->getOperand(1);
7711   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7712     return Result;
7713   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7714     return Result;
7715   return SDValue();
7716 }
7717 
7718 // Transform (add (mul x, c0), c1) ->
7719 //           (add (mul (add x, c1/c0), c0), c1%c0).
7720 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7721 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7722 // to an infinite loop in DAGCombine if transformed.
7723 // Or transform (add (mul x, c0), c1) ->
7724 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7725 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7726 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7727 // lead to an infinite loop in DAGCombine if transformed.
7728 // Or transform (add (mul x, c0), c1) ->
7729 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7730 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7731 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7732 // lead to an infinite loop in DAGCombine if transformed.
7733 // Or transform (add (mul x, c0), c1) ->
7734 //              (mul (add x, c1/c0), c0).
7735 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7736 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7737                                      const RISCVSubtarget &Subtarget) {
7738   // Skip for vector types and larger types.
7739   EVT VT = N->getValueType(0);
7740   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7741     return SDValue();
7742   // The first operand node must be a MUL and has no other use.
7743   SDValue N0 = N->getOperand(0);
7744   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7745     return SDValue();
7746   // Check if c0 and c1 match above conditions.
7747   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7748   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7749   if (!N0C || !N1C)
7750     return SDValue();
7751   // If N0C has multiple uses it's possible one of the cases in
7752   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7753   // in an infinite loop.
7754   if (!N0C->hasOneUse())
7755     return SDValue();
7756   int64_t C0 = N0C->getSExtValue();
7757   int64_t C1 = N1C->getSExtValue();
7758   int64_t CA, CB;
7759   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7760     return SDValue();
7761   // Search for proper CA (non-zero) and CB that both are simm12.
7762   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7763       !isInt<12>(C0 * (C1 / C0))) {
7764     CA = C1 / C0;
7765     CB = C1 % C0;
7766   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7767              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7768     CA = C1 / C0 + 1;
7769     CB = C1 % C0 - C0;
7770   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7771              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7772     CA = C1 / C0 - 1;
7773     CB = C1 % C0 + C0;
7774   } else
7775     return SDValue();
7776   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7777   SDLoc DL(N);
7778   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7779                              DAG.getConstant(CA, DL, VT));
7780   SDValue New1 =
7781       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7782   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7783 }
7784 
7785 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7786                                  const RISCVSubtarget &Subtarget) {
7787   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7788     return V;
7789   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7790     return V;
7791   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7792   //      (select lhs, rhs, cc, x, (add x, y))
7793   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7794 }
7795 
7796 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7797   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7798   //      (select lhs, rhs, cc, x, (sub x, y))
7799   SDValue N0 = N->getOperand(0);
7800   SDValue N1 = N->getOperand(1);
7801   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7802 }
7803 
7804 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7805   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7806   //      (select lhs, rhs, cc, x, (and x, y))
7807   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7808 }
7809 
7810 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7811                                 const RISCVSubtarget &Subtarget) {
7812   if (Subtarget.hasStdExtZbp()) {
7813     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7814       return GREV;
7815     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7816       return GORC;
7817     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7818       return SHFL;
7819   }
7820 
7821   // fold (or (select cond, 0, y), x) ->
7822   //      (select cond, x, (or x, y))
7823   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7824 }
7825 
7826 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7827   // fold (xor (select cond, 0, y), x) ->
7828   //      (select cond, x, (xor x, y))
7829   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7830 }
7831 
7832 static SDValue
7833 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7834                                 const RISCVSubtarget &Subtarget) {
7835   SDValue Src = N->getOperand(0);
7836   EVT VT = N->getValueType(0);
7837 
7838   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7839   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7840       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7841     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7842                        Src.getOperand(0));
7843 
7844   // Fold (i64 (sext_inreg (abs X), i32)) ->
7845   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7846   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7847   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7848   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7849   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7850   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7851   // may get combined into an earlier operation so we need to use
7852   // ComputeNumSignBits.
7853   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7854   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7855   // we can't assume that X has 33 sign bits. We must check.
7856   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7857       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7858       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7859       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7860     SDLoc DL(N);
7861     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7862     SDValue Neg =
7863         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7864     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7865                       DAG.getValueType(MVT::i32));
7866     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7867   }
7868 
7869   return SDValue();
7870 }
7871 
7872 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7873 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7874 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7875                                              bool Commute = false) {
7876   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7877           N->getOpcode() == RISCVISD::SUB_VL) &&
7878          "Unexpected opcode");
7879   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7880   SDValue Op0 = N->getOperand(0);
7881   SDValue Op1 = N->getOperand(1);
7882   if (Commute)
7883     std::swap(Op0, Op1);
7884 
7885   MVT VT = N->getSimpleValueType(0);
7886 
7887   // Determine the narrow size for a widening add/sub.
7888   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7889   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7890                                   VT.getVectorElementCount());
7891 
7892   SDValue Mask = N->getOperand(2);
7893   SDValue VL = N->getOperand(3);
7894 
7895   SDLoc DL(N);
7896 
7897   // If the RHS is a sext or zext, we can form a widening op.
7898   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7899        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7900       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7901     unsigned ExtOpc = Op1.getOpcode();
7902     Op1 = Op1.getOperand(0);
7903     // Re-introduce narrower extends if needed.
7904     if (Op1.getValueType() != NarrowVT)
7905       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7906 
7907     unsigned WOpc;
7908     if (ExtOpc == RISCVISD::VSEXT_VL)
7909       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7910     else
7911       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7912 
7913     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7914   }
7915 
7916   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7917   // sext/zext?
7918 
7919   return SDValue();
7920 }
7921 
7922 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7923 // vwsub(u).vv/vx.
7924 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7925   SDValue Op0 = N->getOperand(0);
7926   SDValue Op1 = N->getOperand(1);
7927   SDValue Mask = N->getOperand(2);
7928   SDValue VL = N->getOperand(3);
7929 
7930   MVT VT = N->getSimpleValueType(0);
7931   MVT NarrowVT = Op1.getSimpleValueType();
7932   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7933 
7934   unsigned VOpc;
7935   switch (N->getOpcode()) {
7936   default: llvm_unreachable("Unexpected opcode");
7937   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7938   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7939   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7940   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7941   }
7942 
7943   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7944                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7945 
7946   SDLoc DL(N);
7947 
7948   // If the LHS is a sext or zext, we can narrow this op to the same size as
7949   // the RHS.
7950   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7951        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7952       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7953     unsigned ExtOpc = Op0.getOpcode();
7954     Op0 = Op0.getOperand(0);
7955     // Re-introduce narrower extends if needed.
7956     if (Op0.getValueType() != NarrowVT)
7957       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7958     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7959   }
7960 
7961   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7962                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7963 
7964   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7965   // to commute and use a vwadd(u).vx instead.
7966   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7967       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7968     Op0 = Op0.getOperand(1);
7969 
7970     // See if have enough sign bits or zero bits in the scalar to use a
7971     // widening add/sub by splatting to smaller element size.
7972     unsigned EltBits = VT.getScalarSizeInBits();
7973     unsigned ScalarBits = Op0.getValueSizeInBits();
7974     // Make sure we're getting all element bits from the scalar register.
7975     // FIXME: Support implicit sign extension of vmv.v.x?
7976     if (ScalarBits < EltBits)
7977       return SDValue();
7978 
7979     if (IsSigned) {
7980       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7981         return SDValue();
7982     } else {
7983       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7984       if (!DAG.MaskedValueIsZero(Op0, Mask))
7985         return SDValue();
7986     }
7987 
7988     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7989                       DAG.getUNDEF(NarrowVT), Op0, VL);
7990     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7991   }
7992 
7993   return SDValue();
7994 }
7995 
7996 // Try to form VWMUL, VWMULU or VWMULSU.
7997 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7998 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7999                                        bool Commute) {
8000   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8001   SDValue Op0 = N->getOperand(0);
8002   SDValue Op1 = N->getOperand(1);
8003   if (Commute)
8004     std::swap(Op0, Op1);
8005 
8006   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8007   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8008   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8009   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8010     return SDValue();
8011 
8012   SDValue Mask = N->getOperand(2);
8013   SDValue VL = N->getOperand(3);
8014 
8015   // Make sure the mask and VL match.
8016   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8017     return SDValue();
8018 
8019   MVT VT = N->getSimpleValueType(0);
8020 
8021   // Determine the narrow size for a widening multiply.
8022   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8023   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8024                                   VT.getVectorElementCount());
8025 
8026   SDLoc DL(N);
8027 
8028   // See if the other operand is the same opcode.
8029   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8030     if (!Op1.hasOneUse())
8031       return SDValue();
8032 
8033     // Make sure the mask and VL match.
8034     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8035       return SDValue();
8036 
8037     Op1 = Op1.getOperand(0);
8038   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8039     // The operand is a splat of a scalar.
8040 
8041     // The pasthru must be undef for tail agnostic
8042     if (!Op1.getOperand(0).isUndef())
8043       return SDValue();
8044     // The VL must be the same.
8045     if (Op1.getOperand(2) != VL)
8046       return SDValue();
8047 
8048     // Get the scalar value.
8049     Op1 = Op1.getOperand(1);
8050 
8051     // See if have enough sign bits or zero bits in the scalar to use a
8052     // widening multiply by splatting to smaller element size.
8053     unsigned EltBits = VT.getScalarSizeInBits();
8054     unsigned ScalarBits = Op1.getValueSizeInBits();
8055     // Make sure we're getting all element bits from the scalar register.
8056     // FIXME: Support implicit sign extension of vmv.v.x?
8057     if (ScalarBits < EltBits)
8058       return SDValue();
8059 
8060     // If the LHS is a sign extend, try to use vwmul.
8061     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8062       // Can use vwmul.
8063     } else {
8064       // Otherwise try to use vwmulu or vwmulsu.
8065       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8066       if (DAG.MaskedValueIsZero(Op1, Mask))
8067         IsVWMULSU = IsSignExt;
8068       else
8069         return SDValue();
8070     }
8071 
8072     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8073                       DAG.getUNDEF(NarrowVT), Op1, VL);
8074   } else
8075     return SDValue();
8076 
8077   Op0 = Op0.getOperand(0);
8078 
8079   // Re-introduce narrower extends if needed.
8080   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8081   if (Op0.getValueType() != NarrowVT)
8082     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8083   // vwmulsu requires second operand to be zero extended.
8084   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8085   if (Op1.getValueType() != NarrowVT)
8086     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8087 
8088   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8089   if (!IsVWMULSU)
8090     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8091   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8092 }
8093 
8094 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8095   switch (Op.getOpcode()) {
8096   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8097   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8098   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8099   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8100   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8101   }
8102 
8103   return RISCVFPRndMode::Invalid;
8104 }
8105 
8106 // Fold
8107 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8108 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8109 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8110 //   (fp_to_int (fceil X))      -> fcvt X, rup
8111 //   (fp_to_int (fround X))     -> fcvt X, rmm
8112 static SDValue performFP_TO_INTCombine(SDNode *N,
8113                                        TargetLowering::DAGCombinerInfo &DCI,
8114                                        const RISCVSubtarget &Subtarget) {
8115   SelectionDAG &DAG = DCI.DAG;
8116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8117   MVT XLenVT = Subtarget.getXLenVT();
8118 
8119   // Only handle XLen or i32 types. Other types narrower than XLen will
8120   // eventually be legalized to XLenVT.
8121   EVT VT = N->getValueType(0);
8122   if (VT != MVT::i32 && VT != XLenVT)
8123     return SDValue();
8124 
8125   SDValue Src = N->getOperand(0);
8126 
8127   // Ensure the FP type is also legal.
8128   if (!TLI.isTypeLegal(Src.getValueType()))
8129     return SDValue();
8130 
8131   // Don't do this for f16 with Zfhmin and not Zfh.
8132   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8133     return SDValue();
8134 
8135   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8136   if (FRM == RISCVFPRndMode::Invalid)
8137     return SDValue();
8138 
8139   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8140 
8141   unsigned Opc;
8142   if (VT == XLenVT)
8143     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8144   else
8145     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8146 
8147   SDLoc DL(N);
8148   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8149                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8150   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8151 }
8152 
8153 // Fold
8154 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8155 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8156 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8157 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8158 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8159 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8160                                        TargetLowering::DAGCombinerInfo &DCI,
8161                                        const RISCVSubtarget &Subtarget) {
8162   SelectionDAG &DAG = DCI.DAG;
8163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8164   MVT XLenVT = Subtarget.getXLenVT();
8165 
8166   // Only handle XLen types. Other types narrower than XLen will eventually be
8167   // legalized to XLenVT.
8168   EVT DstVT = N->getValueType(0);
8169   if (DstVT != XLenVT)
8170     return SDValue();
8171 
8172   SDValue Src = N->getOperand(0);
8173 
8174   // Ensure the FP type is also legal.
8175   if (!TLI.isTypeLegal(Src.getValueType()))
8176     return SDValue();
8177 
8178   // Don't do this for f16 with Zfhmin and not Zfh.
8179   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8180     return SDValue();
8181 
8182   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8183 
8184   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8185   if (FRM == RISCVFPRndMode::Invalid)
8186     return SDValue();
8187 
8188   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8189 
8190   unsigned Opc;
8191   if (SatVT == DstVT)
8192     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8193   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8194     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8195   else
8196     return SDValue();
8197   // FIXME: Support other SatVTs by clamping before or after the conversion.
8198 
8199   Src = Src.getOperand(0);
8200 
8201   SDLoc DL(N);
8202   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8203                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8204 
8205   // RISCV FP-to-int conversions saturate to the destination register size, but
8206   // don't produce 0 for nan.
8207   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8208   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8209 }
8210 
8211 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8212 // smaller than XLenVT.
8213 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8214                                         const RISCVSubtarget &Subtarget) {
8215   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8216 
8217   SDValue Src = N->getOperand(0);
8218   if (Src.getOpcode() != ISD::BSWAP)
8219     return SDValue();
8220 
8221   EVT VT = N->getValueType(0);
8222   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8223       !isPowerOf2_32(VT.getSizeInBits()))
8224     return SDValue();
8225 
8226   SDLoc DL(N);
8227   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8228                      DAG.getConstant(7, DL, VT));
8229 }
8230 
8231 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8232                                                DAGCombinerInfo &DCI) const {
8233   SelectionDAG &DAG = DCI.DAG;
8234 
8235   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8236   // bits are demanded. N will be added to the Worklist if it was not deleted.
8237   // Caller should return SDValue(N, 0) if this returns true.
8238   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8239     SDValue Op = N->getOperand(OpNo);
8240     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8241     if (!SimplifyDemandedBits(Op, Mask, DCI))
8242       return false;
8243 
8244     if (N->getOpcode() != ISD::DELETED_NODE)
8245       DCI.AddToWorklist(N);
8246     return true;
8247   };
8248 
8249   switch (N->getOpcode()) {
8250   default:
8251     break;
8252   case RISCVISD::SplitF64: {
8253     SDValue Op0 = N->getOperand(0);
8254     // If the input to SplitF64 is just BuildPairF64 then the operation is
8255     // redundant. Instead, use BuildPairF64's operands directly.
8256     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8257       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8258 
8259     if (Op0->isUndef()) {
8260       SDValue Lo = DAG.getUNDEF(MVT::i32);
8261       SDValue Hi = DAG.getUNDEF(MVT::i32);
8262       return DCI.CombineTo(N, Lo, Hi);
8263     }
8264 
8265     SDLoc DL(N);
8266 
8267     // It's cheaper to materialise two 32-bit integers than to load a double
8268     // from the constant pool and transfer it to integer registers through the
8269     // stack.
8270     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8271       APInt V = C->getValueAPF().bitcastToAPInt();
8272       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8273       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8274       return DCI.CombineTo(N, Lo, Hi);
8275     }
8276 
8277     // This is a target-specific version of a DAGCombine performed in
8278     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8279     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8280     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8281     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8282         !Op0.getNode()->hasOneUse())
8283       break;
8284     SDValue NewSplitF64 =
8285         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8286                     Op0.getOperand(0));
8287     SDValue Lo = NewSplitF64.getValue(0);
8288     SDValue Hi = NewSplitF64.getValue(1);
8289     APInt SignBit = APInt::getSignMask(32);
8290     if (Op0.getOpcode() == ISD::FNEG) {
8291       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8292                                   DAG.getConstant(SignBit, DL, MVT::i32));
8293       return DCI.CombineTo(N, Lo, NewHi);
8294     }
8295     assert(Op0.getOpcode() == ISD::FABS);
8296     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8297                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8298     return DCI.CombineTo(N, Lo, NewHi);
8299   }
8300   case RISCVISD::SLLW:
8301   case RISCVISD::SRAW:
8302   case RISCVISD::SRLW: {
8303     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8304     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8305         SimplifyDemandedLowBitsHelper(1, 5))
8306       return SDValue(N, 0);
8307 
8308     break;
8309   }
8310   case ISD::ROTR:
8311   case ISD::ROTL:
8312   case RISCVISD::RORW:
8313   case RISCVISD::ROLW: {
8314     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8315       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8316       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8317           SimplifyDemandedLowBitsHelper(1, 5))
8318         return SDValue(N, 0);
8319     }
8320 
8321     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8322   }
8323   case RISCVISD::CLZW:
8324   case RISCVISD::CTZW: {
8325     // Only the lower 32 bits of the first operand are read
8326     if (SimplifyDemandedLowBitsHelper(0, 32))
8327       return SDValue(N, 0);
8328     break;
8329   }
8330   case RISCVISD::GREV:
8331   case RISCVISD::GORC: {
8332     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8333     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8334     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8335     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8336       return SDValue(N, 0);
8337 
8338     return combineGREVI_GORCI(N, DAG);
8339   }
8340   case RISCVISD::GREVW:
8341   case RISCVISD::GORCW: {
8342     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8343     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8344         SimplifyDemandedLowBitsHelper(1, 5))
8345       return SDValue(N, 0);
8346 
8347     break;
8348   }
8349   case RISCVISD::SHFL:
8350   case RISCVISD::UNSHFL: {
8351     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8352     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8353     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8354     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8355       return SDValue(N, 0);
8356 
8357     break;
8358   }
8359   case RISCVISD::SHFLW:
8360   case RISCVISD::UNSHFLW: {
8361     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8362     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8363         SimplifyDemandedLowBitsHelper(1, 4))
8364       return SDValue(N, 0);
8365 
8366     break;
8367   }
8368   case RISCVISD::BCOMPRESSW:
8369   case RISCVISD::BDECOMPRESSW: {
8370     // Only the lower 32 bits of LHS and RHS are read.
8371     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8372         SimplifyDemandedLowBitsHelper(1, 32))
8373       return SDValue(N, 0);
8374 
8375     break;
8376   }
8377   case RISCVISD::FSR:
8378   case RISCVISD::FSL:
8379   case RISCVISD::FSRW:
8380   case RISCVISD::FSLW: {
8381     bool IsWInstruction =
8382         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8383     unsigned BitWidth =
8384         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8385     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8386     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8387     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8388       return SDValue(N, 0);
8389 
8390     break;
8391   }
8392   case RISCVISD::FMV_X_ANYEXTH:
8393   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8394     SDLoc DL(N);
8395     SDValue Op0 = N->getOperand(0);
8396     MVT VT = N->getSimpleValueType(0);
8397     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8398     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8399     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8400     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8401          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8402         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8403          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8404       assert(Op0.getOperand(0).getValueType() == VT &&
8405              "Unexpected value type!");
8406       return Op0.getOperand(0);
8407     }
8408 
8409     // This is a target-specific version of a DAGCombine performed in
8410     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8411     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8412     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8413     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8414         !Op0.getNode()->hasOneUse())
8415       break;
8416     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8417     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8418     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8419     if (Op0.getOpcode() == ISD::FNEG)
8420       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8421                          DAG.getConstant(SignBit, DL, VT));
8422 
8423     assert(Op0.getOpcode() == ISD::FABS);
8424     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8425                        DAG.getConstant(~SignBit, DL, VT));
8426   }
8427   case ISD::ADD:
8428     return performADDCombine(N, DAG, Subtarget);
8429   case ISD::SUB:
8430     return performSUBCombine(N, DAG);
8431   case ISD::AND:
8432     return performANDCombine(N, DAG);
8433   case ISD::OR:
8434     return performORCombine(N, DAG, Subtarget);
8435   case ISD::XOR:
8436     return performXORCombine(N, DAG);
8437   case ISD::SIGN_EXTEND_INREG:
8438     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8439   case ISD::ZERO_EXTEND:
8440     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8441     // type legalization. This is safe because fp_to_uint produces poison if
8442     // it overflows.
8443     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8444       SDValue Src = N->getOperand(0);
8445       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8446           isTypeLegal(Src.getOperand(0).getValueType()))
8447         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8448                            Src.getOperand(0));
8449       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8450           isTypeLegal(Src.getOperand(1).getValueType())) {
8451         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8452         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8453                                   Src.getOperand(0), Src.getOperand(1));
8454         DCI.CombineTo(N, Res);
8455         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8456         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8457         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8458       }
8459     }
8460     return SDValue();
8461   case RISCVISD::SELECT_CC: {
8462     // Transform
8463     SDValue LHS = N->getOperand(0);
8464     SDValue RHS = N->getOperand(1);
8465     SDValue TrueV = N->getOperand(3);
8466     SDValue FalseV = N->getOperand(4);
8467 
8468     // If the True and False values are the same, we don't need a select_cc.
8469     if (TrueV == FalseV)
8470       return TrueV;
8471 
8472     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8473     if (!ISD::isIntEqualitySetCC(CCVal))
8474       break;
8475 
8476     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8477     //      (select_cc X, Y, lt, trueV, falseV)
8478     // Sometimes the setcc is introduced after select_cc has been formed.
8479     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8480         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8481       // If we're looking for eq 0 instead of ne 0, we need to invert the
8482       // condition.
8483       bool Invert = CCVal == ISD::SETEQ;
8484       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8485       if (Invert)
8486         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8487 
8488       SDLoc DL(N);
8489       RHS = LHS.getOperand(1);
8490       LHS = LHS.getOperand(0);
8491       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8492 
8493       SDValue TargetCC = DAG.getCondCode(CCVal);
8494       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8495                          {LHS, RHS, TargetCC, TrueV, FalseV});
8496     }
8497 
8498     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8499     //      (select_cc X, Y, eq/ne, trueV, falseV)
8500     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8501       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8502                          {LHS.getOperand(0), LHS.getOperand(1),
8503                           N->getOperand(2), TrueV, FalseV});
8504     // (select_cc X, 1, setne, trueV, falseV) ->
8505     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8506     // This can occur when legalizing some floating point comparisons.
8507     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8508     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8509       SDLoc DL(N);
8510       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8511       SDValue TargetCC = DAG.getCondCode(CCVal);
8512       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8513       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8514                          {LHS, RHS, TargetCC, TrueV, FalseV});
8515     }
8516 
8517     break;
8518   }
8519   case RISCVISD::BR_CC: {
8520     SDValue LHS = N->getOperand(1);
8521     SDValue RHS = N->getOperand(2);
8522     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8523     if (!ISD::isIntEqualitySetCC(CCVal))
8524       break;
8525 
8526     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8527     //      (br_cc X, Y, lt, dest)
8528     // Sometimes the setcc is introduced after br_cc has been formed.
8529     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8530         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8531       // If we're looking for eq 0 instead of ne 0, we need to invert the
8532       // condition.
8533       bool Invert = CCVal == ISD::SETEQ;
8534       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8535       if (Invert)
8536         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8537 
8538       SDLoc DL(N);
8539       RHS = LHS.getOperand(1);
8540       LHS = LHS.getOperand(0);
8541       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8542 
8543       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8544                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8545                          N->getOperand(4));
8546     }
8547 
8548     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8549     //      (br_cc X, Y, eq/ne, trueV, falseV)
8550     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8551       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8552                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8553                          N->getOperand(3), N->getOperand(4));
8554 
8555     // (br_cc X, 1, setne, br_cc) ->
8556     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8557     // This can occur when legalizing some floating point comparisons.
8558     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8559     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8560       SDLoc DL(N);
8561       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8562       SDValue TargetCC = DAG.getCondCode(CCVal);
8563       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8564       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8565                          N->getOperand(0), LHS, RHS, TargetCC,
8566                          N->getOperand(4));
8567     }
8568     break;
8569   }
8570   case ISD::BITREVERSE:
8571     return performBITREVERSECombine(N, DAG, Subtarget);
8572   case ISD::FP_TO_SINT:
8573   case ISD::FP_TO_UINT:
8574     return performFP_TO_INTCombine(N, DCI, Subtarget);
8575   case ISD::FP_TO_SINT_SAT:
8576   case ISD::FP_TO_UINT_SAT:
8577     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8578   case ISD::FCOPYSIGN: {
8579     EVT VT = N->getValueType(0);
8580     if (!VT.isVector())
8581       break;
8582     // There is a form of VFSGNJ which injects the negated sign of its second
8583     // operand. Try and bubble any FNEG up after the extend/round to produce
8584     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8585     // TRUNC=1.
8586     SDValue In2 = N->getOperand(1);
8587     // Avoid cases where the extend/round has multiple uses, as duplicating
8588     // those is typically more expensive than removing a fneg.
8589     if (!In2.hasOneUse())
8590       break;
8591     if (In2.getOpcode() != ISD::FP_EXTEND &&
8592         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8593       break;
8594     In2 = In2.getOperand(0);
8595     if (In2.getOpcode() != ISD::FNEG)
8596       break;
8597     SDLoc DL(N);
8598     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8599     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8600                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8601   }
8602   case ISD::MGATHER:
8603   case ISD::MSCATTER:
8604   case ISD::VP_GATHER:
8605   case ISD::VP_SCATTER: {
8606     if (!DCI.isBeforeLegalize())
8607       break;
8608     SDValue Index, ScaleOp;
8609     bool IsIndexScaled = false;
8610     bool IsIndexSigned = false;
8611     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8612       Index = VPGSN->getIndex();
8613       ScaleOp = VPGSN->getScale();
8614       IsIndexScaled = VPGSN->isIndexScaled();
8615       IsIndexSigned = VPGSN->isIndexSigned();
8616     } else {
8617       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8618       Index = MGSN->getIndex();
8619       ScaleOp = MGSN->getScale();
8620       IsIndexScaled = MGSN->isIndexScaled();
8621       IsIndexSigned = MGSN->isIndexSigned();
8622     }
8623     EVT IndexVT = Index.getValueType();
8624     MVT XLenVT = Subtarget.getXLenVT();
8625     // RISCV indexed loads only support the "unsigned unscaled" addressing
8626     // mode, so anything else must be manually legalized.
8627     bool NeedsIdxLegalization =
8628         IsIndexScaled ||
8629         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8630     if (!NeedsIdxLegalization)
8631       break;
8632 
8633     SDLoc DL(N);
8634 
8635     // Any index legalization should first promote to XLenVT, so we don't lose
8636     // bits when scaling. This may create an illegal index type so we let
8637     // LLVM's legalization take care of the splitting.
8638     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8639     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8640       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8641       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8642                           DL, IndexVT, Index);
8643     }
8644 
8645     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8646     if (IsIndexScaled && Scale != 1) {
8647       // Manually scale the indices by the element size.
8648       // TODO: Sanitize the scale operand here?
8649       // TODO: For VP nodes, should we use VP_SHL here?
8650       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8651       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8652       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8653     }
8654 
8655     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8656     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8657       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8658                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8659                               VPGN->getScale(), VPGN->getMask(),
8660                               VPGN->getVectorLength()},
8661                              VPGN->getMemOperand(), NewIndexTy);
8662     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8663       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8664                               {VPSN->getChain(), VPSN->getValue(),
8665                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8666                                VPSN->getMask(), VPSN->getVectorLength()},
8667                               VPSN->getMemOperand(), NewIndexTy);
8668     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8669       return DAG.getMaskedGather(
8670           N->getVTList(), MGN->getMemoryVT(), DL,
8671           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8672            MGN->getBasePtr(), Index, MGN->getScale()},
8673           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8674     const auto *MSN = cast<MaskedScatterSDNode>(N);
8675     return DAG.getMaskedScatter(
8676         N->getVTList(), MSN->getMemoryVT(), DL,
8677         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8678          Index, MSN->getScale()},
8679         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8680   }
8681   case RISCVISD::SRA_VL:
8682   case RISCVISD::SRL_VL:
8683   case RISCVISD::SHL_VL: {
8684     SDValue ShAmt = N->getOperand(1);
8685     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8686       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8687       SDLoc DL(N);
8688       SDValue VL = N->getOperand(3);
8689       EVT VT = N->getValueType(0);
8690       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8691                           ShAmt.getOperand(1), VL);
8692       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8693                          N->getOperand(2), N->getOperand(3));
8694     }
8695     break;
8696   }
8697   case ISD::SRA:
8698   case ISD::SRL:
8699   case ISD::SHL: {
8700     SDValue ShAmt = N->getOperand(1);
8701     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8702       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8703       SDLoc DL(N);
8704       EVT VT = N->getValueType(0);
8705       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8706                           ShAmt.getOperand(1),
8707                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8708       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8709     }
8710     break;
8711   }
8712   case RISCVISD::ADD_VL:
8713     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8714       return V;
8715     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8716   case RISCVISD::SUB_VL:
8717     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8718   case RISCVISD::VWADD_W_VL:
8719   case RISCVISD::VWADDU_W_VL:
8720   case RISCVISD::VWSUB_W_VL:
8721   case RISCVISD::VWSUBU_W_VL:
8722     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8723   case RISCVISD::MUL_VL:
8724     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8725       return V;
8726     // Mul is commutative.
8727     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8728   case ISD::STORE: {
8729     auto *Store = cast<StoreSDNode>(N);
8730     SDValue Val = Store->getValue();
8731     // Combine store of vmv.x.s to vse with VL of 1.
8732     // FIXME: Support FP.
8733     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8734       SDValue Src = Val.getOperand(0);
8735       EVT VecVT = Src.getValueType();
8736       EVT MemVT = Store->getMemoryVT();
8737       // The memory VT and the element type must match.
8738       if (VecVT.getVectorElementType() == MemVT) {
8739         SDLoc DL(N);
8740         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8741         return DAG.getStoreVP(
8742             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8743             DAG.getConstant(1, DL, MaskVT),
8744             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8745             Store->getMemOperand(), Store->getAddressingMode(),
8746             Store->isTruncatingStore(), /*IsCompress*/ false);
8747       }
8748     }
8749 
8750     break;
8751   }
8752   case ISD::SPLAT_VECTOR: {
8753     EVT VT = N->getValueType(0);
8754     // Only perform this combine on legal MVT types.
8755     if (!isTypeLegal(VT))
8756       break;
8757     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8758                                          DAG, Subtarget))
8759       return Gather;
8760     break;
8761   }
8762   case RISCVISD::VMV_V_X_VL: {
8763     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8764     // scalar input.
8765     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8766     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8767     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8768       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8769         return SDValue(N, 0);
8770 
8771     break;
8772   }
8773   case ISD::INTRINSIC_WO_CHAIN: {
8774     unsigned IntNo = N->getConstantOperandVal(0);
8775     switch (IntNo) {
8776       // By default we do not combine any intrinsic.
8777     default:
8778       return SDValue();
8779     case Intrinsic::riscv_vcpop:
8780     case Intrinsic::riscv_vcpop_mask:
8781     case Intrinsic::riscv_vfirst:
8782     case Intrinsic::riscv_vfirst_mask: {
8783       SDValue VL = N->getOperand(2);
8784       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8785           IntNo == Intrinsic::riscv_vfirst_mask)
8786         VL = N->getOperand(3);
8787       if (!isNullConstant(VL))
8788         return SDValue();
8789       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8790       SDLoc DL(N);
8791       EVT VT = N->getValueType(0);
8792       if (IntNo == Intrinsic::riscv_vfirst ||
8793           IntNo == Intrinsic::riscv_vfirst_mask)
8794         return DAG.getConstant(-1, DL, VT);
8795       return DAG.getConstant(0, DL, VT);
8796     }
8797     }
8798   }
8799   }
8800 
8801   return SDValue();
8802 }
8803 
8804 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8805     const SDNode *N, CombineLevel Level) const {
8806   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8807   // materialised in fewer instructions than `(OP _, c1)`:
8808   //
8809   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8810   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8811   SDValue N0 = N->getOperand(0);
8812   EVT Ty = N0.getValueType();
8813   if (Ty.isScalarInteger() &&
8814       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8815     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8816     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8817     if (C1 && C2) {
8818       const APInt &C1Int = C1->getAPIntValue();
8819       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8820 
8821       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8822       // and the combine should happen, to potentially allow further combines
8823       // later.
8824       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8825           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8826         return true;
8827 
8828       // We can materialise `c1` in an add immediate, so it's "free", and the
8829       // combine should be prevented.
8830       if (C1Int.getMinSignedBits() <= 64 &&
8831           isLegalAddImmediate(C1Int.getSExtValue()))
8832         return false;
8833 
8834       // Neither constant will fit into an immediate, so find materialisation
8835       // costs.
8836       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8837                                               Subtarget.getFeatureBits(),
8838                                               /*CompressionCost*/true);
8839       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8840           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8841           /*CompressionCost*/true);
8842 
8843       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8844       // combine should be prevented.
8845       if (C1Cost < ShiftedC1Cost)
8846         return false;
8847     }
8848   }
8849   return true;
8850 }
8851 
8852 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8853     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8854     TargetLoweringOpt &TLO) const {
8855   // Delay this optimization as late as possible.
8856   if (!TLO.LegalOps)
8857     return false;
8858 
8859   EVT VT = Op.getValueType();
8860   if (VT.isVector())
8861     return false;
8862 
8863   // Only handle AND for now.
8864   if (Op.getOpcode() != ISD::AND)
8865     return false;
8866 
8867   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8868   if (!C)
8869     return false;
8870 
8871   const APInt &Mask = C->getAPIntValue();
8872 
8873   // Clear all non-demanded bits initially.
8874   APInt ShrunkMask = Mask & DemandedBits;
8875 
8876   // Try to make a smaller immediate by setting undemanded bits.
8877 
8878   APInt ExpandedMask = Mask | ~DemandedBits;
8879 
8880   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8881     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8882   };
8883   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8884     if (NewMask == Mask)
8885       return true;
8886     SDLoc DL(Op);
8887     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8888     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8889     return TLO.CombineTo(Op, NewOp);
8890   };
8891 
8892   // If the shrunk mask fits in sign extended 12 bits, let the target
8893   // independent code apply it.
8894   if (ShrunkMask.isSignedIntN(12))
8895     return false;
8896 
8897   // Preserve (and X, 0xffff) when zext.h is supported.
8898   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8899     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8900     if (IsLegalMask(NewMask))
8901       return UseMask(NewMask);
8902   }
8903 
8904   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8905   if (VT == MVT::i64) {
8906     APInt NewMask = APInt(64, 0xffffffff);
8907     if (IsLegalMask(NewMask))
8908       return UseMask(NewMask);
8909   }
8910 
8911   // For the remaining optimizations, we need to be able to make a negative
8912   // number through a combination of mask and undemanded bits.
8913   if (!ExpandedMask.isNegative())
8914     return false;
8915 
8916   // What is the fewest number of bits we need to represent the negative number.
8917   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8918 
8919   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8920   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8921   APInt NewMask = ShrunkMask;
8922   if (MinSignedBits <= 12)
8923     NewMask.setBitsFrom(11);
8924   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8925     NewMask.setBitsFrom(31);
8926   else
8927     return false;
8928 
8929   // Check that our new mask is a subset of the demanded mask.
8930   assert(IsLegalMask(NewMask));
8931   return UseMask(NewMask);
8932 }
8933 
8934 static void computeGREV(APInt &Src, unsigned ShAmt) {
8935   ShAmt &= Src.getBitWidth() - 1;
8936   uint64_t x = Src.getZExtValue();
8937   if (ShAmt & 1)
8938     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8939   if (ShAmt & 2)
8940     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8941   if (ShAmt & 4)
8942     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8943   if (ShAmt & 8)
8944     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8945   if (ShAmt & 16)
8946     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8947   if (ShAmt & 32)
8948     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8949   Src = x;
8950 }
8951 
8952 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8953                                                         KnownBits &Known,
8954                                                         const APInt &DemandedElts,
8955                                                         const SelectionDAG &DAG,
8956                                                         unsigned Depth) const {
8957   unsigned BitWidth = Known.getBitWidth();
8958   unsigned Opc = Op.getOpcode();
8959   assert((Opc >= ISD::BUILTIN_OP_END ||
8960           Opc == ISD::INTRINSIC_WO_CHAIN ||
8961           Opc == ISD::INTRINSIC_W_CHAIN ||
8962           Opc == ISD::INTRINSIC_VOID) &&
8963          "Should use MaskedValueIsZero if you don't know whether Op"
8964          " is a target node!");
8965 
8966   Known.resetAll();
8967   switch (Opc) {
8968   default: break;
8969   case RISCVISD::SELECT_CC: {
8970     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8971     // If we don't know any bits, early out.
8972     if (Known.isUnknown())
8973       break;
8974     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8975 
8976     // Only known if known in both the LHS and RHS.
8977     Known = KnownBits::commonBits(Known, Known2);
8978     break;
8979   }
8980   case RISCVISD::REMUW: {
8981     KnownBits Known2;
8982     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8983     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8984     // We only care about the lower 32 bits.
8985     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8986     // Restore the original width by sign extending.
8987     Known = Known.sext(BitWidth);
8988     break;
8989   }
8990   case RISCVISD::DIVUW: {
8991     KnownBits Known2;
8992     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8993     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8994     // We only care about the lower 32 bits.
8995     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8996     // Restore the original width by sign extending.
8997     Known = Known.sext(BitWidth);
8998     break;
8999   }
9000   case RISCVISD::CTZW: {
9001     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9002     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9003     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9004     Known.Zero.setBitsFrom(LowBits);
9005     break;
9006   }
9007   case RISCVISD::CLZW: {
9008     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9009     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9010     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9011     Known.Zero.setBitsFrom(LowBits);
9012     break;
9013   }
9014   case RISCVISD::GREV: {
9015     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9016       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9017       unsigned ShAmt = C->getZExtValue();
9018       computeGREV(Known.Zero, ShAmt);
9019       computeGREV(Known.One, ShAmt);
9020     }
9021     break;
9022   }
9023   case RISCVISD::READ_VLENB: {
9024     // If we know the minimum VLen from Zvl extensions, we can use that to
9025     // determine the trailing zeros of VLENB.
9026     // FIXME: Limit to 128 bit vectors until we have more testing.
9027     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9028     if (MinVLenB > 0)
9029       Known.Zero.setLowBits(Log2_32(MinVLenB));
9030     // We assume VLENB is no more than 65536 / 8 bytes.
9031     Known.Zero.setBitsFrom(14);
9032     break;
9033   }
9034   case ISD::INTRINSIC_W_CHAIN:
9035   case ISD::INTRINSIC_WO_CHAIN: {
9036     unsigned IntNo =
9037         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9038     switch (IntNo) {
9039     default:
9040       // We can't do anything for most intrinsics.
9041       break;
9042     case Intrinsic::riscv_vsetvli:
9043     case Intrinsic::riscv_vsetvlimax:
9044     case Intrinsic::riscv_vsetvli_opt:
9045     case Intrinsic::riscv_vsetvlimax_opt:
9046       // Assume that VL output is positive and would fit in an int32_t.
9047       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9048       if (BitWidth >= 32)
9049         Known.Zero.setBitsFrom(31);
9050       break;
9051     }
9052     break;
9053   }
9054   }
9055 }
9056 
9057 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9058     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9059     unsigned Depth) const {
9060   switch (Op.getOpcode()) {
9061   default:
9062     break;
9063   case RISCVISD::SELECT_CC: {
9064     unsigned Tmp =
9065         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9066     if (Tmp == 1) return 1;  // Early out.
9067     unsigned Tmp2 =
9068         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9069     return std::min(Tmp, Tmp2);
9070   }
9071   case RISCVISD::SLLW:
9072   case RISCVISD::SRAW:
9073   case RISCVISD::SRLW:
9074   case RISCVISD::DIVW:
9075   case RISCVISD::DIVUW:
9076   case RISCVISD::REMUW:
9077   case RISCVISD::ROLW:
9078   case RISCVISD::RORW:
9079   case RISCVISD::GREVW:
9080   case RISCVISD::GORCW:
9081   case RISCVISD::FSLW:
9082   case RISCVISD::FSRW:
9083   case RISCVISD::SHFLW:
9084   case RISCVISD::UNSHFLW:
9085   case RISCVISD::BCOMPRESSW:
9086   case RISCVISD::BDECOMPRESSW:
9087   case RISCVISD::BFPW:
9088   case RISCVISD::FCVT_W_RV64:
9089   case RISCVISD::FCVT_WU_RV64:
9090   case RISCVISD::STRICT_FCVT_W_RV64:
9091   case RISCVISD::STRICT_FCVT_WU_RV64:
9092     // TODO: As the result is sign-extended, this is conservatively correct. A
9093     // more precise answer could be calculated for SRAW depending on known
9094     // bits in the shift amount.
9095     return 33;
9096   case RISCVISD::SHFL:
9097   case RISCVISD::UNSHFL: {
9098     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9099     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9100     // will stay within the upper 32 bits. If there were more than 32 sign bits
9101     // before there will be at least 33 sign bits after.
9102     if (Op.getValueType() == MVT::i64 &&
9103         isa<ConstantSDNode>(Op.getOperand(1)) &&
9104         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9105       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9106       if (Tmp > 32)
9107         return 33;
9108     }
9109     break;
9110   }
9111   case RISCVISD::VMV_X_S: {
9112     // The number of sign bits of the scalar result is computed by obtaining the
9113     // element type of the input vector operand, subtracting its width from the
9114     // XLEN, and then adding one (sign bit within the element type). If the
9115     // element type is wider than XLen, the least-significant XLEN bits are
9116     // taken.
9117     unsigned XLen = Subtarget.getXLen();
9118     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9119     if (EltBits <= XLen)
9120       return XLen - EltBits + 1;
9121     break;
9122   }
9123   }
9124 
9125   return 1;
9126 }
9127 
9128 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9129                                                   MachineBasicBlock *BB) {
9130   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9131 
9132   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9133   // Should the count have wrapped while it was being read, we need to try
9134   // again.
9135   // ...
9136   // read:
9137   // rdcycleh x3 # load high word of cycle
9138   // rdcycle  x2 # load low word of cycle
9139   // rdcycleh x4 # load high word of cycle
9140   // bne x3, x4, read # check if high word reads match, otherwise try again
9141   // ...
9142 
9143   MachineFunction &MF = *BB->getParent();
9144   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9145   MachineFunction::iterator It = ++BB->getIterator();
9146 
9147   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9148   MF.insert(It, LoopMBB);
9149 
9150   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9151   MF.insert(It, DoneMBB);
9152 
9153   // Transfer the remainder of BB and its successor edges to DoneMBB.
9154   DoneMBB->splice(DoneMBB->begin(), BB,
9155                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9156   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9157 
9158   BB->addSuccessor(LoopMBB);
9159 
9160   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9161   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9162   Register LoReg = MI.getOperand(0).getReg();
9163   Register HiReg = MI.getOperand(1).getReg();
9164   DebugLoc DL = MI.getDebugLoc();
9165 
9166   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9167   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9168       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9169       .addReg(RISCV::X0);
9170   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9171       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9172       .addReg(RISCV::X0);
9173   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9174       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9175       .addReg(RISCV::X0);
9176 
9177   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9178       .addReg(HiReg)
9179       .addReg(ReadAgainReg)
9180       .addMBB(LoopMBB);
9181 
9182   LoopMBB->addSuccessor(LoopMBB);
9183   LoopMBB->addSuccessor(DoneMBB);
9184 
9185   MI.eraseFromParent();
9186 
9187   return DoneMBB;
9188 }
9189 
9190 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9191                                              MachineBasicBlock *BB) {
9192   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9193 
9194   MachineFunction &MF = *BB->getParent();
9195   DebugLoc DL = MI.getDebugLoc();
9196   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9197   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9198   Register LoReg = MI.getOperand(0).getReg();
9199   Register HiReg = MI.getOperand(1).getReg();
9200   Register SrcReg = MI.getOperand(2).getReg();
9201   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9202   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9203 
9204   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9205                           RI);
9206   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9207   MachineMemOperand *MMOLo =
9208       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9209   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9210       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9211   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9212       .addFrameIndex(FI)
9213       .addImm(0)
9214       .addMemOperand(MMOLo);
9215   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9216       .addFrameIndex(FI)
9217       .addImm(4)
9218       .addMemOperand(MMOHi);
9219   MI.eraseFromParent(); // The pseudo instruction is gone now.
9220   return BB;
9221 }
9222 
9223 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9224                                                  MachineBasicBlock *BB) {
9225   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9226          "Unexpected instruction");
9227 
9228   MachineFunction &MF = *BB->getParent();
9229   DebugLoc DL = MI.getDebugLoc();
9230   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9231   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9232   Register DstReg = MI.getOperand(0).getReg();
9233   Register LoReg = MI.getOperand(1).getReg();
9234   Register HiReg = MI.getOperand(2).getReg();
9235   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9236   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9237 
9238   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9239   MachineMemOperand *MMOLo =
9240       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9241   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9242       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9243   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9244       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9245       .addFrameIndex(FI)
9246       .addImm(0)
9247       .addMemOperand(MMOLo);
9248   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9249       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9250       .addFrameIndex(FI)
9251       .addImm(4)
9252       .addMemOperand(MMOHi);
9253   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9254   MI.eraseFromParent(); // The pseudo instruction is gone now.
9255   return BB;
9256 }
9257 
9258 static bool isSelectPseudo(MachineInstr &MI) {
9259   switch (MI.getOpcode()) {
9260   default:
9261     return false;
9262   case RISCV::Select_GPR_Using_CC_GPR:
9263   case RISCV::Select_FPR16_Using_CC_GPR:
9264   case RISCV::Select_FPR32_Using_CC_GPR:
9265   case RISCV::Select_FPR64_Using_CC_GPR:
9266     return true;
9267   }
9268 }
9269 
9270 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9271                                         unsigned RelOpcode, unsigned EqOpcode,
9272                                         const RISCVSubtarget &Subtarget) {
9273   DebugLoc DL = MI.getDebugLoc();
9274   Register DstReg = MI.getOperand(0).getReg();
9275   Register Src1Reg = MI.getOperand(1).getReg();
9276   Register Src2Reg = MI.getOperand(2).getReg();
9277   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9278   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9279   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9280 
9281   // Save the current FFLAGS.
9282   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9283 
9284   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9285                  .addReg(Src1Reg)
9286                  .addReg(Src2Reg);
9287   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9288     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9289 
9290   // Restore the FFLAGS.
9291   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9292       .addReg(SavedFFlags, RegState::Kill);
9293 
9294   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9295   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9296                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9297                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9298   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9299     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9300 
9301   // Erase the pseudoinstruction.
9302   MI.eraseFromParent();
9303   return BB;
9304 }
9305 
9306 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9307                                            MachineBasicBlock *BB,
9308                                            const RISCVSubtarget &Subtarget) {
9309   // To "insert" Select_* instructions, we actually have to insert the triangle
9310   // control-flow pattern.  The incoming instructions know the destination vreg
9311   // to set, the condition code register to branch on, the true/false values to
9312   // select between, and the condcode to use to select the appropriate branch.
9313   //
9314   // We produce the following control flow:
9315   //     HeadMBB
9316   //     |  \
9317   //     |  IfFalseMBB
9318   //     | /
9319   //    TailMBB
9320   //
9321   // When we find a sequence of selects we attempt to optimize their emission
9322   // by sharing the control flow. Currently we only handle cases where we have
9323   // multiple selects with the exact same condition (same LHS, RHS and CC).
9324   // The selects may be interleaved with other instructions if the other
9325   // instructions meet some requirements we deem safe:
9326   // - They are debug instructions. Otherwise,
9327   // - They do not have side-effects, do not access memory and their inputs do
9328   //   not depend on the results of the select pseudo-instructions.
9329   // The TrueV/FalseV operands of the selects cannot depend on the result of
9330   // previous selects in the sequence.
9331   // These conditions could be further relaxed. See the X86 target for a
9332   // related approach and more information.
9333   Register LHS = MI.getOperand(1).getReg();
9334   Register RHS = MI.getOperand(2).getReg();
9335   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9336 
9337   SmallVector<MachineInstr *, 4> SelectDebugValues;
9338   SmallSet<Register, 4> SelectDests;
9339   SelectDests.insert(MI.getOperand(0).getReg());
9340 
9341   MachineInstr *LastSelectPseudo = &MI;
9342 
9343   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9344        SequenceMBBI != E; ++SequenceMBBI) {
9345     if (SequenceMBBI->isDebugInstr())
9346       continue;
9347     else if (isSelectPseudo(*SequenceMBBI)) {
9348       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9349           SequenceMBBI->getOperand(2).getReg() != RHS ||
9350           SequenceMBBI->getOperand(3).getImm() != CC ||
9351           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9352           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9353         break;
9354       LastSelectPseudo = &*SequenceMBBI;
9355       SequenceMBBI->collectDebugValues(SelectDebugValues);
9356       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9357     } else {
9358       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9359           SequenceMBBI->mayLoadOrStore())
9360         break;
9361       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9362             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9363           }))
9364         break;
9365     }
9366   }
9367 
9368   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9369   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9370   DebugLoc DL = MI.getDebugLoc();
9371   MachineFunction::iterator I = ++BB->getIterator();
9372 
9373   MachineBasicBlock *HeadMBB = BB;
9374   MachineFunction *F = BB->getParent();
9375   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9376   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9377 
9378   F->insert(I, IfFalseMBB);
9379   F->insert(I, TailMBB);
9380 
9381   // Transfer debug instructions associated with the selects to TailMBB.
9382   for (MachineInstr *DebugInstr : SelectDebugValues) {
9383     TailMBB->push_back(DebugInstr->removeFromParent());
9384   }
9385 
9386   // Move all instructions after the sequence to TailMBB.
9387   TailMBB->splice(TailMBB->end(), HeadMBB,
9388                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9389   // Update machine-CFG edges by transferring all successors of the current
9390   // block to the new block which will contain the Phi nodes for the selects.
9391   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9392   // Set the successors for HeadMBB.
9393   HeadMBB->addSuccessor(IfFalseMBB);
9394   HeadMBB->addSuccessor(TailMBB);
9395 
9396   // Insert appropriate branch.
9397   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9398     .addReg(LHS)
9399     .addReg(RHS)
9400     .addMBB(TailMBB);
9401 
9402   // IfFalseMBB just falls through to TailMBB.
9403   IfFalseMBB->addSuccessor(TailMBB);
9404 
9405   // Create PHIs for all of the select pseudo-instructions.
9406   auto SelectMBBI = MI.getIterator();
9407   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9408   auto InsertionPoint = TailMBB->begin();
9409   while (SelectMBBI != SelectEnd) {
9410     auto Next = std::next(SelectMBBI);
9411     if (isSelectPseudo(*SelectMBBI)) {
9412       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9413       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9414               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9415           .addReg(SelectMBBI->getOperand(4).getReg())
9416           .addMBB(HeadMBB)
9417           .addReg(SelectMBBI->getOperand(5).getReg())
9418           .addMBB(IfFalseMBB);
9419       SelectMBBI->eraseFromParent();
9420     }
9421     SelectMBBI = Next;
9422   }
9423 
9424   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9425   return TailMBB;
9426 }
9427 
9428 MachineBasicBlock *
9429 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9430                                                  MachineBasicBlock *BB) const {
9431   switch (MI.getOpcode()) {
9432   default:
9433     llvm_unreachable("Unexpected instr type to insert");
9434   case RISCV::ReadCycleWide:
9435     assert(!Subtarget.is64Bit() &&
9436            "ReadCycleWrite is only to be used on riscv32");
9437     return emitReadCycleWidePseudo(MI, BB);
9438   case RISCV::Select_GPR_Using_CC_GPR:
9439   case RISCV::Select_FPR16_Using_CC_GPR:
9440   case RISCV::Select_FPR32_Using_CC_GPR:
9441   case RISCV::Select_FPR64_Using_CC_GPR:
9442     return emitSelectPseudo(MI, BB, Subtarget);
9443   case RISCV::BuildPairF64Pseudo:
9444     return emitBuildPairF64Pseudo(MI, BB);
9445   case RISCV::SplitF64Pseudo:
9446     return emitSplitF64Pseudo(MI, BB);
9447   case RISCV::PseudoQuietFLE_H:
9448     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9449   case RISCV::PseudoQuietFLT_H:
9450     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9451   case RISCV::PseudoQuietFLE_S:
9452     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9453   case RISCV::PseudoQuietFLT_S:
9454     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9455   case RISCV::PseudoQuietFLE_D:
9456     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9457   case RISCV::PseudoQuietFLT_D:
9458     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9459   }
9460 }
9461 
9462 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9463                                                         SDNode *Node) const {
9464   // Add FRM dependency to any instructions with dynamic rounding mode.
9465   unsigned Opc = MI.getOpcode();
9466   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9467   if (Idx < 0)
9468     return;
9469   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9470     return;
9471   // If the instruction already reads FRM, don't add another read.
9472   if (MI.readsRegister(RISCV::FRM))
9473     return;
9474   MI.addOperand(
9475       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9476 }
9477 
9478 // Calling Convention Implementation.
9479 // The expectations for frontend ABI lowering vary from target to target.
9480 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9481 // details, but this is a longer term goal. For now, we simply try to keep the
9482 // role of the frontend as simple and well-defined as possible. The rules can
9483 // be summarised as:
9484 // * Never split up large scalar arguments. We handle them here.
9485 // * If a hardfloat calling convention is being used, and the struct may be
9486 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9487 // available, then pass as two separate arguments. If either the GPRs or FPRs
9488 // are exhausted, then pass according to the rule below.
9489 // * If a struct could never be passed in registers or directly in a stack
9490 // slot (as it is larger than 2*XLEN and the floating point rules don't
9491 // apply), then pass it using a pointer with the byval attribute.
9492 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9493 // word-sized array or a 2*XLEN scalar (depending on alignment).
9494 // * The frontend can determine whether a struct is returned by reference or
9495 // not based on its size and fields. If it will be returned by reference, the
9496 // frontend must modify the prototype so a pointer with the sret annotation is
9497 // passed as the first argument. This is not necessary for large scalar
9498 // returns.
9499 // * Struct return values and varargs should be coerced to structs containing
9500 // register-size fields in the same situations they would be for fixed
9501 // arguments.
9502 
9503 static const MCPhysReg ArgGPRs[] = {
9504   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9505   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9506 };
9507 static const MCPhysReg ArgFPR16s[] = {
9508   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9509   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9510 };
9511 static const MCPhysReg ArgFPR32s[] = {
9512   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9513   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9514 };
9515 static const MCPhysReg ArgFPR64s[] = {
9516   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9517   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9518 };
9519 // This is an interim calling convention and it may be changed in the future.
9520 static const MCPhysReg ArgVRs[] = {
9521     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9522     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9523     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9524 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9525                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9526                                      RISCV::V20M2, RISCV::V22M2};
9527 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9528                                      RISCV::V20M4};
9529 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9530 
9531 // Pass a 2*XLEN argument that has been split into two XLEN values through
9532 // registers or the stack as necessary.
9533 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9534                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9535                                 MVT ValVT2, MVT LocVT2,
9536                                 ISD::ArgFlagsTy ArgFlags2) {
9537   unsigned XLenInBytes = XLen / 8;
9538   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9539     // At least one half can be passed via register.
9540     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9541                                      VA1.getLocVT(), CCValAssign::Full));
9542   } else {
9543     // Both halves must be passed on the stack, with proper alignment.
9544     Align StackAlign =
9545         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9546     State.addLoc(
9547         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9548                             State.AllocateStack(XLenInBytes, StackAlign),
9549                             VA1.getLocVT(), CCValAssign::Full));
9550     State.addLoc(CCValAssign::getMem(
9551         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9552         LocVT2, CCValAssign::Full));
9553     return false;
9554   }
9555 
9556   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9557     // The second half can also be passed via register.
9558     State.addLoc(
9559         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9560   } else {
9561     // The second half is passed via the stack, without additional alignment.
9562     State.addLoc(CCValAssign::getMem(
9563         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9564         LocVT2, CCValAssign::Full));
9565   }
9566 
9567   return false;
9568 }
9569 
9570 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9571                                Optional<unsigned> FirstMaskArgument,
9572                                CCState &State, const RISCVTargetLowering &TLI) {
9573   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9574   if (RC == &RISCV::VRRegClass) {
9575     // Assign the first mask argument to V0.
9576     // This is an interim calling convention and it may be changed in the
9577     // future.
9578     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9579       return State.AllocateReg(RISCV::V0);
9580     return State.AllocateReg(ArgVRs);
9581   }
9582   if (RC == &RISCV::VRM2RegClass)
9583     return State.AllocateReg(ArgVRM2s);
9584   if (RC == &RISCV::VRM4RegClass)
9585     return State.AllocateReg(ArgVRM4s);
9586   if (RC == &RISCV::VRM8RegClass)
9587     return State.AllocateReg(ArgVRM8s);
9588   llvm_unreachable("Unhandled register class for ValueType");
9589 }
9590 
9591 // Implements the RISC-V calling convention. Returns true upon failure.
9592 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9593                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9594                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9595                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9596                      Optional<unsigned> FirstMaskArgument) {
9597   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9598   assert(XLen == 32 || XLen == 64);
9599   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9600 
9601   // Any return value split in to more than two values can't be returned
9602   // directly. Vectors are returned via the available vector registers.
9603   if (!LocVT.isVector() && IsRet && ValNo > 1)
9604     return true;
9605 
9606   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9607   // variadic argument, or if no F16/F32 argument registers are available.
9608   bool UseGPRForF16_F32 = true;
9609   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9610   // variadic argument, or if no F64 argument registers are available.
9611   bool UseGPRForF64 = true;
9612 
9613   switch (ABI) {
9614   default:
9615     llvm_unreachable("Unexpected ABI");
9616   case RISCVABI::ABI_ILP32:
9617   case RISCVABI::ABI_LP64:
9618     break;
9619   case RISCVABI::ABI_ILP32F:
9620   case RISCVABI::ABI_LP64F:
9621     UseGPRForF16_F32 = !IsFixed;
9622     break;
9623   case RISCVABI::ABI_ILP32D:
9624   case RISCVABI::ABI_LP64D:
9625     UseGPRForF16_F32 = !IsFixed;
9626     UseGPRForF64 = !IsFixed;
9627     break;
9628   }
9629 
9630   // FPR16, FPR32, and FPR64 alias each other.
9631   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9632     UseGPRForF16_F32 = true;
9633     UseGPRForF64 = true;
9634   }
9635 
9636   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9637   // similar local variables rather than directly checking against the target
9638   // ABI.
9639 
9640   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9641     LocVT = XLenVT;
9642     LocInfo = CCValAssign::BCvt;
9643   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9644     LocVT = MVT::i64;
9645     LocInfo = CCValAssign::BCvt;
9646   }
9647 
9648   // If this is a variadic argument, the RISC-V calling convention requires
9649   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9650   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9651   // be used regardless of whether the original argument was split during
9652   // legalisation or not. The argument will not be passed by registers if the
9653   // original type is larger than 2*XLEN, so the register alignment rule does
9654   // not apply.
9655   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9656   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9657       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9658     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9659     // Skip 'odd' register if necessary.
9660     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9661       State.AllocateReg(ArgGPRs);
9662   }
9663 
9664   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9665   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9666       State.getPendingArgFlags();
9667 
9668   assert(PendingLocs.size() == PendingArgFlags.size() &&
9669          "PendingLocs and PendingArgFlags out of sync");
9670 
9671   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9672   // registers are exhausted.
9673   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9674     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9675            "Can't lower f64 if it is split");
9676     // Depending on available argument GPRS, f64 may be passed in a pair of
9677     // GPRs, split between a GPR and the stack, or passed completely on the
9678     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9679     // cases.
9680     Register Reg = State.AllocateReg(ArgGPRs);
9681     LocVT = MVT::i32;
9682     if (!Reg) {
9683       unsigned StackOffset = State.AllocateStack(8, Align(8));
9684       State.addLoc(
9685           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9686       return false;
9687     }
9688     if (!State.AllocateReg(ArgGPRs))
9689       State.AllocateStack(4, Align(4));
9690     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9691     return false;
9692   }
9693 
9694   // Fixed-length vectors are located in the corresponding scalable-vector
9695   // container types.
9696   if (ValVT.isFixedLengthVector())
9697     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9698 
9699   // Split arguments might be passed indirectly, so keep track of the pending
9700   // values. Split vectors are passed via a mix of registers and indirectly, so
9701   // treat them as we would any other argument.
9702   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9703     LocVT = XLenVT;
9704     LocInfo = CCValAssign::Indirect;
9705     PendingLocs.push_back(
9706         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9707     PendingArgFlags.push_back(ArgFlags);
9708     if (!ArgFlags.isSplitEnd()) {
9709       return false;
9710     }
9711   }
9712 
9713   // If the split argument only had two elements, it should be passed directly
9714   // in registers or on the stack.
9715   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9716       PendingLocs.size() <= 2) {
9717     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9718     // Apply the normal calling convention rules to the first half of the
9719     // split argument.
9720     CCValAssign VA = PendingLocs[0];
9721     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9722     PendingLocs.clear();
9723     PendingArgFlags.clear();
9724     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9725                                ArgFlags);
9726   }
9727 
9728   // Allocate to a register if possible, or else a stack slot.
9729   Register Reg;
9730   unsigned StoreSizeBytes = XLen / 8;
9731   Align StackAlign = Align(XLen / 8);
9732 
9733   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9734     Reg = State.AllocateReg(ArgFPR16s);
9735   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9736     Reg = State.AllocateReg(ArgFPR32s);
9737   else if (ValVT == MVT::f64 && !UseGPRForF64)
9738     Reg = State.AllocateReg(ArgFPR64s);
9739   else if (ValVT.isVector()) {
9740     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9741     if (!Reg) {
9742       // For return values, the vector must be passed fully via registers or
9743       // via the stack.
9744       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9745       // but we're using all of them.
9746       if (IsRet)
9747         return true;
9748       // Try using a GPR to pass the address
9749       if ((Reg = State.AllocateReg(ArgGPRs))) {
9750         LocVT = XLenVT;
9751         LocInfo = CCValAssign::Indirect;
9752       } else if (ValVT.isScalableVector()) {
9753         LocVT = XLenVT;
9754         LocInfo = CCValAssign::Indirect;
9755       } else {
9756         // Pass fixed-length vectors on the stack.
9757         LocVT = ValVT;
9758         StoreSizeBytes = ValVT.getStoreSize();
9759         // Align vectors to their element sizes, being careful for vXi1
9760         // vectors.
9761         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9762       }
9763     }
9764   } else {
9765     Reg = State.AllocateReg(ArgGPRs);
9766   }
9767 
9768   unsigned StackOffset =
9769       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9770 
9771   // If we reach this point and PendingLocs is non-empty, we must be at the
9772   // end of a split argument that must be passed indirectly.
9773   if (!PendingLocs.empty()) {
9774     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9775     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9776 
9777     for (auto &It : PendingLocs) {
9778       if (Reg)
9779         It.convertToReg(Reg);
9780       else
9781         It.convertToMem(StackOffset);
9782       State.addLoc(It);
9783     }
9784     PendingLocs.clear();
9785     PendingArgFlags.clear();
9786     return false;
9787   }
9788 
9789   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9790           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9791          "Expected an XLenVT or vector types at this stage");
9792 
9793   if (Reg) {
9794     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9795     return false;
9796   }
9797 
9798   // When a floating-point value is passed on the stack, no bit-conversion is
9799   // needed.
9800   if (ValVT.isFloatingPoint()) {
9801     LocVT = ValVT;
9802     LocInfo = CCValAssign::Full;
9803   }
9804   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9805   return false;
9806 }
9807 
9808 template <typename ArgTy>
9809 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9810   for (const auto &ArgIdx : enumerate(Args)) {
9811     MVT ArgVT = ArgIdx.value().VT;
9812     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9813       return ArgIdx.index();
9814   }
9815   return None;
9816 }
9817 
9818 void RISCVTargetLowering::analyzeInputArgs(
9819     MachineFunction &MF, CCState &CCInfo,
9820     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9821     RISCVCCAssignFn Fn) const {
9822   unsigned NumArgs = Ins.size();
9823   FunctionType *FType = MF.getFunction().getFunctionType();
9824 
9825   Optional<unsigned> FirstMaskArgument;
9826   if (Subtarget.hasVInstructions())
9827     FirstMaskArgument = preAssignMask(Ins);
9828 
9829   for (unsigned i = 0; i != NumArgs; ++i) {
9830     MVT ArgVT = Ins[i].VT;
9831     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9832 
9833     Type *ArgTy = nullptr;
9834     if (IsRet)
9835       ArgTy = FType->getReturnType();
9836     else if (Ins[i].isOrigArg())
9837       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9838 
9839     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9840     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9841            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9842            FirstMaskArgument)) {
9843       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9844                         << EVT(ArgVT).getEVTString() << '\n');
9845       llvm_unreachable(nullptr);
9846     }
9847   }
9848 }
9849 
9850 void RISCVTargetLowering::analyzeOutputArgs(
9851     MachineFunction &MF, CCState &CCInfo,
9852     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9853     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9854   unsigned NumArgs = Outs.size();
9855 
9856   Optional<unsigned> FirstMaskArgument;
9857   if (Subtarget.hasVInstructions())
9858     FirstMaskArgument = preAssignMask(Outs);
9859 
9860   for (unsigned i = 0; i != NumArgs; i++) {
9861     MVT ArgVT = Outs[i].VT;
9862     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9863     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9864 
9865     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9866     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9867            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9868            FirstMaskArgument)) {
9869       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9870                         << EVT(ArgVT).getEVTString() << "\n");
9871       llvm_unreachable(nullptr);
9872     }
9873   }
9874 }
9875 
9876 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9877 // values.
9878 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9879                                    const CCValAssign &VA, const SDLoc &DL,
9880                                    const RISCVSubtarget &Subtarget) {
9881   switch (VA.getLocInfo()) {
9882   default:
9883     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9884   case CCValAssign::Full:
9885     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9886       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9887     break;
9888   case CCValAssign::BCvt:
9889     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9890       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9891     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9892       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9893     else
9894       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9895     break;
9896   }
9897   return Val;
9898 }
9899 
9900 // The caller is responsible for loading the full value if the argument is
9901 // passed with CCValAssign::Indirect.
9902 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9903                                 const CCValAssign &VA, const SDLoc &DL,
9904                                 const RISCVTargetLowering &TLI) {
9905   MachineFunction &MF = DAG.getMachineFunction();
9906   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9907   EVT LocVT = VA.getLocVT();
9908   SDValue Val;
9909   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9910   Register VReg = RegInfo.createVirtualRegister(RC);
9911   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9912   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9913 
9914   if (VA.getLocInfo() == CCValAssign::Indirect)
9915     return Val;
9916 
9917   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9918 }
9919 
9920 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9921                                    const CCValAssign &VA, const SDLoc &DL,
9922                                    const RISCVSubtarget &Subtarget) {
9923   EVT LocVT = VA.getLocVT();
9924 
9925   switch (VA.getLocInfo()) {
9926   default:
9927     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9928   case CCValAssign::Full:
9929     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9930       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9931     break;
9932   case CCValAssign::BCvt:
9933     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9934       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9935     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9936       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9937     else
9938       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9939     break;
9940   }
9941   return Val;
9942 }
9943 
9944 // The caller is responsible for loading the full value if the argument is
9945 // passed with CCValAssign::Indirect.
9946 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9947                                 const CCValAssign &VA, const SDLoc &DL) {
9948   MachineFunction &MF = DAG.getMachineFunction();
9949   MachineFrameInfo &MFI = MF.getFrameInfo();
9950   EVT LocVT = VA.getLocVT();
9951   EVT ValVT = VA.getValVT();
9952   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9953   if (ValVT.isScalableVector()) {
9954     // When the value is a scalable vector, we save the pointer which points to
9955     // the scalable vector value in the stack. The ValVT will be the pointer
9956     // type, instead of the scalable vector type.
9957     ValVT = LocVT;
9958   }
9959   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9960                                  /*IsImmutable=*/true);
9961   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9962   SDValue Val;
9963 
9964   ISD::LoadExtType ExtType;
9965   switch (VA.getLocInfo()) {
9966   default:
9967     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9968   case CCValAssign::Full:
9969   case CCValAssign::Indirect:
9970   case CCValAssign::BCvt:
9971     ExtType = ISD::NON_EXTLOAD;
9972     break;
9973   }
9974   Val = DAG.getExtLoad(
9975       ExtType, DL, LocVT, Chain, FIN,
9976       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9977   return Val;
9978 }
9979 
9980 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9981                                        const CCValAssign &VA, const SDLoc &DL) {
9982   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9983          "Unexpected VA");
9984   MachineFunction &MF = DAG.getMachineFunction();
9985   MachineFrameInfo &MFI = MF.getFrameInfo();
9986   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9987 
9988   if (VA.isMemLoc()) {
9989     // f64 is passed on the stack.
9990     int FI =
9991         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9992     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9993     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9994                        MachinePointerInfo::getFixedStack(MF, FI));
9995   }
9996 
9997   assert(VA.isRegLoc() && "Expected register VA assignment");
9998 
9999   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10000   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10001   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10002   SDValue Hi;
10003   if (VA.getLocReg() == RISCV::X17) {
10004     // Second half of f64 is passed on the stack.
10005     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10006     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10007     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10008                      MachinePointerInfo::getFixedStack(MF, FI));
10009   } else {
10010     // Second half of f64 is passed in another GPR.
10011     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10012     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10013     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10014   }
10015   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10016 }
10017 
10018 // FastCC has less than 1% performance improvement for some particular
10019 // benchmark. But theoretically, it may has benenfit for some cases.
10020 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10021                             unsigned ValNo, MVT ValVT, MVT LocVT,
10022                             CCValAssign::LocInfo LocInfo,
10023                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10024                             bool IsFixed, bool IsRet, Type *OrigTy,
10025                             const RISCVTargetLowering &TLI,
10026                             Optional<unsigned> FirstMaskArgument) {
10027 
10028   // X5 and X6 might be used for save-restore libcall.
10029   static const MCPhysReg GPRList[] = {
10030       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10031       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10032       RISCV::X29, RISCV::X30, RISCV::X31};
10033 
10034   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10035     if (unsigned Reg = State.AllocateReg(GPRList)) {
10036       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10037       return false;
10038     }
10039   }
10040 
10041   if (LocVT == MVT::f16) {
10042     static const MCPhysReg FPR16List[] = {
10043         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10044         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10045         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10046         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10047     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10048       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10049       return false;
10050     }
10051   }
10052 
10053   if (LocVT == MVT::f32) {
10054     static const MCPhysReg FPR32List[] = {
10055         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10056         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10057         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10058         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10059     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10060       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10061       return false;
10062     }
10063   }
10064 
10065   if (LocVT == MVT::f64) {
10066     static const MCPhysReg FPR64List[] = {
10067         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10068         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10069         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10070         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10071     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10072       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10073       return false;
10074     }
10075   }
10076 
10077   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10078     unsigned Offset4 = State.AllocateStack(4, Align(4));
10079     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10080     return false;
10081   }
10082 
10083   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10084     unsigned Offset5 = State.AllocateStack(8, Align(8));
10085     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10086     return false;
10087   }
10088 
10089   if (LocVT.isVector()) {
10090     if (unsigned Reg =
10091             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10092       // Fixed-length vectors are located in the corresponding scalable-vector
10093       // container types.
10094       if (ValVT.isFixedLengthVector())
10095         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10096       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10097     } else {
10098       // Try and pass the address via a "fast" GPR.
10099       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10100         LocInfo = CCValAssign::Indirect;
10101         LocVT = TLI.getSubtarget().getXLenVT();
10102         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10103       } else if (ValVT.isFixedLengthVector()) {
10104         auto StackAlign =
10105             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10106         unsigned StackOffset =
10107             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10108         State.addLoc(
10109             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10110       } else {
10111         // Can't pass scalable vectors on the stack.
10112         return true;
10113       }
10114     }
10115 
10116     return false;
10117   }
10118 
10119   return true; // CC didn't match.
10120 }
10121 
10122 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10123                          CCValAssign::LocInfo LocInfo,
10124                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10125 
10126   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10127     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10128     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10129     static const MCPhysReg GPRList[] = {
10130         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10131         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10132     if (unsigned Reg = State.AllocateReg(GPRList)) {
10133       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10134       return false;
10135     }
10136   }
10137 
10138   if (LocVT == MVT::f32) {
10139     // Pass in STG registers: F1, ..., F6
10140     //                        fs0 ... fs5
10141     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10142                                           RISCV::F18_F, RISCV::F19_F,
10143                                           RISCV::F20_F, RISCV::F21_F};
10144     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10145       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10146       return false;
10147     }
10148   }
10149 
10150   if (LocVT == MVT::f64) {
10151     // Pass in STG registers: D1, ..., D6
10152     //                        fs6 ... fs11
10153     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10154                                           RISCV::F24_D, RISCV::F25_D,
10155                                           RISCV::F26_D, RISCV::F27_D};
10156     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10157       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10158       return false;
10159     }
10160   }
10161 
10162   report_fatal_error("No registers left in GHC calling convention");
10163   return true;
10164 }
10165 
10166 // Transform physical registers into virtual registers.
10167 SDValue RISCVTargetLowering::LowerFormalArguments(
10168     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10169     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10170     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10171 
10172   MachineFunction &MF = DAG.getMachineFunction();
10173 
10174   switch (CallConv) {
10175   default:
10176     report_fatal_error("Unsupported calling convention");
10177   case CallingConv::C:
10178   case CallingConv::Fast:
10179     break;
10180   case CallingConv::GHC:
10181     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10182         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10183       report_fatal_error(
10184         "GHC calling convention requires the F and D instruction set extensions");
10185   }
10186 
10187   const Function &Func = MF.getFunction();
10188   if (Func.hasFnAttribute("interrupt")) {
10189     if (!Func.arg_empty())
10190       report_fatal_error(
10191         "Functions with the interrupt attribute cannot have arguments!");
10192 
10193     StringRef Kind =
10194       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10195 
10196     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10197       report_fatal_error(
10198         "Function interrupt attribute argument not supported!");
10199   }
10200 
10201   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10202   MVT XLenVT = Subtarget.getXLenVT();
10203   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10204   // Used with vargs to acumulate store chains.
10205   std::vector<SDValue> OutChains;
10206 
10207   // Assign locations to all of the incoming arguments.
10208   SmallVector<CCValAssign, 16> ArgLocs;
10209   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10210 
10211   if (CallConv == CallingConv::GHC)
10212     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10213   else
10214     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10215                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10216                                                    : CC_RISCV);
10217 
10218   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10219     CCValAssign &VA = ArgLocs[i];
10220     SDValue ArgValue;
10221     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10222     // case.
10223     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10224       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10225     else if (VA.isRegLoc())
10226       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10227     else
10228       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10229 
10230     if (VA.getLocInfo() == CCValAssign::Indirect) {
10231       // If the original argument was split and passed by reference (e.g. i128
10232       // on RV32), we need to load all parts of it here (using the same
10233       // address). Vectors may be partly split to registers and partly to the
10234       // stack, in which case the base address is partly offset and subsequent
10235       // stores are relative to that.
10236       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10237                                    MachinePointerInfo()));
10238       unsigned ArgIndex = Ins[i].OrigArgIndex;
10239       unsigned ArgPartOffset = Ins[i].PartOffset;
10240       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10241       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10242         CCValAssign &PartVA = ArgLocs[i + 1];
10243         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10244         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10245         if (PartVA.getValVT().isScalableVector())
10246           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10247         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10248         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10249                                      MachinePointerInfo()));
10250         ++i;
10251       }
10252       continue;
10253     }
10254     InVals.push_back(ArgValue);
10255   }
10256 
10257   if (IsVarArg) {
10258     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10259     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10260     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10261     MachineFrameInfo &MFI = MF.getFrameInfo();
10262     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10263     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10264 
10265     // Offset of the first variable argument from stack pointer, and size of
10266     // the vararg save area. For now, the varargs save area is either zero or
10267     // large enough to hold a0-a7.
10268     int VaArgOffset, VarArgsSaveSize;
10269 
10270     // If all registers are allocated, then all varargs must be passed on the
10271     // stack and we don't need to save any argregs.
10272     if (ArgRegs.size() == Idx) {
10273       VaArgOffset = CCInfo.getNextStackOffset();
10274       VarArgsSaveSize = 0;
10275     } else {
10276       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10277       VaArgOffset = -VarArgsSaveSize;
10278     }
10279 
10280     // Record the frame index of the first variable argument
10281     // which is a value necessary to VASTART.
10282     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10283     RVFI->setVarArgsFrameIndex(FI);
10284 
10285     // If saving an odd number of registers then create an extra stack slot to
10286     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10287     // offsets to even-numbered registered remain 2*XLEN-aligned.
10288     if (Idx % 2) {
10289       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10290       VarArgsSaveSize += XLenInBytes;
10291     }
10292 
10293     // Copy the integer registers that may have been used for passing varargs
10294     // to the vararg save area.
10295     for (unsigned I = Idx; I < ArgRegs.size();
10296          ++I, VaArgOffset += XLenInBytes) {
10297       const Register Reg = RegInfo.createVirtualRegister(RC);
10298       RegInfo.addLiveIn(ArgRegs[I], Reg);
10299       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10300       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10301       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10302       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10303                                    MachinePointerInfo::getFixedStack(MF, FI));
10304       cast<StoreSDNode>(Store.getNode())
10305           ->getMemOperand()
10306           ->setValue((Value *)nullptr);
10307       OutChains.push_back(Store);
10308     }
10309     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10310   }
10311 
10312   // All stores are grouped in one node to allow the matching between
10313   // the size of Ins and InVals. This only happens for vararg functions.
10314   if (!OutChains.empty()) {
10315     OutChains.push_back(Chain);
10316     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10317   }
10318 
10319   return Chain;
10320 }
10321 
10322 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10323 /// for tail call optimization.
10324 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10325 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10326     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10327     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10328 
10329   auto &Callee = CLI.Callee;
10330   auto CalleeCC = CLI.CallConv;
10331   auto &Outs = CLI.Outs;
10332   auto &Caller = MF.getFunction();
10333   auto CallerCC = Caller.getCallingConv();
10334 
10335   // Exception-handling functions need a special set of instructions to
10336   // indicate a return to the hardware. Tail-calling another function would
10337   // probably break this.
10338   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10339   // should be expanded as new function attributes are introduced.
10340   if (Caller.hasFnAttribute("interrupt"))
10341     return false;
10342 
10343   // Do not tail call opt if the stack is used to pass parameters.
10344   if (CCInfo.getNextStackOffset() != 0)
10345     return false;
10346 
10347   // Do not tail call opt if any parameters need to be passed indirectly.
10348   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10349   // passed indirectly. So the address of the value will be passed in a
10350   // register, or if not available, then the address is put on the stack. In
10351   // order to pass indirectly, space on the stack often needs to be allocated
10352   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10353   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10354   // are passed CCValAssign::Indirect.
10355   for (auto &VA : ArgLocs)
10356     if (VA.getLocInfo() == CCValAssign::Indirect)
10357       return false;
10358 
10359   // Do not tail call opt if either caller or callee uses struct return
10360   // semantics.
10361   auto IsCallerStructRet = Caller.hasStructRetAttr();
10362   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10363   if (IsCallerStructRet || IsCalleeStructRet)
10364     return false;
10365 
10366   // Externally-defined functions with weak linkage should not be
10367   // tail-called. The behaviour of branch instructions in this situation (as
10368   // used for tail calls) is implementation-defined, so we cannot rely on the
10369   // linker replacing the tail call with a return.
10370   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10371     const GlobalValue *GV = G->getGlobal();
10372     if (GV->hasExternalWeakLinkage())
10373       return false;
10374   }
10375 
10376   // The callee has to preserve all registers the caller needs to preserve.
10377   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10378   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10379   if (CalleeCC != CallerCC) {
10380     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10381     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10382       return false;
10383   }
10384 
10385   // Byval parameters hand the function a pointer directly into the stack area
10386   // we want to reuse during a tail call. Working around this *is* possible
10387   // but less efficient and uglier in LowerCall.
10388   for (auto &Arg : Outs)
10389     if (Arg.Flags.isByVal())
10390       return false;
10391 
10392   return true;
10393 }
10394 
10395 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10396   return DAG.getDataLayout().getPrefTypeAlign(
10397       VT.getTypeForEVT(*DAG.getContext()));
10398 }
10399 
10400 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10401 // and output parameter nodes.
10402 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10403                                        SmallVectorImpl<SDValue> &InVals) const {
10404   SelectionDAG &DAG = CLI.DAG;
10405   SDLoc &DL = CLI.DL;
10406   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10407   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10408   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10409   SDValue Chain = CLI.Chain;
10410   SDValue Callee = CLI.Callee;
10411   bool &IsTailCall = CLI.IsTailCall;
10412   CallingConv::ID CallConv = CLI.CallConv;
10413   bool IsVarArg = CLI.IsVarArg;
10414   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10415   MVT XLenVT = Subtarget.getXLenVT();
10416 
10417   MachineFunction &MF = DAG.getMachineFunction();
10418 
10419   // Analyze the operands of the call, assigning locations to each operand.
10420   SmallVector<CCValAssign, 16> ArgLocs;
10421   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10422 
10423   if (CallConv == CallingConv::GHC)
10424     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10425   else
10426     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10427                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10428                                                     : CC_RISCV);
10429 
10430   // Check if it's really possible to do a tail call.
10431   if (IsTailCall)
10432     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10433 
10434   if (IsTailCall)
10435     ++NumTailCalls;
10436   else if (CLI.CB && CLI.CB->isMustTailCall())
10437     report_fatal_error("failed to perform tail call elimination on a call "
10438                        "site marked musttail");
10439 
10440   // Get a count of how many bytes are to be pushed on the stack.
10441   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10442 
10443   // Create local copies for byval args
10444   SmallVector<SDValue, 8> ByValArgs;
10445   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10446     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10447     if (!Flags.isByVal())
10448       continue;
10449 
10450     SDValue Arg = OutVals[i];
10451     unsigned Size = Flags.getByValSize();
10452     Align Alignment = Flags.getNonZeroByValAlign();
10453 
10454     int FI =
10455         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10456     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10457     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10458 
10459     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10460                           /*IsVolatile=*/false,
10461                           /*AlwaysInline=*/false, IsTailCall,
10462                           MachinePointerInfo(), MachinePointerInfo());
10463     ByValArgs.push_back(FIPtr);
10464   }
10465 
10466   if (!IsTailCall)
10467     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10468 
10469   // Copy argument values to their designated locations.
10470   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10471   SmallVector<SDValue, 8> MemOpChains;
10472   SDValue StackPtr;
10473   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10474     CCValAssign &VA = ArgLocs[i];
10475     SDValue ArgValue = OutVals[i];
10476     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10477 
10478     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10479     bool IsF64OnRV32DSoftABI =
10480         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10481     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10482       SDValue SplitF64 = DAG.getNode(
10483           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10484       SDValue Lo = SplitF64.getValue(0);
10485       SDValue Hi = SplitF64.getValue(1);
10486 
10487       Register RegLo = VA.getLocReg();
10488       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10489 
10490       if (RegLo == RISCV::X17) {
10491         // Second half of f64 is passed on the stack.
10492         // Work out the address of the stack slot.
10493         if (!StackPtr.getNode())
10494           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10495         // Emit the store.
10496         MemOpChains.push_back(
10497             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10498       } else {
10499         // Second half of f64 is passed in another GPR.
10500         assert(RegLo < RISCV::X31 && "Invalid register pair");
10501         Register RegHigh = RegLo + 1;
10502         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10503       }
10504       continue;
10505     }
10506 
10507     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10508     // as any other MemLoc.
10509 
10510     // Promote the value if needed.
10511     // For now, only handle fully promoted and indirect arguments.
10512     if (VA.getLocInfo() == CCValAssign::Indirect) {
10513       // Store the argument in a stack slot and pass its address.
10514       Align StackAlign =
10515           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10516                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10517       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10518       // If the original argument was split (e.g. i128), we need
10519       // to store the required parts of it here (and pass just one address).
10520       // Vectors may be partly split to registers and partly to the stack, in
10521       // which case the base address is partly offset and subsequent stores are
10522       // relative to that.
10523       unsigned ArgIndex = Outs[i].OrigArgIndex;
10524       unsigned ArgPartOffset = Outs[i].PartOffset;
10525       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10526       // Calculate the total size to store. We don't have access to what we're
10527       // actually storing other than performing the loop and collecting the
10528       // info.
10529       SmallVector<std::pair<SDValue, SDValue>> Parts;
10530       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10531         SDValue PartValue = OutVals[i + 1];
10532         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10533         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10534         EVT PartVT = PartValue.getValueType();
10535         if (PartVT.isScalableVector())
10536           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10537         StoredSize += PartVT.getStoreSize();
10538         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10539         Parts.push_back(std::make_pair(PartValue, Offset));
10540         ++i;
10541       }
10542       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10543       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10544       MemOpChains.push_back(
10545           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10546                        MachinePointerInfo::getFixedStack(MF, FI)));
10547       for (const auto &Part : Parts) {
10548         SDValue PartValue = Part.first;
10549         SDValue PartOffset = Part.second;
10550         SDValue Address =
10551             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10552         MemOpChains.push_back(
10553             DAG.getStore(Chain, DL, PartValue, Address,
10554                          MachinePointerInfo::getFixedStack(MF, FI)));
10555       }
10556       ArgValue = SpillSlot;
10557     } else {
10558       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10559     }
10560 
10561     // Use local copy if it is a byval arg.
10562     if (Flags.isByVal())
10563       ArgValue = ByValArgs[j++];
10564 
10565     if (VA.isRegLoc()) {
10566       // Queue up the argument copies and emit them at the end.
10567       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10568     } else {
10569       assert(VA.isMemLoc() && "Argument not register or memory");
10570       assert(!IsTailCall && "Tail call not allowed if stack is used "
10571                             "for passing parameters");
10572 
10573       // Work out the address of the stack slot.
10574       if (!StackPtr.getNode())
10575         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10576       SDValue Address =
10577           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10578                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10579 
10580       // Emit the store.
10581       MemOpChains.push_back(
10582           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10583     }
10584   }
10585 
10586   // Join the stores, which are independent of one another.
10587   if (!MemOpChains.empty())
10588     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10589 
10590   SDValue Glue;
10591 
10592   // Build a sequence of copy-to-reg nodes, chained and glued together.
10593   for (auto &Reg : RegsToPass) {
10594     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10595     Glue = Chain.getValue(1);
10596   }
10597 
10598   // Validate that none of the argument registers have been marked as
10599   // reserved, if so report an error. Do the same for the return address if this
10600   // is not a tailcall.
10601   validateCCReservedRegs(RegsToPass, MF);
10602   if (!IsTailCall &&
10603       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10604     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10605         MF.getFunction(),
10606         "Return address register required, but has been reserved."});
10607 
10608   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10609   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10610   // split it and then direct call can be matched by PseudoCALL.
10611   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10612     const GlobalValue *GV = S->getGlobal();
10613 
10614     unsigned OpFlags = RISCVII::MO_CALL;
10615     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10616       OpFlags = RISCVII::MO_PLT;
10617 
10618     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10619   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10620     unsigned OpFlags = RISCVII::MO_CALL;
10621 
10622     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10623                                                  nullptr))
10624       OpFlags = RISCVII::MO_PLT;
10625 
10626     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10627   }
10628 
10629   // The first call operand is the chain and the second is the target address.
10630   SmallVector<SDValue, 8> Ops;
10631   Ops.push_back(Chain);
10632   Ops.push_back(Callee);
10633 
10634   // Add argument registers to the end of the list so that they are
10635   // known live into the call.
10636   for (auto &Reg : RegsToPass)
10637     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10638 
10639   if (!IsTailCall) {
10640     // Add a register mask operand representing the call-preserved registers.
10641     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10642     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10643     assert(Mask && "Missing call preserved mask for calling convention");
10644     Ops.push_back(DAG.getRegisterMask(Mask));
10645   }
10646 
10647   // Glue the call to the argument copies, if any.
10648   if (Glue.getNode())
10649     Ops.push_back(Glue);
10650 
10651   // Emit the call.
10652   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10653 
10654   if (IsTailCall) {
10655     MF.getFrameInfo().setHasTailCall();
10656     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10657   }
10658 
10659   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10660   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10661   Glue = Chain.getValue(1);
10662 
10663   // Mark the end of the call, which is glued to the call itself.
10664   Chain = DAG.getCALLSEQ_END(Chain,
10665                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10666                              DAG.getConstant(0, DL, PtrVT, true),
10667                              Glue, DL);
10668   Glue = Chain.getValue(1);
10669 
10670   // Assign locations to each value returned by this call.
10671   SmallVector<CCValAssign, 16> RVLocs;
10672   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10673   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10674 
10675   // Copy all of the result registers out of their specified physreg.
10676   for (auto &VA : RVLocs) {
10677     // Copy the value out
10678     SDValue RetValue =
10679         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10680     // Glue the RetValue to the end of the call sequence
10681     Chain = RetValue.getValue(1);
10682     Glue = RetValue.getValue(2);
10683 
10684     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10685       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10686       SDValue RetValue2 =
10687           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10688       Chain = RetValue2.getValue(1);
10689       Glue = RetValue2.getValue(2);
10690       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10691                              RetValue2);
10692     }
10693 
10694     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10695 
10696     InVals.push_back(RetValue);
10697   }
10698 
10699   return Chain;
10700 }
10701 
10702 bool RISCVTargetLowering::CanLowerReturn(
10703     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10704     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10705   SmallVector<CCValAssign, 16> RVLocs;
10706   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10707 
10708   Optional<unsigned> FirstMaskArgument;
10709   if (Subtarget.hasVInstructions())
10710     FirstMaskArgument = preAssignMask(Outs);
10711 
10712   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10713     MVT VT = Outs[i].VT;
10714     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10715     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10716     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10717                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10718                  *this, FirstMaskArgument))
10719       return false;
10720   }
10721   return true;
10722 }
10723 
10724 SDValue
10725 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10726                                  bool IsVarArg,
10727                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10728                                  const SmallVectorImpl<SDValue> &OutVals,
10729                                  const SDLoc &DL, SelectionDAG &DAG) const {
10730   const MachineFunction &MF = DAG.getMachineFunction();
10731   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10732 
10733   // Stores the assignment of the return value to a location.
10734   SmallVector<CCValAssign, 16> RVLocs;
10735 
10736   // Info about the registers and stack slot.
10737   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10738                  *DAG.getContext());
10739 
10740   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10741                     nullptr, CC_RISCV);
10742 
10743   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10744     report_fatal_error("GHC functions return void only");
10745 
10746   SDValue Glue;
10747   SmallVector<SDValue, 4> RetOps(1, Chain);
10748 
10749   // Copy the result values into the output registers.
10750   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10751     SDValue Val = OutVals[i];
10752     CCValAssign &VA = RVLocs[i];
10753     assert(VA.isRegLoc() && "Can only return in registers!");
10754 
10755     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10756       // Handle returning f64 on RV32D with a soft float ABI.
10757       assert(VA.isRegLoc() && "Expected return via registers");
10758       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10759                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10760       SDValue Lo = SplitF64.getValue(0);
10761       SDValue Hi = SplitF64.getValue(1);
10762       Register RegLo = VA.getLocReg();
10763       assert(RegLo < RISCV::X31 && "Invalid register pair");
10764       Register RegHi = RegLo + 1;
10765 
10766       if (STI.isRegisterReservedByUser(RegLo) ||
10767           STI.isRegisterReservedByUser(RegHi))
10768         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10769             MF.getFunction(),
10770             "Return value register required, but has been reserved."});
10771 
10772       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10773       Glue = Chain.getValue(1);
10774       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10775       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10776       Glue = Chain.getValue(1);
10777       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10778     } else {
10779       // Handle a 'normal' return.
10780       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10781       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10782 
10783       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10784         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10785             MF.getFunction(),
10786             "Return value register required, but has been reserved."});
10787 
10788       // Guarantee that all emitted copies are stuck together.
10789       Glue = Chain.getValue(1);
10790       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10791     }
10792   }
10793 
10794   RetOps[0] = Chain; // Update chain.
10795 
10796   // Add the glue node if we have it.
10797   if (Glue.getNode()) {
10798     RetOps.push_back(Glue);
10799   }
10800 
10801   unsigned RetOpc = RISCVISD::RET_FLAG;
10802   // Interrupt service routines use different return instructions.
10803   const Function &Func = DAG.getMachineFunction().getFunction();
10804   if (Func.hasFnAttribute("interrupt")) {
10805     if (!Func.getReturnType()->isVoidTy())
10806       report_fatal_error(
10807           "Functions with the interrupt attribute must have void return type!");
10808 
10809     MachineFunction &MF = DAG.getMachineFunction();
10810     StringRef Kind =
10811       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10812 
10813     if (Kind == "user")
10814       RetOpc = RISCVISD::URET_FLAG;
10815     else if (Kind == "supervisor")
10816       RetOpc = RISCVISD::SRET_FLAG;
10817     else
10818       RetOpc = RISCVISD::MRET_FLAG;
10819   }
10820 
10821   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10822 }
10823 
10824 void RISCVTargetLowering::validateCCReservedRegs(
10825     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10826     MachineFunction &MF) const {
10827   const Function &F = MF.getFunction();
10828   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10829 
10830   if (llvm::any_of(Regs, [&STI](auto Reg) {
10831         return STI.isRegisterReservedByUser(Reg.first);
10832       }))
10833     F.getContext().diagnose(DiagnosticInfoUnsupported{
10834         F, "Argument register required, but has been reserved."});
10835 }
10836 
10837 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10838   return CI->isTailCall();
10839 }
10840 
10841 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10842 #define NODE_NAME_CASE(NODE)                                                   \
10843   case RISCVISD::NODE:                                                         \
10844     return "RISCVISD::" #NODE;
10845   // clang-format off
10846   switch ((RISCVISD::NodeType)Opcode) {
10847   case RISCVISD::FIRST_NUMBER:
10848     break;
10849   NODE_NAME_CASE(RET_FLAG)
10850   NODE_NAME_CASE(URET_FLAG)
10851   NODE_NAME_CASE(SRET_FLAG)
10852   NODE_NAME_CASE(MRET_FLAG)
10853   NODE_NAME_CASE(CALL)
10854   NODE_NAME_CASE(SELECT_CC)
10855   NODE_NAME_CASE(BR_CC)
10856   NODE_NAME_CASE(BuildPairF64)
10857   NODE_NAME_CASE(SplitF64)
10858   NODE_NAME_CASE(TAIL)
10859   NODE_NAME_CASE(MULHSU)
10860   NODE_NAME_CASE(SLLW)
10861   NODE_NAME_CASE(SRAW)
10862   NODE_NAME_CASE(SRLW)
10863   NODE_NAME_CASE(DIVW)
10864   NODE_NAME_CASE(DIVUW)
10865   NODE_NAME_CASE(REMUW)
10866   NODE_NAME_CASE(ROLW)
10867   NODE_NAME_CASE(RORW)
10868   NODE_NAME_CASE(CLZW)
10869   NODE_NAME_CASE(CTZW)
10870   NODE_NAME_CASE(FSLW)
10871   NODE_NAME_CASE(FSRW)
10872   NODE_NAME_CASE(FSL)
10873   NODE_NAME_CASE(FSR)
10874   NODE_NAME_CASE(FMV_H_X)
10875   NODE_NAME_CASE(FMV_X_ANYEXTH)
10876   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10877   NODE_NAME_CASE(FMV_W_X_RV64)
10878   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10879   NODE_NAME_CASE(FCVT_X)
10880   NODE_NAME_CASE(FCVT_XU)
10881   NODE_NAME_CASE(FCVT_W_RV64)
10882   NODE_NAME_CASE(FCVT_WU_RV64)
10883   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10884   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10885   NODE_NAME_CASE(READ_CYCLE_WIDE)
10886   NODE_NAME_CASE(GREV)
10887   NODE_NAME_CASE(GREVW)
10888   NODE_NAME_CASE(GORC)
10889   NODE_NAME_CASE(GORCW)
10890   NODE_NAME_CASE(SHFL)
10891   NODE_NAME_CASE(SHFLW)
10892   NODE_NAME_CASE(UNSHFL)
10893   NODE_NAME_CASE(UNSHFLW)
10894   NODE_NAME_CASE(BFP)
10895   NODE_NAME_CASE(BFPW)
10896   NODE_NAME_CASE(BCOMPRESS)
10897   NODE_NAME_CASE(BCOMPRESSW)
10898   NODE_NAME_CASE(BDECOMPRESS)
10899   NODE_NAME_CASE(BDECOMPRESSW)
10900   NODE_NAME_CASE(VMV_V_X_VL)
10901   NODE_NAME_CASE(VFMV_V_F_VL)
10902   NODE_NAME_CASE(VMV_X_S)
10903   NODE_NAME_CASE(VMV_S_X_VL)
10904   NODE_NAME_CASE(VFMV_S_F_VL)
10905   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10906   NODE_NAME_CASE(READ_VLENB)
10907   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10908   NODE_NAME_CASE(VSLIDEUP_VL)
10909   NODE_NAME_CASE(VSLIDE1UP_VL)
10910   NODE_NAME_CASE(VSLIDEDOWN_VL)
10911   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10912   NODE_NAME_CASE(VID_VL)
10913   NODE_NAME_CASE(VFNCVT_ROD_VL)
10914   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10915   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10916   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10917   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10918   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10919   NODE_NAME_CASE(VECREDUCE_AND_VL)
10920   NODE_NAME_CASE(VECREDUCE_OR_VL)
10921   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10922   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10923   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10924   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10925   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10926   NODE_NAME_CASE(ADD_VL)
10927   NODE_NAME_CASE(AND_VL)
10928   NODE_NAME_CASE(MUL_VL)
10929   NODE_NAME_CASE(OR_VL)
10930   NODE_NAME_CASE(SDIV_VL)
10931   NODE_NAME_CASE(SHL_VL)
10932   NODE_NAME_CASE(SREM_VL)
10933   NODE_NAME_CASE(SRA_VL)
10934   NODE_NAME_CASE(SRL_VL)
10935   NODE_NAME_CASE(SUB_VL)
10936   NODE_NAME_CASE(UDIV_VL)
10937   NODE_NAME_CASE(UREM_VL)
10938   NODE_NAME_CASE(XOR_VL)
10939   NODE_NAME_CASE(SADDSAT_VL)
10940   NODE_NAME_CASE(UADDSAT_VL)
10941   NODE_NAME_CASE(SSUBSAT_VL)
10942   NODE_NAME_CASE(USUBSAT_VL)
10943   NODE_NAME_CASE(FADD_VL)
10944   NODE_NAME_CASE(FSUB_VL)
10945   NODE_NAME_CASE(FMUL_VL)
10946   NODE_NAME_CASE(FDIV_VL)
10947   NODE_NAME_CASE(FNEG_VL)
10948   NODE_NAME_CASE(FABS_VL)
10949   NODE_NAME_CASE(FSQRT_VL)
10950   NODE_NAME_CASE(FMA_VL)
10951   NODE_NAME_CASE(FCOPYSIGN_VL)
10952   NODE_NAME_CASE(SMIN_VL)
10953   NODE_NAME_CASE(SMAX_VL)
10954   NODE_NAME_CASE(UMIN_VL)
10955   NODE_NAME_CASE(UMAX_VL)
10956   NODE_NAME_CASE(FMINNUM_VL)
10957   NODE_NAME_CASE(FMAXNUM_VL)
10958   NODE_NAME_CASE(MULHS_VL)
10959   NODE_NAME_CASE(MULHU_VL)
10960   NODE_NAME_CASE(FP_TO_SINT_VL)
10961   NODE_NAME_CASE(FP_TO_UINT_VL)
10962   NODE_NAME_CASE(SINT_TO_FP_VL)
10963   NODE_NAME_CASE(UINT_TO_FP_VL)
10964   NODE_NAME_CASE(FP_EXTEND_VL)
10965   NODE_NAME_CASE(FP_ROUND_VL)
10966   NODE_NAME_CASE(VWMUL_VL)
10967   NODE_NAME_CASE(VWMULU_VL)
10968   NODE_NAME_CASE(VWMULSU_VL)
10969   NODE_NAME_CASE(VWADD_VL)
10970   NODE_NAME_CASE(VWADDU_VL)
10971   NODE_NAME_CASE(VWSUB_VL)
10972   NODE_NAME_CASE(VWSUBU_VL)
10973   NODE_NAME_CASE(VWADD_W_VL)
10974   NODE_NAME_CASE(VWADDU_W_VL)
10975   NODE_NAME_CASE(VWSUB_W_VL)
10976   NODE_NAME_CASE(VWSUBU_W_VL)
10977   NODE_NAME_CASE(SETCC_VL)
10978   NODE_NAME_CASE(VSELECT_VL)
10979   NODE_NAME_CASE(VP_MERGE_VL)
10980   NODE_NAME_CASE(VMAND_VL)
10981   NODE_NAME_CASE(VMOR_VL)
10982   NODE_NAME_CASE(VMXOR_VL)
10983   NODE_NAME_CASE(VMCLR_VL)
10984   NODE_NAME_CASE(VMSET_VL)
10985   NODE_NAME_CASE(VRGATHER_VX_VL)
10986   NODE_NAME_CASE(VRGATHER_VV_VL)
10987   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10988   NODE_NAME_CASE(VSEXT_VL)
10989   NODE_NAME_CASE(VZEXT_VL)
10990   NODE_NAME_CASE(VCPOP_VL)
10991   NODE_NAME_CASE(READ_CSR)
10992   NODE_NAME_CASE(WRITE_CSR)
10993   NODE_NAME_CASE(SWAP_CSR)
10994   }
10995   // clang-format on
10996   return nullptr;
10997 #undef NODE_NAME_CASE
10998 }
10999 
11000 /// getConstraintType - Given a constraint letter, return the type of
11001 /// constraint it is for this target.
11002 RISCVTargetLowering::ConstraintType
11003 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11004   if (Constraint.size() == 1) {
11005     switch (Constraint[0]) {
11006     default:
11007       break;
11008     case 'f':
11009       return C_RegisterClass;
11010     case 'I':
11011     case 'J':
11012     case 'K':
11013       return C_Immediate;
11014     case 'A':
11015       return C_Memory;
11016     case 'S': // A symbolic address
11017       return C_Other;
11018     }
11019   } else {
11020     if (Constraint == "vr" || Constraint == "vm")
11021       return C_RegisterClass;
11022   }
11023   return TargetLowering::getConstraintType(Constraint);
11024 }
11025 
11026 std::pair<unsigned, const TargetRegisterClass *>
11027 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11028                                                   StringRef Constraint,
11029                                                   MVT VT) const {
11030   // First, see if this is a constraint that directly corresponds to a
11031   // RISCV register class.
11032   if (Constraint.size() == 1) {
11033     switch (Constraint[0]) {
11034     case 'r':
11035       // TODO: Support fixed vectors up to XLen for P extension?
11036       if (VT.isVector())
11037         break;
11038       return std::make_pair(0U, &RISCV::GPRRegClass);
11039     case 'f':
11040       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11041         return std::make_pair(0U, &RISCV::FPR16RegClass);
11042       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11043         return std::make_pair(0U, &RISCV::FPR32RegClass);
11044       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11045         return std::make_pair(0U, &RISCV::FPR64RegClass);
11046       break;
11047     default:
11048       break;
11049     }
11050   } else if (Constraint == "vr") {
11051     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11052                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11053       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11054         return std::make_pair(0U, RC);
11055     }
11056   } else if (Constraint == "vm") {
11057     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11058       return std::make_pair(0U, &RISCV::VMV0RegClass);
11059   }
11060 
11061   // Clang will correctly decode the usage of register name aliases into their
11062   // official names. However, other frontends like `rustc` do not. This allows
11063   // users of these frontends to use the ABI names for registers in LLVM-style
11064   // register constraints.
11065   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11066                                .Case("{zero}", RISCV::X0)
11067                                .Case("{ra}", RISCV::X1)
11068                                .Case("{sp}", RISCV::X2)
11069                                .Case("{gp}", RISCV::X3)
11070                                .Case("{tp}", RISCV::X4)
11071                                .Case("{t0}", RISCV::X5)
11072                                .Case("{t1}", RISCV::X6)
11073                                .Case("{t2}", RISCV::X7)
11074                                .Cases("{s0}", "{fp}", RISCV::X8)
11075                                .Case("{s1}", RISCV::X9)
11076                                .Case("{a0}", RISCV::X10)
11077                                .Case("{a1}", RISCV::X11)
11078                                .Case("{a2}", RISCV::X12)
11079                                .Case("{a3}", RISCV::X13)
11080                                .Case("{a4}", RISCV::X14)
11081                                .Case("{a5}", RISCV::X15)
11082                                .Case("{a6}", RISCV::X16)
11083                                .Case("{a7}", RISCV::X17)
11084                                .Case("{s2}", RISCV::X18)
11085                                .Case("{s3}", RISCV::X19)
11086                                .Case("{s4}", RISCV::X20)
11087                                .Case("{s5}", RISCV::X21)
11088                                .Case("{s6}", RISCV::X22)
11089                                .Case("{s7}", RISCV::X23)
11090                                .Case("{s8}", RISCV::X24)
11091                                .Case("{s9}", RISCV::X25)
11092                                .Case("{s10}", RISCV::X26)
11093                                .Case("{s11}", RISCV::X27)
11094                                .Case("{t3}", RISCV::X28)
11095                                .Case("{t4}", RISCV::X29)
11096                                .Case("{t5}", RISCV::X30)
11097                                .Case("{t6}", RISCV::X31)
11098                                .Default(RISCV::NoRegister);
11099   if (XRegFromAlias != RISCV::NoRegister)
11100     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11101 
11102   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11103   // TableGen record rather than the AsmName to choose registers for InlineAsm
11104   // constraints, plus we want to match those names to the widest floating point
11105   // register type available, manually select floating point registers here.
11106   //
11107   // The second case is the ABI name of the register, so that frontends can also
11108   // use the ABI names in register constraint lists.
11109   if (Subtarget.hasStdExtF()) {
11110     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11111                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11112                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11113                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11114                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11115                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11116                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11117                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11118                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11119                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11120                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11121                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11122                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11123                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11124                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11125                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11126                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11127                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11128                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11129                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11130                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11131                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11132                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11133                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11134                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11135                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11136                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11137                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11138                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11139                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11140                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11141                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11142                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11143                         .Default(RISCV::NoRegister);
11144     if (FReg != RISCV::NoRegister) {
11145       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11146       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11147         unsigned RegNo = FReg - RISCV::F0_F;
11148         unsigned DReg = RISCV::F0_D + RegNo;
11149         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11150       }
11151       if (VT == MVT::f32 || VT == MVT::Other)
11152         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11153       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11154         unsigned RegNo = FReg - RISCV::F0_F;
11155         unsigned HReg = RISCV::F0_H + RegNo;
11156         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11157       }
11158     }
11159   }
11160 
11161   if (Subtarget.hasVInstructions()) {
11162     Register VReg = StringSwitch<Register>(Constraint.lower())
11163                         .Case("{v0}", RISCV::V0)
11164                         .Case("{v1}", RISCV::V1)
11165                         .Case("{v2}", RISCV::V2)
11166                         .Case("{v3}", RISCV::V3)
11167                         .Case("{v4}", RISCV::V4)
11168                         .Case("{v5}", RISCV::V5)
11169                         .Case("{v6}", RISCV::V6)
11170                         .Case("{v7}", RISCV::V7)
11171                         .Case("{v8}", RISCV::V8)
11172                         .Case("{v9}", RISCV::V9)
11173                         .Case("{v10}", RISCV::V10)
11174                         .Case("{v11}", RISCV::V11)
11175                         .Case("{v12}", RISCV::V12)
11176                         .Case("{v13}", RISCV::V13)
11177                         .Case("{v14}", RISCV::V14)
11178                         .Case("{v15}", RISCV::V15)
11179                         .Case("{v16}", RISCV::V16)
11180                         .Case("{v17}", RISCV::V17)
11181                         .Case("{v18}", RISCV::V18)
11182                         .Case("{v19}", RISCV::V19)
11183                         .Case("{v20}", RISCV::V20)
11184                         .Case("{v21}", RISCV::V21)
11185                         .Case("{v22}", RISCV::V22)
11186                         .Case("{v23}", RISCV::V23)
11187                         .Case("{v24}", RISCV::V24)
11188                         .Case("{v25}", RISCV::V25)
11189                         .Case("{v26}", RISCV::V26)
11190                         .Case("{v27}", RISCV::V27)
11191                         .Case("{v28}", RISCV::V28)
11192                         .Case("{v29}", RISCV::V29)
11193                         .Case("{v30}", RISCV::V30)
11194                         .Case("{v31}", RISCV::V31)
11195                         .Default(RISCV::NoRegister);
11196     if (VReg != RISCV::NoRegister) {
11197       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11198         return std::make_pair(VReg, &RISCV::VMRegClass);
11199       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11200         return std::make_pair(VReg, &RISCV::VRRegClass);
11201       for (const auto *RC :
11202            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11203         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11204           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11205           return std::make_pair(VReg, RC);
11206         }
11207       }
11208     }
11209   }
11210 
11211   std::pair<Register, const TargetRegisterClass *> Res =
11212       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11213 
11214   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11215   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11216   // Subtarget into account.
11217   if (Res.second == &RISCV::GPRF16RegClass ||
11218       Res.second == &RISCV::GPRF32RegClass ||
11219       Res.second == &RISCV::GPRF64RegClass)
11220     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11221 
11222   return Res;
11223 }
11224 
11225 unsigned
11226 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11227   // Currently only support length 1 constraints.
11228   if (ConstraintCode.size() == 1) {
11229     switch (ConstraintCode[0]) {
11230     case 'A':
11231       return InlineAsm::Constraint_A;
11232     default:
11233       break;
11234     }
11235   }
11236 
11237   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11238 }
11239 
11240 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11241     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11242     SelectionDAG &DAG) const {
11243   // Currently only support length 1 constraints.
11244   if (Constraint.length() == 1) {
11245     switch (Constraint[0]) {
11246     case 'I':
11247       // Validate & create a 12-bit signed immediate operand.
11248       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11249         uint64_t CVal = C->getSExtValue();
11250         if (isInt<12>(CVal))
11251           Ops.push_back(
11252               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11253       }
11254       return;
11255     case 'J':
11256       // Validate & create an integer zero operand.
11257       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11258         if (C->getZExtValue() == 0)
11259           Ops.push_back(
11260               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11261       return;
11262     case 'K':
11263       // Validate & create a 5-bit unsigned immediate operand.
11264       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11265         uint64_t CVal = C->getZExtValue();
11266         if (isUInt<5>(CVal))
11267           Ops.push_back(
11268               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11269       }
11270       return;
11271     case 'S':
11272       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11273         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11274                                                  GA->getValueType(0)));
11275       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11276         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11277                                                 BA->getValueType(0)));
11278       }
11279       return;
11280     default:
11281       break;
11282     }
11283   }
11284   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11285 }
11286 
11287 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11288                                                    Instruction *Inst,
11289                                                    AtomicOrdering Ord) const {
11290   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11291     return Builder.CreateFence(Ord);
11292   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11293     return Builder.CreateFence(AtomicOrdering::Release);
11294   return nullptr;
11295 }
11296 
11297 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11298                                                     Instruction *Inst,
11299                                                     AtomicOrdering Ord) const {
11300   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11301     return Builder.CreateFence(AtomicOrdering::Acquire);
11302   return nullptr;
11303 }
11304 
11305 TargetLowering::AtomicExpansionKind
11306 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11307   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11308   // point operations can't be used in an lr/sc sequence without breaking the
11309   // forward-progress guarantee.
11310   if (AI->isFloatingPointOperation())
11311     return AtomicExpansionKind::CmpXChg;
11312 
11313   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11314   if (Size == 8 || Size == 16)
11315     return AtomicExpansionKind::MaskedIntrinsic;
11316   return AtomicExpansionKind::None;
11317 }
11318 
11319 static Intrinsic::ID
11320 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11321   if (XLen == 32) {
11322     switch (BinOp) {
11323     default:
11324       llvm_unreachable("Unexpected AtomicRMW BinOp");
11325     case AtomicRMWInst::Xchg:
11326       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11327     case AtomicRMWInst::Add:
11328       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11329     case AtomicRMWInst::Sub:
11330       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11331     case AtomicRMWInst::Nand:
11332       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11333     case AtomicRMWInst::Max:
11334       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11335     case AtomicRMWInst::Min:
11336       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11337     case AtomicRMWInst::UMax:
11338       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11339     case AtomicRMWInst::UMin:
11340       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11341     }
11342   }
11343 
11344   if (XLen == 64) {
11345     switch (BinOp) {
11346     default:
11347       llvm_unreachable("Unexpected AtomicRMW BinOp");
11348     case AtomicRMWInst::Xchg:
11349       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11350     case AtomicRMWInst::Add:
11351       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11352     case AtomicRMWInst::Sub:
11353       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11354     case AtomicRMWInst::Nand:
11355       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11356     case AtomicRMWInst::Max:
11357       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11358     case AtomicRMWInst::Min:
11359       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11360     case AtomicRMWInst::UMax:
11361       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11362     case AtomicRMWInst::UMin:
11363       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11364     }
11365   }
11366 
11367   llvm_unreachable("Unexpected XLen\n");
11368 }
11369 
11370 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11371     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11372     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11373   unsigned XLen = Subtarget.getXLen();
11374   Value *Ordering =
11375       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11376   Type *Tys[] = {AlignedAddr->getType()};
11377   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11378       AI->getModule(),
11379       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11380 
11381   if (XLen == 64) {
11382     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11383     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11384     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11385   }
11386 
11387   Value *Result;
11388 
11389   // Must pass the shift amount needed to sign extend the loaded value prior
11390   // to performing a signed comparison for min/max. ShiftAmt is the number of
11391   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11392   // is the number of bits to left+right shift the value in order to
11393   // sign-extend.
11394   if (AI->getOperation() == AtomicRMWInst::Min ||
11395       AI->getOperation() == AtomicRMWInst::Max) {
11396     const DataLayout &DL = AI->getModule()->getDataLayout();
11397     unsigned ValWidth =
11398         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11399     Value *SextShamt =
11400         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11401     Result = Builder.CreateCall(LrwOpScwLoop,
11402                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11403   } else {
11404     Result =
11405         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11406   }
11407 
11408   if (XLen == 64)
11409     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11410   return Result;
11411 }
11412 
11413 TargetLowering::AtomicExpansionKind
11414 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11415     AtomicCmpXchgInst *CI) const {
11416   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11417   if (Size == 8 || Size == 16)
11418     return AtomicExpansionKind::MaskedIntrinsic;
11419   return AtomicExpansionKind::None;
11420 }
11421 
11422 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11423     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11424     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11425   unsigned XLen = Subtarget.getXLen();
11426   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11427   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11428   if (XLen == 64) {
11429     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11430     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11431     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11432     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11433   }
11434   Type *Tys[] = {AlignedAddr->getType()};
11435   Function *MaskedCmpXchg =
11436       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11437   Value *Result = Builder.CreateCall(
11438       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11439   if (XLen == 64)
11440     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11441   return Result;
11442 }
11443 
11444 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11445   return false;
11446 }
11447 
11448 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11449                                                EVT VT) const {
11450   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11451     return false;
11452 
11453   switch (FPVT.getSimpleVT().SimpleTy) {
11454   case MVT::f16:
11455     return Subtarget.hasStdExtZfh();
11456   case MVT::f32:
11457     return Subtarget.hasStdExtF();
11458   case MVT::f64:
11459     return Subtarget.hasStdExtD();
11460   default:
11461     return false;
11462   }
11463 }
11464 
11465 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11466   // If we are using the small code model, we can reduce size of jump table
11467   // entry to 4 bytes.
11468   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11469       getTargetMachine().getCodeModel() == CodeModel::Small) {
11470     return MachineJumpTableInfo::EK_Custom32;
11471   }
11472   return TargetLowering::getJumpTableEncoding();
11473 }
11474 
11475 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11476     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11477     unsigned uid, MCContext &Ctx) const {
11478   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11479          getTargetMachine().getCodeModel() == CodeModel::Small);
11480   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11481 }
11482 
11483 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11484                                                      EVT VT) const {
11485   VT = VT.getScalarType();
11486 
11487   if (!VT.isSimple())
11488     return false;
11489 
11490   switch (VT.getSimpleVT().SimpleTy) {
11491   case MVT::f16:
11492     return Subtarget.hasStdExtZfh();
11493   case MVT::f32:
11494     return Subtarget.hasStdExtF();
11495   case MVT::f64:
11496     return Subtarget.hasStdExtD();
11497   default:
11498     break;
11499   }
11500 
11501   return false;
11502 }
11503 
11504 Register RISCVTargetLowering::getExceptionPointerRegister(
11505     const Constant *PersonalityFn) const {
11506   return RISCV::X10;
11507 }
11508 
11509 Register RISCVTargetLowering::getExceptionSelectorRegister(
11510     const Constant *PersonalityFn) const {
11511   return RISCV::X11;
11512 }
11513 
11514 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11515   // Return false to suppress the unnecessary extensions if the LibCall
11516   // arguments or return value is f32 type for LP64 ABI.
11517   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11518   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11519     return false;
11520 
11521   return true;
11522 }
11523 
11524 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11525   if (Subtarget.is64Bit() && Type == MVT::i32)
11526     return true;
11527 
11528   return IsSigned;
11529 }
11530 
11531 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11532                                                  SDValue C) const {
11533   // Check integral scalar types.
11534   if (VT.isScalarInteger()) {
11535     // Omit the optimization if the sub target has the M extension and the data
11536     // size exceeds XLen.
11537     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11538       return false;
11539     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11540       // Break the MUL to a SLLI and an ADD/SUB.
11541       const APInt &Imm = ConstNode->getAPIntValue();
11542       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11543           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11544         return true;
11545       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11546       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11547           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11548            (Imm - 8).isPowerOf2()))
11549         return true;
11550       // Omit the following optimization if the sub target has the M extension
11551       // and the data size >= XLen.
11552       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11553         return false;
11554       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11555       // a pair of LUI/ADDI.
11556       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11557         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11558         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11559             (1 - ImmS).isPowerOf2())
11560         return true;
11561       }
11562     }
11563   }
11564 
11565   return false;
11566 }
11567 
11568 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11569                                                       SDValue ConstNode) const {
11570   // Let the DAGCombiner decide for vectors.
11571   EVT VT = AddNode.getValueType();
11572   if (VT.isVector())
11573     return true;
11574 
11575   // Let the DAGCombiner decide for larger types.
11576   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11577     return true;
11578 
11579   // It is worse if c1 is simm12 while c1*c2 is not.
11580   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11581   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11582   const APInt &C1 = C1Node->getAPIntValue();
11583   const APInt &C2 = C2Node->getAPIntValue();
11584   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11585     return false;
11586 
11587   // Default to true and let the DAGCombiner decide.
11588   return true;
11589 }
11590 
11591 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11592     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11593     bool *Fast) const {
11594   if (!VT.isVector())
11595     return false;
11596 
11597   EVT ElemVT = VT.getVectorElementType();
11598   if (Alignment >= ElemVT.getStoreSize()) {
11599     if (Fast)
11600       *Fast = true;
11601     return true;
11602   }
11603 
11604   return false;
11605 }
11606 
11607 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11608     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11609     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11610   bool IsABIRegCopy = CC.hasValue();
11611   EVT ValueVT = Val.getValueType();
11612   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11613     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11614     // and cast to f32.
11615     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11616     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11617     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11618                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11619     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11620     Parts[0] = Val;
11621     return true;
11622   }
11623 
11624   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11625     LLVMContext &Context = *DAG.getContext();
11626     EVT ValueEltVT = ValueVT.getVectorElementType();
11627     EVT PartEltVT = PartVT.getVectorElementType();
11628     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11629     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11630     if (PartVTBitSize % ValueVTBitSize == 0) {
11631       assert(PartVTBitSize >= ValueVTBitSize);
11632       // If the element types are different, bitcast to the same element type of
11633       // PartVT first.
11634       // Give an example here, we want copy a <vscale x 1 x i8> value to
11635       // <vscale x 4 x i16>.
11636       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11637       // subvector, then we can bitcast to <vscale x 4 x i16>.
11638       if (ValueEltVT != PartEltVT) {
11639         if (PartVTBitSize > ValueVTBitSize) {
11640           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11641           assert(Count != 0 && "The number of element should not be zero.");
11642           EVT SameEltTypeVT =
11643               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11644           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11645                             DAG.getUNDEF(SameEltTypeVT), Val,
11646                             DAG.getVectorIdxConstant(0, DL));
11647         }
11648         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11649       } else {
11650         Val =
11651             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11652                         Val, DAG.getVectorIdxConstant(0, DL));
11653       }
11654       Parts[0] = Val;
11655       return true;
11656     }
11657   }
11658   return false;
11659 }
11660 
11661 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11662     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11663     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11664   bool IsABIRegCopy = CC.hasValue();
11665   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11666     SDValue Val = Parts[0];
11667 
11668     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11669     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11670     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11671     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11672     return Val;
11673   }
11674 
11675   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11676     LLVMContext &Context = *DAG.getContext();
11677     SDValue Val = Parts[0];
11678     EVT ValueEltVT = ValueVT.getVectorElementType();
11679     EVT PartEltVT = PartVT.getVectorElementType();
11680     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11681     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11682     if (PartVTBitSize % ValueVTBitSize == 0) {
11683       assert(PartVTBitSize >= ValueVTBitSize);
11684       EVT SameEltTypeVT = ValueVT;
11685       // If the element types are different, convert it to the same element type
11686       // of PartVT.
11687       // Give an example here, we want copy a <vscale x 1 x i8> value from
11688       // <vscale x 4 x i16>.
11689       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11690       // then we can extract <vscale x 1 x i8>.
11691       if (ValueEltVT != PartEltVT) {
11692         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11693         assert(Count != 0 && "The number of element should not be zero.");
11694         SameEltTypeVT =
11695             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11696         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11697       }
11698       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11699                         DAG.getVectorIdxConstant(0, DL));
11700       return Val;
11701     }
11702   }
11703   return SDValue();
11704 }
11705 
11706 SDValue
11707 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11708                                    SelectionDAG &DAG,
11709                                    SmallVectorImpl<SDNode *> &Created) const {
11710   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11711   if (isIntDivCheap(N->getValueType(0), Attr))
11712     return SDValue(N, 0); // Lower SDIV as SDIV
11713 
11714   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11715          "Unexpected divisor!");
11716 
11717   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11718   if (!Subtarget.hasStdExtZbt())
11719     return SDValue();
11720 
11721   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11722   // Besides, more critical path instructions will be generated when dividing
11723   // by 2. So we keep using the original DAGs for these cases.
11724   unsigned Lg2 = Divisor.countTrailingZeros();
11725   if (Lg2 == 1 || Lg2 >= 12)
11726     return SDValue();
11727 
11728   // fold (sdiv X, pow2)
11729   EVT VT = N->getValueType(0);
11730   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11731     return SDValue();
11732 
11733   SDLoc DL(N);
11734   SDValue N0 = N->getOperand(0);
11735   SDValue Zero = DAG.getConstant(0, DL, VT);
11736   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11737 
11738   // Add (N0 < 0) ? Pow2 - 1 : 0;
11739   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11740   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11741   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11742 
11743   Created.push_back(Cmp.getNode());
11744   Created.push_back(Add.getNode());
11745   Created.push_back(Sel.getNode());
11746 
11747   // Divide by pow2.
11748   SDValue SRA =
11749       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11750 
11751   // If we're dividing by a positive value, we're done.  Otherwise, we must
11752   // negate the result.
11753   if (Divisor.isNonNegative())
11754     return SRA;
11755 
11756   Created.push_back(SRA.getNode());
11757   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11758 }
11759 
11760 #define GET_REGISTER_MATCHER
11761 #include "RISCVGenAsmMatcher.inc"
11762 
11763 Register
11764 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11765                                        const MachineFunction &MF) const {
11766   Register Reg = MatchRegisterAltName(RegName);
11767   if (Reg == RISCV::NoRegister)
11768     Reg = MatchRegisterName(RegName);
11769   if (Reg == RISCV::NoRegister)
11770     report_fatal_error(
11771         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11772   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11773   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11774     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11775                              StringRef(RegName) + "\"."));
11776   return Reg;
11777 }
11778 
11779 namespace llvm {
11780 namespace RISCVVIntrinsicsTable {
11781 
11782 #define GET_RISCVVIntrinsicsTable_IMPL
11783 #include "RISCVGenSearchableTables.inc"
11784 
11785 } // namespace RISCVVIntrinsicsTable
11786 
11787 } // namespace llvm
11788