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::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
1038                        ISD::OR, ISD::XOR});
1039 
1040   if (Subtarget.hasStdExtZbp())
1041     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
1042   if (Subtarget.hasStdExtZbkb())
1043     setTargetDAGCombine(ISD::BITREVERSE);
1044   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1045     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1046   if (Subtarget.hasStdExtF())
1047     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1048                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
1049   if (Subtarget.hasVInstructions())
1050     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
1051                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
1052                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
1053 
1054   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1055   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1056 }
1057 
1058 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1059                                             LLVMContext &Context,
1060                                             EVT VT) const {
1061   if (!VT.isVector())
1062     return getPointerTy(DL);
1063   if (Subtarget.hasVInstructions() &&
1064       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1065     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1066   return VT.changeVectorElementTypeToInteger();
1067 }
1068 
1069 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1070   return Subtarget.getXLenVT();
1071 }
1072 
1073 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1074                                              const CallInst &I,
1075                                              MachineFunction &MF,
1076                                              unsigned Intrinsic) const {
1077   auto &DL = I.getModule()->getDataLayout();
1078   switch (Intrinsic) {
1079   default:
1080     return false;
1081   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1082   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1083   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1084   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1085   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1086   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1087   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1088   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1089   case Intrinsic::riscv_masked_cmpxchg_i32:
1090     Info.opc = ISD::INTRINSIC_W_CHAIN;
1091     Info.memVT = MVT::i32;
1092     Info.ptrVal = I.getArgOperand(0);
1093     Info.offset = 0;
1094     Info.align = Align(4);
1095     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1096                  MachineMemOperand::MOVolatile;
1097     return true;
1098   case Intrinsic::riscv_masked_strided_load:
1099     Info.opc = ISD::INTRINSIC_W_CHAIN;
1100     Info.ptrVal = I.getArgOperand(1);
1101     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1102     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1103     Info.size = MemoryLocation::UnknownSize;
1104     Info.flags |= MachineMemOperand::MOLoad;
1105     return true;
1106   case Intrinsic::riscv_masked_strided_store:
1107     Info.opc = ISD::INTRINSIC_VOID;
1108     Info.ptrVal = I.getArgOperand(1);
1109     Info.memVT =
1110         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1111     Info.align = Align(
1112         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1113         8);
1114     Info.size = MemoryLocation::UnknownSize;
1115     Info.flags |= MachineMemOperand::MOStore;
1116     return true;
1117   case Intrinsic::riscv_seg2_load:
1118   case Intrinsic::riscv_seg3_load:
1119   case Intrinsic::riscv_seg4_load:
1120   case Intrinsic::riscv_seg5_load:
1121   case Intrinsic::riscv_seg6_load:
1122   case Intrinsic::riscv_seg7_load:
1123   case Intrinsic::riscv_seg8_load:
1124     Info.opc = ISD::INTRINSIC_W_CHAIN;
1125     Info.ptrVal = I.getArgOperand(0);
1126     Info.memVT =
1127         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1128     Info.align =
1129         Align(DL.getTypeSizeInBits(
1130                   I.getType()->getStructElementType(0)->getScalarType()) /
1131               8);
1132     Info.size = MemoryLocation::UnknownSize;
1133     Info.flags |= MachineMemOperand::MOLoad;
1134     return true;
1135   }
1136 }
1137 
1138 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1139                                                 const AddrMode &AM, Type *Ty,
1140                                                 unsigned AS,
1141                                                 Instruction *I) const {
1142   // No global is ever allowed as a base.
1143   if (AM.BaseGV)
1144     return false;
1145 
1146   // Require a 12-bit signed offset.
1147   if (!isInt<12>(AM.BaseOffs))
1148     return false;
1149 
1150   switch (AM.Scale) {
1151   case 0: // "r+i" or just "i", depending on HasBaseReg.
1152     break;
1153   case 1:
1154     if (!AM.HasBaseReg) // allow "r+i".
1155       break;
1156     return false; // disallow "r+r" or "r+r+i".
1157   default:
1158     return false;
1159   }
1160 
1161   return true;
1162 }
1163 
1164 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1165   return isInt<12>(Imm);
1166 }
1167 
1168 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1169   return isInt<12>(Imm);
1170 }
1171 
1172 // On RV32, 64-bit integers are split into their high and low parts and held
1173 // in two different registers, so the trunc is free since the low register can
1174 // just be used.
1175 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1176   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1177     return false;
1178   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1179   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1180   return (SrcBits == 64 && DestBits == 32);
1181 }
1182 
1183 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1184   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1185       !SrcVT.isInteger() || !DstVT.isInteger())
1186     return false;
1187   unsigned SrcBits = SrcVT.getSizeInBits();
1188   unsigned DestBits = DstVT.getSizeInBits();
1189   return (SrcBits == 64 && DestBits == 32);
1190 }
1191 
1192 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1193   // Zexts are free if they can be combined with a load.
1194   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1195   // poorly with type legalization of compares preferring sext.
1196   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1197     EVT MemVT = LD->getMemoryVT();
1198     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1199         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1200          LD->getExtensionType() == ISD::ZEXTLOAD))
1201       return true;
1202   }
1203 
1204   return TargetLowering::isZExtFree(Val, VT2);
1205 }
1206 
1207 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1208   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1209 }
1210 
1211 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1212   return Subtarget.hasStdExtZbb();
1213 }
1214 
1215 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1216   return Subtarget.hasStdExtZbb();
1217 }
1218 
1219 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1220   EVT VT = Y.getValueType();
1221 
1222   // FIXME: Support vectors once we have tests.
1223   if (VT.isVector())
1224     return false;
1225 
1226   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1227           Subtarget.hasStdExtZbkb()) &&
1228          !isa<ConstantSDNode>(Y);
1229 }
1230 
1231 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1232   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1233   auto *C = dyn_cast<ConstantSDNode>(Y);
1234   return C && C->getAPIntValue().ule(10);
1235 }
1236 
1237 /// Check if sinking \p I's operands to I's basic block is profitable, because
1238 /// the operands can be folded into a target instruction, e.g.
1239 /// splats of scalars can fold into vector instructions.
1240 bool RISCVTargetLowering::shouldSinkOperands(
1241     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1242   using namespace llvm::PatternMatch;
1243 
1244   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1245     return false;
1246 
1247   auto IsSinker = [&](Instruction *I, int Operand) {
1248     switch (I->getOpcode()) {
1249     case Instruction::Add:
1250     case Instruction::Sub:
1251     case Instruction::Mul:
1252     case Instruction::And:
1253     case Instruction::Or:
1254     case Instruction::Xor:
1255     case Instruction::FAdd:
1256     case Instruction::FSub:
1257     case Instruction::FMul:
1258     case Instruction::FDiv:
1259     case Instruction::ICmp:
1260     case Instruction::FCmp:
1261       return true;
1262     case Instruction::Shl:
1263     case Instruction::LShr:
1264     case Instruction::AShr:
1265     case Instruction::UDiv:
1266     case Instruction::SDiv:
1267     case Instruction::URem:
1268     case Instruction::SRem:
1269       return Operand == 1;
1270     case Instruction::Call:
1271       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1272         switch (II->getIntrinsicID()) {
1273         case Intrinsic::fma:
1274         case Intrinsic::vp_fma:
1275           return Operand == 0 || Operand == 1;
1276         // FIXME: Our patterns can only match vx/vf instructions when the splat
1277         // it on the RHS, because TableGen doesn't recognize our VP operations
1278         // as commutative.
1279         case Intrinsic::vp_add:
1280         case Intrinsic::vp_mul:
1281         case Intrinsic::vp_and:
1282         case Intrinsic::vp_or:
1283         case Intrinsic::vp_xor:
1284         case Intrinsic::vp_fadd:
1285         case Intrinsic::vp_fmul:
1286         case Intrinsic::vp_shl:
1287         case Intrinsic::vp_lshr:
1288         case Intrinsic::vp_ashr:
1289         case Intrinsic::vp_udiv:
1290         case Intrinsic::vp_sdiv:
1291         case Intrinsic::vp_urem:
1292         case Intrinsic::vp_srem:
1293           return Operand == 1;
1294         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1295         // explicit patterns for both LHS and RHS (as 'vr' versions).
1296         case Intrinsic::vp_sub:
1297         case Intrinsic::vp_fsub:
1298         case Intrinsic::vp_fdiv:
1299           return Operand == 0 || Operand == 1;
1300         default:
1301           return false;
1302         }
1303       }
1304       return false;
1305     default:
1306       return false;
1307     }
1308   };
1309 
1310   for (auto OpIdx : enumerate(I->operands())) {
1311     if (!IsSinker(I, OpIdx.index()))
1312       continue;
1313 
1314     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1315     // Make sure we are not already sinking this operand
1316     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1317       continue;
1318 
1319     // We are looking for a splat that can be sunk.
1320     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1321                              m_Undef(), m_ZeroMask())))
1322       continue;
1323 
1324     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1325     // and vector registers
1326     for (Use &U : Op->uses()) {
1327       Instruction *Insn = cast<Instruction>(U.getUser());
1328       if (!IsSinker(Insn, U.getOperandNo()))
1329         return false;
1330     }
1331 
1332     Ops.push_back(&Op->getOperandUse(0));
1333     Ops.push_back(&OpIdx.value());
1334   }
1335   return true;
1336 }
1337 
1338 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1339                                        bool ForCodeSize) const {
1340   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1341   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1342     return false;
1343   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1344     return false;
1345   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1346     return false;
1347   return Imm.isZero();
1348 }
1349 
1350 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1351   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1352          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1353          (VT == MVT::f64 && Subtarget.hasStdExtD());
1354 }
1355 
1356 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1357                                                       CallingConv::ID CC,
1358                                                       EVT VT) const {
1359   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1360   // We might still end up using a GPR but that will be decided based on ABI.
1361   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1362   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1363     return MVT::f32;
1364 
1365   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1366 }
1367 
1368 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1369                                                            CallingConv::ID CC,
1370                                                            EVT VT) const {
1371   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1372   // We might still end up using a GPR but that will be decided based on ABI.
1373   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1374   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1375     return 1;
1376 
1377   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1378 }
1379 
1380 // Changes the condition code and swaps operands if necessary, so the SetCC
1381 // operation matches one of the comparisons supported directly by branches
1382 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1383 // with 1/-1.
1384 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1385                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1386   // Convert X > -1 to X >= 0.
1387   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1388     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1389     CC = ISD::SETGE;
1390     return;
1391   }
1392   // Convert X < 1 to 0 >= X.
1393   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1394     RHS = LHS;
1395     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1396     CC = ISD::SETGE;
1397     return;
1398   }
1399 
1400   switch (CC) {
1401   default:
1402     break;
1403   case ISD::SETGT:
1404   case ISD::SETLE:
1405   case ISD::SETUGT:
1406   case ISD::SETULE:
1407     CC = ISD::getSetCCSwappedOperands(CC);
1408     std::swap(LHS, RHS);
1409     break;
1410   }
1411 }
1412 
1413 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1414   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1415   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1416   if (VT.getVectorElementType() == MVT::i1)
1417     KnownSize *= 8;
1418 
1419   switch (KnownSize) {
1420   default:
1421     llvm_unreachable("Invalid LMUL.");
1422   case 8:
1423     return RISCVII::VLMUL::LMUL_F8;
1424   case 16:
1425     return RISCVII::VLMUL::LMUL_F4;
1426   case 32:
1427     return RISCVII::VLMUL::LMUL_F2;
1428   case 64:
1429     return RISCVII::VLMUL::LMUL_1;
1430   case 128:
1431     return RISCVII::VLMUL::LMUL_2;
1432   case 256:
1433     return RISCVII::VLMUL::LMUL_4;
1434   case 512:
1435     return RISCVII::VLMUL::LMUL_8;
1436   }
1437 }
1438 
1439 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1440   switch (LMul) {
1441   default:
1442     llvm_unreachable("Invalid LMUL.");
1443   case RISCVII::VLMUL::LMUL_F8:
1444   case RISCVII::VLMUL::LMUL_F4:
1445   case RISCVII::VLMUL::LMUL_F2:
1446   case RISCVII::VLMUL::LMUL_1:
1447     return RISCV::VRRegClassID;
1448   case RISCVII::VLMUL::LMUL_2:
1449     return RISCV::VRM2RegClassID;
1450   case RISCVII::VLMUL::LMUL_4:
1451     return RISCV::VRM4RegClassID;
1452   case RISCVII::VLMUL::LMUL_8:
1453     return RISCV::VRM8RegClassID;
1454   }
1455 }
1456 
1457 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1458   RISCVII::VLMUL LMUL = getLMUL(VT);
1459   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1460       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1461       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1462       LMUL == RISCVII::VLMUL::LMUL_1) {
1463     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1464                   "Unexpected subreg numbering");
1465     return RISCV::sub_vrm1_0 + Index;
1466   }
1467   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1468     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1469                   "Unexpected subreg numbering");
1470     return RISCV::sub_vrm2_0 + Index;
1471   }
1472   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1473     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1474                   "Unexpected subreg numbering");
1475     return RISCV::sub_vrm4_0 + Index;
1476   }
1477   llvm_unreachable("Invalid vector type.");
1478 }
1479 
1480 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1481   if (VT.getVectorElementType() == MVT::i1)
1482     return RISCV::VRRegClassID;
1483   return getRegClassIDForLMUL(getLMUL(VT));
1484 }
1485 
1486 // Attempt to decompose a subvector insert/extract between VecVT and
1487 // SubVecVT via subregister indices. Returns the subregister index that
1488 // can perform the subvector insert/extract with the given element index, as
1489 // well as the index corresponding to any leftover subvectors that must be
1490 // further inserted/extracted within the register class for SubVecVT.
1491 std::pair<unsigned, unsigned>
1492 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1493     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1494     const RISCVRegisterInfo *TRI) {
1495   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1496                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1497                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1498                 "Register classes not ordered");
1499   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1500   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1501   // Try to compose a subregister index that takes us from the incoming
1502   // LMUL>1 register class down to the outgoing one. At each step we half
1503   // the LMUL:
1504   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1505   // Note that this is not guaranteed to find a subregister index, such as
1506   // when we are extracting from one VR type to another.
1507   unsigned SubRegIdx = RISCV::NoSubRegister;
1508   for (const unsigned RCID :
1509        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1510     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1511       VecVT = VecVT.getHalfNumVectorElementsVT();
1512       bool IsHi =
1513           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1514       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1515                                             getSubregIndexByMVT(VecVT, IsHi));
1516       if (IsHi)
1517         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1518     }
1519   return {SubRegIdx, InsertExtractIdx};
1520 }
1521 
1522 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1523 // stores for those types.
1524 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1525   return !Subtarget.useRVVForFixedLengthVectors() ||
1526          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1527 }
1528 
1529 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1530   if (ScalarTy->isPointerTy())
1531     return true;
1532 
1533   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1534       ScalarTy->isIntegerTy(32))
1535     return true;
1536 
1537   if (ScalarTy->isIntegerTy(64))
1538     return Subtarget.hasVInstructionsI64();
1539 
1540   if (ScalarTy->isHalfTy())
1541     return Subtarget.hasVInstructionsF16();
1542   if (ScalarTy->isFloatTy())
1543     return Subtarget.hasVInstructionsF32();
1544   if (ScalarTy->isDoubleTy())
1545     return Subtarget.hasVInstructionsF64();
1546 
1547   return false;
1548 }
1549 
1550 static SDValue getVLOperand(SDValue Op) {
1551   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1552           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1553          "Unexpected opcode");
1554   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1555   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1556   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1557       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1558   if (!II)
1559     return SDValue();
1560   return Op.getOperand(II->VLOperand + 1 + HasChain);
1561 }
1562 
1563 static bool useRVVForFixedLengthVectorVT(MVT VT,
1564                                          const RISCVSubtarget &Subtarget) {
1565   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1566   if (!Subtarget.useRVVForFixedLengthVectors())
1567     return false;
1568 
1569   // We only support a set of vector types with a consistent maximum fixed size
1570   // across all supported vector element types to avoid legalization issues.
1571   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1572   // fixed-length vector type we support is 1024 bytes.
1573   if (VT.getFixedSizeInBits() > 1024 * 8)
1574     return false;
1575 
1576   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1577 
1578   MVT EltVT = VT.getVectorElementType();
1579 
1580   // Don't use RVV for vectors we cannot scalarize if required.
1581   switch (EltVT.SimpleTy) {
1582   // i1 is supported but has different rules.
1583   default:
1584     return false;
1585   case MVT::i1:
1586     // Masks can only use a single register.
1587     if (VT.getVectorNumElements() > MinVLen)
1588       return false;
1589     MinVLen /= 8;
1590     break;
1591   case MVT::i8:
1592   case MVT::i16:
1593   case MVT::i32:
1594     break;
1595   case MVT::i64:
1596     if (!Subtarget.hasVInstructionsI64())
1597       return false;
1598     break;
1599   case MVT::f16:
1600     if (!Subtarget.hasVInstructionsF16())
1601       return false;
1602     break;
1603   case MVT::f32:
1604     if (!Subtarget.hasVInstructionsF32())
1605       return false;
1606     break;
1607   case MVT::f64:
1608     if (!Subtarget.hasVInstructionsF64())
1609       return false;
1610     break;
1611   }
1612 
1613   // Reject elements larger than ELEN.
1614   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1615     return false;
1616 
1617   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1618   // Don't use RVV for types that don't fit.
1619   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1620     return false;
1621 
1622   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1623   // the base fixed length RVV support in place.
1624   if (!VT.isPow2VectorType())
1625     return false;
1626 
1627   return true;
1628 }
1629 
1630 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1631   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1632 }
1633 
1634 // Return the largest legal scalable vector type that matches VT's element type.
1635 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1636                                             const RISCVSubtarget &Subtarget) {
1637   // This may be called before legal types are setup.
1638   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1639           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1640          "Expected legal fixed length vector!");
1641 
1642   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1643   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1644 
1645   MVT EltVT = VT.getVectorElementType();
1646   switch (EltVT.SimpleTy) {
1647   default:
1648     llvm_unreachable("unexpected element type for RVV container");
1649   case MVT::i1:
1650   case MVT::i8:
1651   case MVT::i16:
1652   case MVT::i32:
1653   case MVT::i64:
1654   case MVT::f16:
1655   case MVT::f32:
1656   case MVT::f64: {
1657     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1658     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1659     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1660     unsigned NumElts =
1661         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1662     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1663     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1664     return MVT::getScalableVectorVT(EltVT, NumElts);
1665   }
1666   }
1667 }
1668 
1669 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1670                                             const RISCVSubtarget &Subtarget) {
1671   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1672                                           Subtarget);
1673 }
1674 
1675 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1676   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1677 }
1678 
1679 // Grow V to consume an entire RVV register.
1680 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1681                                        const RISCVSubtarget &Subtarget) {
1682   assert(VT.isScalableVector() &&
1683          "Expected to convert into a scalable vector!");
1684   assert(V.getValueType().isFixedLengthVector() &&
1685          "Expected a fixed length vector operand!");
1686   SDLoc DL(V);
1687   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1688   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1689 }
1690 
1691 // Shrink V so it's just big enough to maintain a VT's worth of data.
1692 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1693                                          const RISCVSubtarget &Subtarget) {
1694   assert(VT.isFixedLengthVector() &&
1695          "Expected to convert into a fixed length vector!");
1696   assert(V.getValueType().isScalableVector() &&
1697          "Expected a scalable vector operand!");
1698   SDLoc DL(V);
1699   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1700   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1701 }
1702 
1703 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1704 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1705 // the vector type that it is contained in.
1706 static std::pair<SDValue, SDValue>
1707 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1708                 const RISCVSubtarget &Subtarget) {
1709   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1710   MVT XLenVT = Subtarget.getXLenVT();
1711   SDValue VL = VecVT.isFixedLengthVector()
1712                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1713                    : DAG.getRegister(RISCV::X0, XLenVT);
1714   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1715   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1716   return {Mask, VL};
1717 }
1718 
1719 // As above but assuming the given type is a scalable vector type.
1720 static std::pair<SDValue, SDValue>
1721 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1722                         const RISCVSubtarget &Subtarget) {
1723   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1724   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1725 }
1726 
1727 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1728 // of either is (currently) supported. This can get us into an infinite loop
1729 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1730 // as a ..., etc.
1731 // Until either (or both) of these can reliably lower any node, reporting that
1732 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1733 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1734 // which is not desirable.
1735 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1736     EVT VT, unsigned DefinedValues) const {
1737   return false;
1738 }
1739 
1740 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1741                                   const RISCVSubtarget &Subtarget) {
1742   // RISCV FP-to-int conversions saturate to the destination register size, but
1743   // don't produce 0 for nan. We can use a conversion instruction and fix the
1744   // nan case with a compare and a select.
1745   SDValue Src = Op.getOperand(0);
1746 
1747   EVT DstVT = Op.getValueType();
1748   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1749 
1750   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1751   unsigned Opc;
1752   if (SatVT == DstVT)
1753     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1754   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1755     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1756   else
1757     return SDValue();
1758   // FIXME: Support other SatVTs by clamping before or after the conversion.
1759 
1760   SDLoc DL(Op);
1761   SDValue FpToInt = DAG.getNode(
1762       Opc, DL, DstVT, Src,
1763       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1764 
1765   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1766   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1767 }
1768 
1769 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1770 // and back. Taking care to avoid converting values that are nan or already
1771 // correct.
1772 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1773 // have FRM dependencies modeled yet.
1774 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1775   MVT VT = Op.getSimpleValueType();
1776   assert(VT.isVector() && "Unexpected type");
1777 
1778   SDLoc DL(Op);
1779 
1780   // Freeze the source since we are increasing the number of uses.
1781   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1782 
1783   // Truncate to integer and convert back to FP.
1784   MVT IntVT = VT.changeVectorElementTypeToInteger();
1785   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1786   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1787 
1788   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1789 
1790   if (Op.getOpcode() == ISD::FCEIL) {
1791     // If the truncated value is the greater than or equal to the original
1792     // value, we've computed the ceil. Otherwise, we went the wrong way and
1793     // need to increase by 1.
1794     // FIXME: This should use a masked operation. Handle here or in isel?
1795     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1796                                  DAG.getConstantFP(1.0, DL, VT));
1797     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1798     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1799   } else if (Op.getOpcode() == ISD::FFLOOR) {
1800     // If the truncated value is the less than or equal to the original value,
1801     // we've computed the floor. Otherwise, we went the wrong way and need to
1802     // decrease by 1.
1803     // FIXME: This should use a masked operation. Handle here or in isel?
1804     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1805                                  DAG.getConstantFP(1.0, DL, VT));
1806     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1807     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1808   }
1809 
1810   // Restore the original sign so that -0.0 is preserved.
1811   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1812 
1813   // Determine the largest integer that can be represented exactly. This and
1814   // values larger than it don't have any fractional bits so don't need to
1815   // be converted.
1816   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1817   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1818   APFloat MaxVal = APFloat(FltSem);
1819   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1820                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1821   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1822 
1823   // If abs(Src) was larger than MaxVal or nan, keep it.
1824   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1825   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1826   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1827 }
1828 
1829 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1830 // This mode isn't supported in vector hardware on RISCV. But as long as we
1831 // aren't compiling with trapping math, we can emulate this with
1832 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1833 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1834 // dependencies modeled yet.
1835 // FIXME: Use masked operations to avoid final merge.
1836 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1837   MVT VT = Op.getSimpleValueType();
1838   assert(VT.isVector() && "Unexpected type");
1839 
1840   SDLoc DL(Op);
1841 
1842   // Freeze the source since we are increasing the number of uses.
1843   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1844 
1845   // We do the conversion on the absolute value and fix the sign at the end.
1846   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1847 
1848   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1849   bool Ignored;
1850   APFloat Point5Pred = APFloat(0.5f);
1851   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1852   Point5Pred.next(/*nextDown*/ true);
1853 
1854   // Add the adjustment.
1855   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1856                                DAG.getConstantFP(Point5Pred, DL, VT));
1857 
1858   // Truncate to integer and convert back to fp.
1859   MVT IntVT = VT.changeVectorElementTypeToInteger();
1860   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1861   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1862 
1863   // Restore the original sign.
1864   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1865 
1866   // Determine the largest integer that can be represented exactly. This and
1867   // values larger than it don't have any fractional bits so don't need to
1868   // be converted.
1869   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1870   APFloat MaxVal = APFloat(FltSem);
1871   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1872                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1873   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1874 
1875   // If abs(Src) was larger than MaxVal or nan, keep it.
1876   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1877   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1878   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1879 }
1880 
1881 struct VIDSequence {
1882   int64_t StepNumerator;
1883   unsigned StepDenominator;
1884   int64_t Addend;
1885 };
1886 
1887 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1888 // to the (non-zero) step S and start value X. This can be then lowered as the
1889 // RVV sequence (VID * S) + X, for example.
1890 // The step S is represented as an integer numerator divided by a positive
1891 // denominator. Note that the implementation currently only identifies
1892 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1893 // cannot detect 2/3, for example.
1894 // Note that this method will also match potentially unappealing index
1895 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1896 // determine whether this is worth generating code for.
1897 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1898   unsigned NumElts = Op.getNumOperands();
1899   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1900   if (!Op.getValueType().isInteger())
1901     return None;
1902 
1903   Optional<unsigned> SeqStepDenom;
1904   Optional<int64_t> SeqStepNum, SeqAddend;
1905   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1906   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1907   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1908     // Assume undef elements match the sequence; we just have to be careful
1909     // when interpolating across them.
1910     if (Op.getOperand(Idx).isUndef())
1911       continue;
1912     // The BUILD_VECTOR must be all constants.
1913     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1914       return None;
1915 
1916     uint64_t Val = Op.getConstantOperandVal(Idx) &
1917                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1918 
1919     if (PrevElt) {
1920       // Calculate the step since the last non-undef element, and ensure
1921       // it's consistent across the entire sequence.
1922       unsigned IdxDiff = Idx - PrevElt->second;
1923       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1924 
1925       // A zero-value value difference means that we're somewhere in the middle
1926       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1927       // step change before evaluating the sequence.
1928       if (ValDiff != 0) {
1929         int64_t Remainder = ValDiff % IdxDiff;
1930         // Normalize the step if it's greater than 1.
1931         if (Remainder != ValDiff) {
1932           // The difference must cleanly divide the element span.
1933           if (Remainder != 0)
1934             return None;
1935           ValDiff /= IdxDiff;
1936           IdxDiff = 1;
1937         }
1938 
1939         if (!SeqStepNum)
1940           SeqStepNum = ValDiff;
1941         else if (ValDiff != SeqStepNum)
1942           return None;
1943 
1944         if (!SeqStepDenom)
1945           SeqStepDenom = IdxDiff;
1946         else if (IdxDiff != *SeqStepDenom)
1947           return None;
1948       }
1949     }
1950 
1951     // Record and/or check any addend.
1952     if (SeqStepNum && SeqStepDenom) {
1953       uint64_t ExpectedVal =
1954           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1955       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1956       if (!SeqAddend)
1957         SeqAddend = Addend;
1958       else if (SeqAddend != Addend)
1959         return None;
1960     }
1961 
1962     // Record this non-undef element for later.
1963     if (!PrevElt || PrevElt->first != Val)
1964       PrevElt = std::make_pair(Val, Idx);
1965   }
1966   // We need to have logged both a step and an addend for this to count as
1967   // a legal index sequence.
1968   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1969     return None;
1970 
1971   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1972 }
1973 
1974 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1975 // and lower it as a VRGATHER_VX_VL from the source vector.
1976 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1977                                   SelectionDAG &DAG,
1978                                   const RISCVSubtarget &Subtarget) {
1979   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1980     return SDValue();
1981   SDValue Vec = SplatVal.getOperand(0);
1982   // Only perform this optimization on vectors of the same size for simplicity.
1983   if (Vec.getValueType() != VT)
1984     return SDValue();
1985   SDValue Idx = SplatVal.getOperand(1);
1986   // The index must be a legal type.
1987   if (Idx.getValueType() != Subtarget.getXLenVT())
1988     return SDValue();
1989 
1990   MVT ContainerVT = VT;
1991   if (VT.isFixedLengthVector()) {
1992     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1993     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1994   }
1995 
1996   SDValue Mask, VL;
1997   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1998 
1999   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2000                                Idx, Mask, VL);
2001 
2002   if (!VT.isFixedLengthVector())
2003     return Gather;
2004 
2005   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2006 }
2007 
2008 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2009                                  const RISCVSubtarget &Subtarget) {
2010   MVT VT = Op.getSimpleValueType();
2011   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2012 
2013   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2014 
2015   SDLoc DL(Op);
2016   SDValue Mask, VL;
2017   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2018 
2019   MVT XLenVT = Subtarget.getXLenVT();
2020   unsigned NumElts = Op.getNumOperands();
2021 
2022   if (VT.getVectorElementType() == MVT::i1) {
2023     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2024       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2025       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2026     }
2027 
2028     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2029       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2030       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2031     }
2032 
2033     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2034     // scalar integer chunks whose bit-width depends on the number of mask
2035     // bits and XLEN.
2036     // First, determine the most appropriate scalar integer type to use. This
2037     // is at most XLenVT, but may be shrunk to a smaller vector element type
2038     // according to the size of the final vector - use i8 chunks rather than
2039     // XLenVT if we're producing a v8i1. This results in more consistent
2040     // codegen across RV32 and RV64.
2041     unsigned NumViaIntegerBits =
2042         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2043     NumViaIntegerBits = std::min(NumViaIntegerBits,
2044                                  Subtarget.getMaxELENForFixedLengthVectors());
2045     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2046       // If we have to use more than one INSERT_VECTOR_ELT then this
2047       // optimization is likely to increase code size; avoid peforming it in
2048       // such a case. We can use a load from a constant pool in this case.
2049       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2050         return SDValue();
2051       // Now we can create our integer vector type. Note that it may be larger
2052       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2053       MVT IntegerViaVecVT =
2054           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2055                            divideCeil(NumElts, NumViaIntegerBits));
2056 
2057       uint64_t Bits = 0;
2058       unsigned BitPos = 0, IntegerEltIdx = 0;
2059       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2060 
2061       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2062         // Once we accumulate enough bits to fill our scalar type, insert into
2063         // our vector and clear our accumulated data.
2064         if (I != 0 && I % NumViaIntegerBits == 0) {
2065           if (NumViaIntegerBits <= 32)
2066             Bits = SignExtend64(Bits, 32);
2067           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2068           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2069                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2070           Bits = 0;
2071           BitPos = 0;
2072           IntegerEltIdx++;
2073         }
2074         SDValue V = Op.getOperand(I);
2075         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2076         Bits |= ((uint64_t)BitValue << BitPos);
2077       }
2078 
2079       // Insert the (remaining) scalar value into position in our integer
2080       // vector type.
2081       if (NumViaIntegerBits <= 32)
2082         Bits = SignExtend64(Bits, 32);
2083       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2084       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2085                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2086 
2087       if (NumElts < NumViaIntegerBits) {
2088         // If we're producing a smaller vector than our minimum legal integer
2089         // type, bitcast to the equivalent (known-legal) mask type, and extract
2090         // our final mask.
2091         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2092         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2093         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2094                           DAG.getConstant(0, DL, XLenVT));
2095       } else {
2096         // Else we must have produced an integer type with the same size as the
2097         // mask type; bitcast for the final result.
2098         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2099         Vec = DAG.getBitcast(VT, Vec);
2100       }
2101 
2102       return Vec;
2103     }
2104 
2105     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2106     // vector type, we have a legal equivalently-sized i8 type, so we can use
2107     // that.
2108     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2109     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2110 
2111     SDValue WideVec;
2112     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2113       // For a splat, perform a scalar truncate before creating the wider
2114       // vector.
2115       assert(Splat.getValueType() == XLenVT &&
2116              "Unexpected type for i1 splat value");
2117       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2118                           DAG.getConstant(1, DL, XLenVT));
2119       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2120     } else {
2121       SmallVector<SDValue, 8> Ops(Op->op_values());
2122       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2123       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2124       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2125     }
2126 
2127     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2128   }
2129 
2130   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2131     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2132       return Gather;
2133     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2134                                         : RISCVISD::VMV_V_X_VL;
2135     Splat =
2136         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2137     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2138   }
2139 
2140   // Try and match index sequences, which we can lower to the vid instruction
2141   // with optional modifications. An all-undef vector is matched by
2142   // getSplatValue, above.
2143   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2144     int64_t StepNumerator = SimpleVID->StepNumerator;
2145     unsigned StepDenominator = SimpleVID->StepDenominator;
2146     int64_t Addend = SimpleVID->Addend;
2147 
2148     assert(StepNumerator != 0 && "Invalid step");
2149     bool Negate = false;
2150     int64_t SplatStepVal = StepNumerator;
2151     unsigned StepOpcode = ISD::MUL;
2152     if (StepNumerator != 1) {
2153       if (isPowerOf2_64(std::abs(StepNumerator))) {
2154         Negate = StepNumerator < 0;
2155         StepOpcode = ISD::SHL;
2156         SplatStepVal = Log2_64(std::abs(StepNumerator));
2157       }
2158     }
2159 
2160     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2161     // threshold since it's the immediate value many RVV instructions accept.
2162     // There is no vmul.vi instruction so ensure multiply constant can fit in
2163     // a single addi instruction.
2164     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2165          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2166         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2167       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2168       // Convert right out of the scalable type so we can use standard ISD
2169       // nodes for the rest of the computation. If we used scalable types with
2170       // these, we'd lose the fixed-length vector info and generate worse
2171       // vsetvli code.
2172       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2173       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2174           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2175         SDValue SplatStep = DAG.getSplatBuildVector(
2176             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2177         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2178       }
2179       if (StepDenominator != 1) {
2180         SDValue SplatStep = DAG.getSplatBuildVector(
2181             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2182         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2183       }
2184       if (Addend != 0 || Negate) {
2185         SDValue SplatAddend = DAG.getSplatBuildVector(
2186             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2187         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2188       }
2189       return VID;
2190     }
2191   }
2192 
2193   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2194   // when re-interpreted as a vector with a larger element type. For example,
2195   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2196   // could be instead splat as
2197   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2198   // TODO: This optimization could also work on non-constant splats, but it
2199   // would require bit-manipulation instructions to construct the splat value.
2200   SmallVector<SDValue> Sequence;
2201   unsigned EltBitSize = VT.getScalarSizeInBits();
2202   const auto *BV = cast<BuildVectorSDNode>(Op);
2203   if (VT.isInteger() && EltBitSize < 64 &&
2204       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2205       BV->getRepeatedSequence(Sequence) &&
2206       (Sequence.size() * EltBitSize) <= 64) {
2207     unsigned SeqLen = Sequence.size();
2208     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2209     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2210     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2211             ViaIntVT == MVT::i64) &&
2212            "Unexpected sequence type");
2213 
2214     unsigned EltIdx = 0;
2215     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2216     uint64_t SplatValue = 0;
2217     // Construct the amalgamated value which can be splatted as this larger
2218     // vector type.
2219     for (const auto &SeqV : Sequence) {
2220       if (!SeqV.isUndef())
2221         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2222                        << (EltIdx * EltBitSize));
2223       EltIdx++;
2224     }
2225 
2226     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2227     // achieve better constant materializion.
2228     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2229       SplatValue = SignExtend64(SplatValue, 32);
2230 
2231     // Since we can't introduce illegal i64 types at this stage, we can only
2232     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2233     // way we can use RVV instructions to splat.
2234     assert((ViaIntVT.bitsLE(XLenVT) ||
2235             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2236            "Unexpected bitcast sequence");
2237     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2238       SDValue ViaVL =
2239           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2240       MVT ViaContainerVT =
2241           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2242       SDValue Splat =
2243           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2244                       DAG.getUNDEF(ViaContainerVT),
2245                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2246       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2247       return DAG.getBitcast(VT, Splat);
2248     }
2249   }
2250 
2251   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2252   // which constitute a large proportion of the elements. In such cases we can
2253   // splat a vector with the dominant element and make up the shortfall with
2254   // INSERT_VECTOR_ELTs.
2255   // Note that this includes vectors of 2 elements by association. The
2256   // upper-most element is the "dominant" one, allowing us to use a splat to
2257   // "insert" the upper element, and an insert of the lower element at position
2258   // 0, which improves codegen.
2259   SDValue DominantValue;
2260   unsigned MostCommonCount = 0;
2261   DenseMap<SDValue, unsigned> ValueCounts;
2262   unsigned NumUndefElts =
2263       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2264 
2265   // Track the number of scalar loads we know we'd be inserting, estimated as
2266   // any non-zero floating-point constant. Other kinds of element are either
2267   // already in registers or are materialized on demand. The threshold at which
2268   // a vector load is more desirable than several scalar materializion and
2269   // vector-insertion instructions is not known.
2270   unsigned NumScalarLoads = 0;
2271 
2272   for (SDValue V : Op->op_values()) {
2273     if (V.isUndef())
2274       continue;
2275 
2276     ValueCounts.insert(std::make_pair(V, 0));
2277     unsigned &Count = ValueCounts[V];
2278 
2279     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2280       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2281 
2282     // Is this value dominant? In case of a tie, prefer the highest element as
2283     // it's cheaper to insert near the beginning of a vector than it is at the
2284     // end.
2285     if (++Count >= MostCommonCount) {
2286       DominantValue = V;
2287       MostCommonCount = Count;
2288     }
2289   }
2290 
2291   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2292   unsigned NumDefElts = NumElts - NumUndefElts;
2293   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2294 
2295   // Don't perform this optimization when optimizing for size, since
2296   // materializing elements and inserting them tends to cause code bloat.
2297   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2298       ((MostCommonCount > DominantValueCountThreshold) ||
2299        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2300     // Start by splatting the most common element.
2301     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2302 
2303     DenseSet<SDValue> Processed{DominantValue};
2304     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2305     for (const auto &OpIdx : enumerate(Op->ops())) {
2306       const SDValue &V = OpIdx.value();
2307       if (V.isUndef() || !Processed.insert(V).second)
2308         continue;
2309       if (ValueCounts[V] == 1) {
2310         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2311                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2312       } else {
2313         // Blend in all instances of this value using a VSELECT, using a
2314         // mask where each bit signals whether that element is the one
2315         // we're after.
2316         SmallVector<SDValue> Ops;
2317         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2318           return DAG.getConstant(V == V1, DL, XLenVT);
2319         });
2320         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2321                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2322                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2323       }
2324     }
2325 
2326     return Vec;
2327   }
2328 
2329   return SDValue();
2330 }
2331 
2332 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2333                                    SDValue Lo, SDValue Hi, SDValue VL,
2334                                    SelectionDAG &DAG) {
2335   if (!Passthru)
2336     Passthru = DAG.getUNDEF(VT);
2337   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2338     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2339     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2340     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2341     // node in order to try and match RVV vector/scalar instructions.
2342     if ((LoC >> 31) == HiC)
2343       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2344 
2345     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2346     // vmv.v.x whose EEW = 32 to lower it.
2347     auto *Const = dyn_cast<ConstantSDNode>(VL);
2348     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2349       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2350       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2351       // access the subtarget here now.
2352       auto InterVec = DAG.getNode(
2353           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2354                                   DAG.getRegister(RISCV::X0, MVT::i32));
2355       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2356     }
2357   }
2358 
2359   // Fall back to a stack store and stride x0 vector load.
2360   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2361                      Hi, VL);
2362 }
2363 
2364 // Called by type legalization to handle splat of i64 on RV32.
2365 // FIXME: We can optimize this when the type has sign or zero bits in one
2366 // of the halves.
2367 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2368                                    SDValue Scalar, SDValue VL,
2369                                    SelectionDAG &DAG) {
2370   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2371   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2372                            DAG.getConstant(0, DL, MVT::i32));
2373   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2374                            DAG.getConstant(1, DL, MVT::i32));
2375   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2376 }
2377 
2378 // This function lowers a splat of a scalar operand Splat with the vector
2379 // length VL. It ensures the final sequence is type legal, which is useful when
2380 // lowering a splat after type legalization.
2381 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2382                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2383                                 const RISCVSubtarget &Subtarget) {
2384   bool HasPassthru = Passthru && !Passthru.isUndef();
2385   if (!HasPassthru && !Passthru)
2386     Passthru = DAG.getUNDEF(VT);
2387   if (VT.isFloatingPoint()) {
2388     // If VL is 1, we could use vfmv.s.f.
2389     if (isOneConstant(VL))
2390       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2391     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2392   }
2393 
2394   MVT XLenVT = Subtarget.getXLenVT();
2395 
2396   // Simplest case is that the operand needs to be promoted to XLenVT.
2397   if (Scalar.getValueType().bitsLE(XLenVT)) {
2398     // If the operand is a constant, sign extend to increase our chances
2399     // of being able to use a .vi instruction. ANY_EXTEND would become a
2400     // a zero extend and the simm5 check in isel would fail.
2401     // FIXME: Should we ignore the upper bits in isel instead?
2402     unsigned ExtOpc =
2403         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2404     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2405     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2406     // If VL is 1 and the scalar value won't benefit from immediate, we could
2407     // use vmv.s.x.
2408     if (isOneConstant(VL) &&
2409         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2410       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2411     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2412   }
2413 
2414   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2415          "Unexpected scalar for splat lowering!");
2416 
2417   if (isOneConstant(VL) && isNullConstant(Scalar))
2418     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2419                        DAG.getConstant(0, DL, XLenVT), VL);
2420 
2421   // Otherwise use the more complicated splatting algorithm.
2422   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2423 }
2424 
2425 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2426                                 const RISCVSubtarget &Subtarget) {
2427   // We need to be able to widen elements to the next larger integer type.
2428   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2429     return false;
2430 
2431   int Size = Mask.size();
2432   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2433 
2434   int Srcs[] = {-1, -1};
2435   for (int i = 0; i != Size; ++i) {
2436     // Ignore undef elements.
2437     if (Mask[i] < 0)
2438       continue;
2439 
2440     // Is this an even or odd element.
2441     int Pol = i % 2;
2442 
2443     // Ensure we consistently use the same source for this element polarity.
2444     int Src = Mask[i] / Size;
2445     if (Srcs[Pol] < 0)
2446       Srcs[Pol] = Src;
2447     if (Srcs[Pol] != Src)
2448       return false;
2449 
2450     // Make sure the element within the source is appropriate for this element
2451     // in the destination.
2452     int Elt = Mask[i] % Size;
2453     if (Elt != i / 2)
2454       return false;
2455   }
2456 
2457   // We need to find a source for each polarity and they can't be the same.
2458   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2459     return false;
2460 
2461   // Swap the sources if the second source was in the even polarity.
2462   SwapSources = Srcs[0] > Srcs[1];
2463 
2464   return true;
2465 }
2466 
2467 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2468 /// and then extract the original number of elements from the rotated result.
2469 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2470 /// returned rotation amount is for a rotate right, where elements move from
2471 /// higher elements to lower elements. \p LoSrc indicates the first source
2472 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2473 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2474 /// 0 or 1 if a rotation is found.
2475 ///
2476 /// NOTE: We talk about rotate to the right which matches how bit shift and
2477 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2478 /// and the table below write vectors with the lowest elements on the left.
2479 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2480   int Size = Mask.size();
2481 
2482   // We need to detect various ways of spelling a rotation:
2483   //   [11, 12, 13, 14, 15,  0,  1,  2]
2484   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2485   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2486   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2487   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2488   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2489   int Rotation = 0;
2490   LoSrc = -1;
2491   HiSrc = -1;
2492   for (int i = 0; i != Size; ++i) {
2493     int M = Mask[i];
2494     if (M < 0)
2495       continue;
2496 
2497     // Determine where a rotate vector would have started.
2498     int StartIdx = i - (M % Size);
2499     // The identity rotation isn't interesting, stop.
2500     if (StartIdx == 0)
2501       return -1;
2502 
2503     // If we found the tail of a vector the rotation must be the missing
2504     // front. If we found the head of a vector, it must be how much of the
2505     // head.
2506     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2507 
2508     if (Rotation == 0)
2509       Rotation = CandidateRotation;
2510     else if (Rotation != CandidateRotation)
2511       // The rotations don't match, so we can't match this mask.
2512       return -1;
2513 
2514     // Compute which value this mask is pointing at.
2515     int MaskSrc = M < Size ? 0 : 1;
2516 
2517     // Compute which of the two target values this index should be assigned to.
2518     // This reflects whether the high elements are remaining or the low elemnts
2519     // are remaining.
2520     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2521 
2522     // Either set up this value if we've not encountered it before, or check
2523     // that it remains consistent.
2524     if (TargetSrc < 0)
2525       TargetSrc = MaskSrc;
2526     else if (TargetSrc != MaskSrc)
2527       // This may be a rotation, but it pulls from the inputs in some
2528       // unsupported interleaving.
2529       return -1;
2530   }
2531 
2532   // Check that we successfully analyzed the mask, and normalize the results.
2533   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2534   assert((LoSrc >= 0 || HiSrc >= 0) &&
2535          "Failed to find a rotated input vector!");
2536 
2537   return Rotation;
2538 }
2539 
2540 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2541                                    const RISCVSubtarget &Subtarget) {
2542   SDValue V1 = Op.getOperand(0);
2543   SDValue V2 = Op.getOperand(1);
2544   SDLoc DL(Op);
2545   MVT XLenVT = Subtarget.getXLenVT();
2546   MVT VT = Op.getSimpleValueType();
2547   unsigned NumElts = VT.getVectorNumElements();
2548   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2549 
2550   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2551 
2552   SDValue TrueMask, VL;
2553   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2554 
2555   if (SVN->isSplat()) {
2556     const int Lane = SVN->getSplatIndex();
2557     if (Lane >= 0) {
2558       MVT SVT = VT.getVectorElementType();
2559 
2560       // Turn splatted vector load into a strided load with an X0 stride.
2561       SDValue V = V1;
2562       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2563       // with undef.
2564       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2565       int Offset = Lane;
2566       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2567         int OpElements =
2568             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2569         V = V.getOperand(Offset / OpElements);
2570         Offset %= OpElements;
2571       }
2572 
2573       // We need to ensure the load isn't atomic or volatile.
2574       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2575         auto *Ld = cast<LoadSDNode>(V);
2576         Offset *= SVT.getStoreSize();
2577         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2578                                                    TypeSize::Fixed(Offset), DL);
2579 
2580         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2581         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2582           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2583           SDValue IntID =
2584               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2585           SDValue Ops[] = {Ld->getChain(),
2586                            IntID,
2587                            DAG.getUNDEF(ContainerVT),
2588                            NewAddr,
2589                            DAG.getRegister(RISCV::X0, XLenVT),
2590                            VL};
2591           SDValue NewLoad = DAG.getMemIntrinsicNode(
2592               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2593               DAG.getMachineFunction().getMachineMemOperand(
2594                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2595           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2596           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2597         }
2598 
2599         // Otherwise use a scalar load and splat. This will give the best
2600         // opportunity to fold a splat into the operation. ISel can turn it into
2601         // the x0 strided load if we aren't able to fold away the select.
2602         if (SVT.isFloatingPoint())
2603           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2604                           Ld->getPointerInfo().getWithOffset(Offset),
2605                           Ld->getOriginalAlign(),
2606                           Ld->getMemOperand()->getFlags());
2607         else
2608           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2609                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2610                              Ld->getOriginalAlign(),
2611                              Ld->getMemOperand()->getFlags());
2612         DAG.makeEquivalentMemoryOrdering(Ld, V);
2613 
2614         unsigned Opc =
2615             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2616         SDValue Splat =
2617             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2618         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2619       }
2620 
2621       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2622       assert(Lane < (int)NumElts && "Unexpected lane!");
2623       SDValue Gather =
2624           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2625                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2626       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2627     }
2628   }
2629 
2630   ArrayRef<int> Mask = SVN->getMask();
2631 
2632   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2633   // be undef which can be handled with a single SLIDEDOWN/UP.
2634   int LoSrc, HiSrc;
2635   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2636   if (Rotation > 0) {
2637     SDValue LoV, HiV;
2638     if (LoSrc >= 0) {
2639       LoV = LoSrc == 0 ? V1 : V2;
2640       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2641     }
2642     if (HiSrc >= 0) {
2643       HiV = HiSrc == 0 ? V1 : V2;
2644       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2645     }
2646 
2647     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2648     // to slide LoV up by (NumElts - Rotation).
2649     unsigned InvRotate = NumElts - Rotation;
2650 
2651     SDValue Res = DAG.getUNDEF(ContainerVT);
2652     if (HiV) {
2653       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2654       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2655       // causes multiple vsetvlis in some test cases such as lowering
2656       // reduce.mul
2657       SDValue DownVL = VL;
2658       if (LoV)
2659         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2660       Res =
2661           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2662                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2663     }
2664     if (LoV)
2665       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2666                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2667 
2668     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2669   }
2670 
2671   // Detect an interleave shuffle and lower to
2672   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2673   bool SwapSources;
2674   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2675     // Swap sources if needed.
2676     if (SwapSources)
2677       std::swap(V1, V2);
2678 
2679     // Extract the lower half of the vectors.
2680     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2681     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2682                      DAG.getConstant(0, DL, XLenVT));
2683     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2684                      DAG.getConstant(0, DL, XLenVT));
2685 
2686     // Double the element width and halve the number of elements in an int type.
2687     unsigned EltBits = VT.getScalarSizeInBits();
2688     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2689     MVT WideIntVT =
2690         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2691     // Convert this to a scalable vector. We need to base this on the
2692     // destination size to ensure there's always a type with a smaller LMUL.
2693     MVT WideIntContainerVT =
2694         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2695 
2696     // Convert sources to scalable vectors with the same element count as the
2697     // larger type.
2698     MVT HalfContainerVT = MVT::getVectorVT(
2699         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2700     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2701     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2702 
2703     // Cast sources to integer.
2704     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2705     MVT IntHalfVT =
2706         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2707     V1 = DAG.getBitcast(IntHalfVT, V1);
2708     V2 = DAG.getBitcast(IntHalfVT, V2);
2709 
2710     // Freeze V2 since we use it twice and we need to be sure that the add and
2711     // multiply see the same value.
2712     V2 = DAG.getFreeze(V2);
2713 
2714     // Recreate TrueMask using the widened type's element count.
2715     MVT MaskVT =
2716         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2717     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2718 
2719     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2720     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2721                               V2, TrueMask, VL);
2722     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2723     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2724                                      DAG.getUNDEF(IntHalfVT),
2725                                      DAG.getAllOnesConstant(DL, XLenVT));
2726     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2727                                    V2, Multiplier, TrueMask, VL);
2728     // Add the new copies to our previous addition giving us 2^eltbits copies of
2729     // V2. This is equivalent to shifting V2 left by eltbits. This should
2730     // combine with the vwmulu.vv above to form vwmaccu.vv.
2731     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2732                       TrueMask, VL);
2733     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2734     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2735     // vector VT.
2736     ContainerVT =
2737         MVT::getVectorVT(VT.getVectorElementType(),
2738                          WideIntContainerVT.getVectorElementCount() * 2);
2739     Add = DAG.getBitcast(ContainerVT, Add);
2740     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2741   }
2742 
2743   // Detect shuffles which can be re-expressed as vector selects; these are
2744   // shuffles in which each element in the destination is taken from an element
2745   // at the corresponding index in either source vectors.
2746   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2747     int MaskIndex = MaskIdx.value();
2748     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2749   });
2750 
2751   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2752 
2753   SmallVector<SDValue> MaskVals;
2754   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2755   // merged with a second vrgather.
2756   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2757 
2758   // By default we preserve the original operand order, and use a mask to
2759   // select LHS as true and RHS as false. However, since RVV vector selects may
2760   // feature splats but only on the LHS, we may choose to invert our mask and
2761   // instead select between RHS and LHS.
2762   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2763   bool InvertMask = IsSelect == SwapOps;
2764 
2765   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2766   // half.
2767   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2768 
2769   // Now construct the mask that will be used by the vselect or blended
2770   // vrgather operation. For vrgathers, construct the appropriate indices into
2771   // each vector.
2772   for (int MaskIndex : Mask) {
2773     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2774     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2775     if (!IsSelect) {
2776       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2777       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2778                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2779                                      : DAG.getUNDEF(XLenVT));
2780       GatherIndicesRHS.push_back(
2781           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2782                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2783       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2784         ++LHSIndexCounts[MaskIndex];
2785       if (!IsLHSOrUndefIndex)
2786         ++RHSIndexCounts[MaskIndex - NumElts];
2787     }
2788   }
2789 
2790   if (SwapOps) {
2791     std::swap(V1, V2);
2792     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2793   }
2794 
2795   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2796   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2797   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2798 
2799   if (IsSelect)
2800     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2801 
2802   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2803     // On such a large vector we're unable to use i8 as the index type.
2804     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2805     // may involve vector splitting if we're already at LMUL=8, or our
2806     // user-supplied maximum fixed-length LMUL.
2807     return SDValue();
2808   }
2809 
2810   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2811   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2812   MVT IndexVT = VT.changeTypeToInteger();
2813   // Since we can't introduce illegal index types at this stage, use i16 and
2814   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2815   // than XLenVT.
2816   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2817     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2818     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2819   }
2820 
2821   MVT IndexContainerVT =
2822       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2823 
2824   SDValue Gather;
2825   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2826   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2827   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2828     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2829                               Subtarget);
2830   } else {
2831     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2832     // If only one index is used, we can use a "splat" vrgather.
2833     // TODO: We can splat the most-common index and fix-up any stragglers, if
2834     // that's beneficial.
2835     if (LHSIndexCounts.size() == 1) {
2836       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2837       Gather =
2838           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2839                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2840     } else {
2841       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2842       LHSIndices =
2843           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2844 
2845       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2846                            TrueMask, VL);
2847     }
2848   }
2849 
2850   // If a second vector operand is used by this shuffle, blend it in with an
2851   // additional vrgather.
2852   if (!V2.isUndef()) {
2853     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2854     // If only one index is used, we can use a "splat" vrgather.
2855     // TODO: We can splat the most-common index and fix-up any stragglers, if
2856     // that's beneficial.
2857     if (RHSIndexCounts.size() == 1) {
2858       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2859       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2860                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2861     } else {
2862       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2863       RHSIndices =
2864           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2865       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2866                        VL);
2867     }
2868 
2869     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2870     SelectMask =
2871         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2872 
2873     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2874                          Gather, VL);
2875   }
2876 
2877   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2878 }
2879 
2880 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2881   // Support splats for any type. These should type legalize well.
2882   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2883     return true;
2884 
2885   // Only support legal VTs for other shuffles for now.
2886   if (!isTypeLegal(VT))
2887     return false;
2888 
2889   MVT SVT = VT.getSimpleVT();
2890 
2891   bool SwapSources;
2892   int LoSrc, HiSrc;
2893   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2894          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2895 }
2896 
2897 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2898                                      SDLoc DL, SelectionDAG &DAG,
2899                                      const RISCVSubtarget &Subtarget) {
2900   if (VT.isScalableVector())
2901     return DAG.getFPExtendOrRound(Op, DL, VT);
2902   assert(VT.isFixedLengthVector() &&
2903          "Unexpected value type for RVV FP extend/round lowering");
2904   SDValue Mask, VL;
2905   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2906   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2907                         ? RISCVISD::FP_EXTEND_VL
2908                         : RISCVISD::FP_ROUND_VL;
2909   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2910 }
2911 
2912 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2913 // the exponent.
2914 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2915   MVT VT = Op.getSimpleValueType();
2916   unsigned EltSize = VT.getScalarSizeInBits();
2917   SDValue Src = Op.getOperand(0);
2918   SDLoc DL(Op);
2919 
2920   // We need a FP type that can represent the value.
2921   // TODO: Use f16 for i8 when possible?
2922   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2923   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2924 
2925   // Legal types should have been checked in the RISCVTargetLowering
2926   // constructor.
2927   // TODO: Splitting may make sense in some cases.
2928   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2929          "Expected legal float type!");
2930 
2931   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2932   // The trailing zero count is equal to log2 of this single bit value.
2933   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2934     SDValue Neg =
2935         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2936     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2937   }
2938 
2939   // We have a legal FP type, convert to it.
2940   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2941   // Bitcast to integer and shift the exponent to the LSB.
2942   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2943   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2944   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2945   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2946                               DAG.getConstant(ShiftAmt, DL, IntVT));
2947   // Truncate back to original type to allow vnsrl.
2948   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2949   // The exponent contains log2 of the value in biased form.
2950   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2951 
2952   // For trailing zeros, we just need to subtract the bias.
2953   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2954     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2955                        DAG.getConstant(ExponentBias, DL, VT));
2956 
2957   // For leading zeros, we need to remove the bias and convert from log2 to
2958   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2959   unsigned Adjust = ExponentBias + (EltSize - 1);
2960   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2961 }
2962 
2963 // While RVV has alignment restrictions, we should always be able to load as a
2964 // legal equivalently-sized byte-typed vector instead. This method is
2965 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2966 // the load is already correctly-aligned, it returns SDValue().
2967 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2968                                                     SelectionDAG &DAG) const {
2969   auto *Load = cast<LoadSDNode>(Op);
2970   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2971 
2972   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2973                                      Load->getMemoryVT(),
2974                                      *Load->getMemOperand()))
2975     return SDValue();
2976 
2977   SDLoc DL(Op);
2978   MVT VT = Op.getSimpleValueType();
2979   unsigned EltSizeBits = VT.getScalarSizeInBits();
2980   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2981          "Unexpected unaligned RVV load type");
2982   MVT NewVT =
2983       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2984   assert(NewVT.isValid() &&
2985          "Expecting equally-sized RVV vector types to be legal");
2986   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2987                           Load->getPointerInfo(), Load->getOriginalAlign(),
2988                           Load->getMemOperand()->getFlags());
2989   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2990 }
2991 
2992 // While RVV has alignment restrictions, we should always be able to store as a
2993 // legal equivalently-sized byte-typed vector instead. This method is
2994 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2995 // returns SDValue() if the store is already correctly aligned.
2996 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2997                                                      SelectionDAG &DAG) const {
2998   auto *Store = cast<StoreSDNode>(Op);
2999   assert(Store && Store->getValue().getValueType().isVector() &&
3000          "Expected vector store");
3001 
3002   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3003                                      Store->getMemoryVT(),
3004                                      *Store->getMemOperand()))
3005     return SDValue();
3006 
3007   SDLoc DL(Op);
3008   SDValue StoredVal = Store->getValue();
3009   MVT VT = StoredVal.getSimpleValueType();
3010   unsigned EltSizeBits = VT.getScalarSizeInBits();
3011   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3012          "Unexpected unaligned RVV store type");
3013   MVT NewVT =
3014       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3015   assert(NewVT.isValid() &&
3016          "Expecting equally-sized RVV vector types to be legal");
3017   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3018   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3019                       Store->getPointerInfo(), Store->getOriginalAlign(),
3020                       Store->getMemOperand()->getFlags());
3021 }
3022 
3023 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3024                                             SelectionDAG &DAG) const {
3025   switch (Op.getOpcode()) {
3026   default:
3027     report_fatal_error("unimplemented operand");
3028   case ISD::GlobalAddress:
3029     return lowerGlobalAddress(Op, DAG);
3030   case ISD::BlockAddress:
3031     return lowerBlockAddress(Op, DAG);
3032   case ISD::ConstantPool:
3033     return lowerConstantPool(Op, DAG);
3034   case ISD::JumpTable:
3035     return lowerJumpTable(Op, DAG);
3036   case ISD::GlobalTLSAddress:
3037     return lowerGlobalTLSAddress(Op, DAG);
3038   case ISD::SELECT:
3039     return lowerSELECT(Op, DAG);
3040   case ISD::BRCOND:
3041     return lowerBRCOND(Op, DAG);
3042   case ISD::VASTART:
3043     return lowerVASTART(Op, DAG);
3044   case ISD::FRAMEADDR:
3045     return lowerFRAMEADDR(Op, DAG);
3046   case ISD::RETURNADDR:
3047     return lowerRETURNADDR(Op, DAG);
3048   case ISD::SHL_PARTS:
3049     return lowerShiftLeftParts(Op, DAG);
3050   case ISD::SRA_PARTS:
3051     return lowerShiftRightParts(Op, DAG, true);
3052   case ISD::SRL_PARTS:
3053     return lowerShiftRightParts(Op, DAG, false);
3054   case ISD::BITCAST: {
3055     SDLoc DL(Op);
3056     EVT VT = Op.getValueType();
3057     SDValue Op0 = Op.getOperand(0);
3058     EVT Op0VT = Op0.getValueType();
3059     MVT XLenVT = Subtarget.getXLenVT();
3060     if (VT.isFixedLengthVector()) {
3061       // We can handle fixed length vector bitcasts with a simple replacement
3062       // in isel.
3063       if (Op0VT.isFixedLengthVector())
3064         return Op;
3065       // When bitcasting from scalar to fixed-length vector, insert the scalar
3066       // into a one-element vector of the result type, and perform a vector
3067       // bitcast.
3068       if (!Op0VT.isVector()) {
3069         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3070         if (!isTypeLegal(BVT))
3071           return SDValue();
3072         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3073                                               DAG.getUNDEF(BVT), Op0,
3074                                               DAG.getConstant(0, DL, XLenVT)));
3075       }
3076       return SDValue();
3077     }
3078     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3079     // thus: bitcast the vector to a one-element vector type whose element type
3080     // is the same as the result type, and extract the first element.
3081     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3082       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3083       if (!isTypeLegal(BVT))
3084         return SDValue();
3085       SDValue BVec = DAG.getBitcast(BVT, Op0);
3086       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3087                          DAG.getConstant(0, DL, XLenVT));
3088     }
3089     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3090       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3091       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3092       return FPConv;
3093     }
3094     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3095         Subtarget.hasStdExtF()) {
3096       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3097       SDValue FPConv =
3098           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3099       return FPConv;
3100     }
3101     return SDValue();
3102   }
3103   case ISD::INTRINSIC_WO_CHAIN:
3104     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3105   case ISD::INTRINSIC_W_CHAIN:
3106     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3107   case ISD::INTRINSIC_VOID:
3108     return LowerINTRINSIC_VOID(Op, DAG);
3109   case ISD::BSWAP:
3110   case ISD::BITREVERSE: {
3111     MVT VT = Op.getSimpleValueType();
3112     SDLoc DL(Op);
3113     if (Subtarget.hasStdExtZbp()) {
3114       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3115       // Start with the maximum immediate value which is the bitwidth - 1.
3116       unsigned Imm = VT.getSizeInBits() - 1;
3117       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3118       if (Op.getOpcode() == ISD::BSWAP)
3119         Imm &= ~0x7U;
3120       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3121                          DAG.getConstant(Imm, DL, VT));
3122     }
3123     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3124     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3125     // Expand bitreverse to a bswap(rev8) followed by brev8.
3126     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3127     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3128     // as brev8 by an isel pattern.
3129     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3130                        DAG.getConstant(7, DL, VT));
3131   }
3132   case ISD::FSHL:
3133   case ISD::FSHR: {
3134     MVT VT = Op.getSimpleValueType();
3135     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3136     SDLoc DL(Op);
3137     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3138     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3139     // accidentally setting the extra bit.
3140     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3141     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3142                                 DAG.getConstant(ShAmtWidth, DL, VT));
3143     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3144     // instruction use different orders. fshl will return its first operand for
3145     // shift of zero, fshr will return its second operand. fsl and fsr both
3146     // return rs1 so the ISD nodes need to have different operand orders.
3147     // Shift amount is in rs2.
3148     SDValue Op0 = Op.getOperand(0);
3149     SDValue Op1 = Op.getOperand(1);
3150     unsigned Opc = RISCVISD::FSL;
3151     if (Op.getOpcode() == ISD::FSHR) {
3152       std::swap(Op0, Op1);
3153       Opc = RISCVISD::FSR;
3154     }
3155     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3156   }
3157   case ISD::TRUNCATE: {
3158     SDLoc DL(Op);
3159     MVT VT = Op.getSimpleValueType();
3160     // Only custom-lower vector truncates
3161     if (!VT.isVector())
3162       return Op;
3163 
3164     // Truncates to mask types are handled differently
3165     if (VT.getVectorElementType() == MVT::i1)
3166       return lowerVectorMaskTrunc(Op, DAG);
3167 
3168     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3169     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3170     // truncate by one power of two at a time.
3171     MVT DstEltVT = VT.getVectorElementType();
3172 
3173     SDValue Src = Op.getOperand(0);
3174     MVT SrcVT = Src.getSimpleValueType();
3175     MVT SrcEltVT = SrcVT.getVectorElementType();
3176 
3177     assert(DstEltVT.bitsLT(SrcEltVT) &&
3178            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3179            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3180            "Unexpected vector truncate lowering");
3181 
3182     MVT ContainerVT = SrcVT;
3183     if (SrcVT.isFixedLengthVector()) {
3184       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3185       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3186     }
3187 
3188     SDValue Result = Src;
3189     SDValue Mask, VL;
3190     std::tie(Mask, VL) =
3191         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3192     LLVMContext &Context = *DAG.getContext();
3193     const ElementCount Count = ContainerVT.getVectorElementCount();
3194     do {
3195       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3196       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3197       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3198                            Mask, VL);
3199     } while (SrcEltVT != DstEltVT);
3200 
3201     if (SrcVT.isFixedLengthVector())
3202       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3203 
3204     return Result;
3205   }
3206   case ISD::ANY_EXTEND:
3207   case ISD::ZERO_EXTEND:
3208     if (Op.getOperand(0).getValueType().isVector() &&
3209         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3210       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3211     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3212   case ISD::SIGN_EXTEND:
3213     if (Op.getOperand(0).getValueType().isVector() &&
3214         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3215       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3216     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3217   case ISD::SPLAT_VECTOR_PARTS:
3218     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3219   case ISD::INSERT_VECTOR_ELT:
3220     return lowerINSERT_VECTOR_ELT(Op, DAG);
3221   case ISD::EXTRACT_VECTOR_ELT:
3222     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3223   case ISD::VSCALE: {
3224     MVT VT = Op.getSimpleValueType();
3225     SDLoc DL(Op);
3226     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3227     // We define our scalable vector types for lmul=1 to use a 64 bit known
3228     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3229     // vscale as VLENB / 8.
3230     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3231     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3232       report_fatal_error("Support for VLEN==32 is incomplete.");
3233     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3234       // We assume VLENB is a multiple of 8. We manually choose the best shift
3235       // here because SimplifyDemandedBits isn't always able to simplify it.
3236       uint64_t Val = Op.getConstantOperandVal(0);
3237       if (isPowerOf2_64(Val)) {
3238         uint64_t Log2 = Log2_64(Val);
3239         if (Log2 < 3)
3240           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3241                              DAG.getConstant(3 - Log2, DL, VT));
3242         if (Log2 > 3)
3243           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3244                              DAG.getConstant(Log2 - 3, DL, VT));
3245         return VLENB;
3246       }
3247       // If the multiplier is a multiple of 8, scale it down to avoid needing
3248       // to shift the VLENB value.
3249       if ((Val % 8) == 0)
3250         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3251                            DAG.getConstant(Val / 8, DL, VT));
3252     }
3253 
3254     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3255                                  DAG.getConstant(3, DL, VT));
3256     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3257   }
3258   case ISD::FPOWI: {
3259     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3260     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3261     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3262         Op.getOperand(1).getValueType() == MVT::i32) {
3263       SDLoc DL(Op);
3264       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3265       SDValue Powi =
3266           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3267       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3268                          DAG.getIntPtrConstant(0, DL));
3269     }
3270     return SDValue();
3271   }
3272   case ISD::FP_EXTEND: {
3273     // RVV can only do fp_extend to types double the size as the source. We
3274     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3275     // via f32.
3276     SDLoc DL(Op);
3277     MVT VT = Op.getSimpleValueType();
3278     SDValue Src = Op.getOperand(0);
3279     MVT SrcVT = Src.getSimpleValueType();
3280 
3281     // Prepare any fixed-length vector operands.
3282     MVT ContainerVT = VT;
3283     if (SrcVT.isFixedLengthVector()) {
3284       ContainerVT = getContainerForFixedLengthVector(VT);
3285       MVT SrcContainerVT =
3286           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3287       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3288     }
3289 
3290     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3291         SrcVT.getVectorElementType() != MVT::f16) {
3292       // For scalable vectors, we only need to close the gap between
3293       // vXf16->vXf64.
3294       if (!VT.isFixedLengthVector())
3295         return Op;
3296       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3297       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3298       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3299     }
3300 
3301     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3302     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3303     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3304         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3305 
3306     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3307                                            DL, DAG, Subtarget);
3308     if (VT.isFixedLengthVector())
3309       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3310     return Extend;
3311   }
3312   case ISD::FP_ROUND: {
3313     // RVV can only do fp_round to types half the size as the source. We
3314     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3315     // conversion instruction.
3316     SDLoc DL(Op);
3317     MVT VT = Op.getSimpleValueType();
3318     SDValue Src = Op.getOperand(0);
3319     MVT SrcVT = Src.getSimpleValueType();
3320 
3321     // Prepare any fixed-length vector operands.
3322     MVT ContainerVT = VT;
3323     if (VT.isFixedLengthVector()) {
3324       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3325       ContainerVT =
3326           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3327       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3328     }
3329 
3330     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3331         SrcVT.getVectorElementType() != MVT::f64) {
3332       // For scalable vectors, we only need to close the gap between
3333       // vXf64<->vXf16.
3334       if (!VT.isFixedLengthVector())
3335         return Op;
3336       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3337       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3338       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3339     }
3340 
3341     SDValue Mask, VL;
3342     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3343 
3344     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3345     SDValue IntermediateRound =
3346         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3347     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3348                                           DL, DAG, Subtarget);
3349 
3350     if (VT.isFixedLengthVector())
3351       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3352     return Round;
3353   }
3354   case ISD::FP_TO_SINT:
3355   case ISD::FP_TO_UINT:
3356   case ISD::SINT_TO_FP:
3357   case ISD::UINT_TO_FP: {
3358     // RVV can only do fp<->int conversions to types half/double the size as
3359     // the source. We custom-lower any conversions that do two hops into
3360     // sequences.
3361     MVT VT = Op.getSimpleValueType();
3362     if (!VT.isVector())
3363       return Op;
3364     SDLoc DL(Op);
3365     SDValue Src = Op.getOperand(0);
3366     MVT EltVT = VT.getVectorElementType();
3367     MVT SrcVT = Src.getSimpleValueType();
3368     MVT SrcEltVT = SrcVT.getVectorElementType();
3369     unsigned EltSize = EltVT.getSizeInBits();
3370     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3371     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3372            "Unexpected vector element types");
3373 
3374     bool IsInt2FP = SrcEltVT.isInteger();
3375     // Widening conversions
3376     if (EltSize > (2 * SrcEltSize)) {
3377       if (IsInt2FP) {
3378         // Do a regular integer sign/zero extension then convert to float.
3379         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3380                                       VT.getVectorElementCount());
3381         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3382                                  ? ISD::ZERO_EXTEND
3383                                  : ISD::SIGN_EXTEND;
3384         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3385         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3386       }
3387       // FP2Int
3388       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3389       // Do one doubling fp_extend then complete the operation by converting
3390       // to int.
3391       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3392       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3393       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3394     }
3395 
3396     // Narrowing conversions
3397     if (SrcEltSize > (2 * EltSize)) {
3398       if (IsInt2FP) {
3399         // One narrowing int_to_fp, then an fp_round.
3400         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3401         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3402         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3403         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3404       }
3405       // FP2Int
3406       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3407       // representable by the integer, the result is poison.
3408       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3409                                     VT.getVectorElementCount());
3410       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3411       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3412     }
3413 
3414     // Scalable vectors can exit here. Patterns will handle equally-sized
3415     // conversions halving/doubling ones.
3416     if (!VT.isFixedLengthVector())
3417       return Op;
3418 
3419     // For fixed-length vectors we lower to a custom "VL" node.
3420     unsigned RVVOpc = 0;
3421     switch (Op.getOpcode()) {
3422     default:
3423       llvm_unreachable("Impossible opcode");
3424     case ISD::FP_TO_SINT:
3425       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3426       break;
3427     case ISD::FP_TO_UINT:
3428       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3429       break;
3430     case ISD::SINT_TO_FP:
3431       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3432       break;
3433     case ISD::UINT_TO_FP:
3434       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3435       break;
3436     }
3437 
3438     MVT ContainerVT, SrcContainerVT;
3439     // Derive the reference container type from the larger vector type.
3440     if (SrcEltSize > EltSize) {
3441       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3442       ContainerVT =
3443           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3444     } else {
3445       ContainerVT = getContainerForFixedLengthVector(VT);
3446       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3447     }
3448 
3449     SDValue Mask, VL;
3450     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3451 
3452     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3453     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3454     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3455   }
3456   case ISD::FP_TO_SINT_SAT:
3457   case ISD::FP_TO_UINT_SAT:
3458     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3459   case ISD::FTRUNC:
3460   case ISD::FCEIL:
3461   case ISD::FFLOOR:
3462     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3463   case ISD::FROUND:
3464     return lowerFROUND(Op, DAG);
3465   case ISD::VECREDUCE_ADD:
3466   case ISD::VECREDUCE_UMAX:
3467   case ISD::VECREDUCE_SMAX:
3468   case ISD::VECREDUCE_UMIN:
3469   case ISD::VECREDUCE_SMIN:
3470     return lowerVECREDUCE(Op, DAG);
3471   case ISD::VECREDUCE_AND:
3472   case ISD::VECREDUCE_OR:
3473   case ISD::VECREDUCE_XOR:
3474     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3475       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3476     return lowerVECREDUCE(Op, DAG);
3477   case ISD::VECREDUCE_FADD:
3478   case ISD::VECREDUCE_SEQ_FADD:
3479   case ISD::VECREDUCE_FMIN:
3480   case ISD::VECREDUCE_FMAX:
3481     return lowerFPVECREDUCE(Op, DAG);
3482   case ISD::VP_REDUCE_ADD:
3483   case ISD::VP_REDUCE_UMAX:
3484   case ISD::VP_REDUCE_SMAX:
3485   case ISD::VP_REDUCE_UMIN:
3486   case ISD::VP_REDUCE_SMIN:
3487   case ISD::VP_REDUCE_FADD:
3488   case ISD::VP_REDUCE_SEQ_FADD:
3489   case ISD::VP_REDUCE_FMIN:
3490   case ISD::VP_REDUCE_FMAX:
3491     return lowerVPREDUCE(Op, DAG);
3492   case ISD::VP_REDUCE_AND:
3493   case ISD::VP_REDUCE_OR:
3494   case ISD::VP_REDUCE_XOR:
3495     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3496       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3497     return lowerVPREDUCE(Op, DAG);
3498   case ISD::INSERT_SUBVECTOR:
3499     return lowerINSERT_SUBVECTOR(Op, DAG);
3500   case ISD::EXTRACT_SUBVECTOR:
3501     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3502   case ISD::STEP_VECTOR:
3503     return lowerSTEP_VECTOR(Op, DAG);
3504   case ISD::VECTOR_REVERSE:
3505     return lowerVECTOR_REVERSE(Op, DAG);
3506   case ISD::VECTOR_SPLICE:
3507     return lowerVECTOR_SPLICE(Op, DAG);
3508   case ISD::BUILD_VECTOR:
3509     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3510   case ISD::SPLAT_VECTOR:
3511     if (Op.getValueType().getVectorElementType() == MVT::i1)
3512       return lowerVectorMaskSplat(Op, DAG);
3513     return SDValue();
3514   case ISD::VECTOR_SHUFFLE:
3515     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3516   case ISD::CONCAT_VECTORS: {
3517     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3518     // better than going through the stack, as the default expansion does.
3519     SDLoc DL(Op);
3520     MVT VT = Op.getSimpleValueType();
3521     unsigned NumOpElts =
3522         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3523     SDValue Vec = DAG.getUNDEF(VT);
3524     for (const auto &OpIdx : enumerate(Op->ops())) {
3525       SDValue SubVec = OpIdx.value();
3526       // Don't insert undef subvectors.
3527       if (SubVec.isUndef())
3528         continue;
3529       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3530                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3531     }
3532     return Vec;
3533   }
3534   case ISD::LOAD:
3535     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3536       return V;
3537     if (Op.getValueType().isFixedLengthVector())
3538       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3539     return Op;
3540   case ISD::STORE:
3541     if (auto V = expandUnalignedRVVStore(Op, DAG))
3542       return V;
3543     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3544       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3545     return Op;
3546   case ISD::MLOAD:
3547   case ISD::VP_LOAD:
3548     return lowerMaskedLoad(Op, DAG);
3549   case ISD::MSTORE:
3550   case ISD::VP_STORE:
3551     return lowerMaskedStore(Op, DAG);
3552   case ISD::SETCC:
3553     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3554   case ISD::ADD:
3555     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3556   case ISD::SUB:
3557     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3558   case ISD::MUL:
3559     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3560   case ISD::MULHS:
3561     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3562   case ISD::MULHU:
3563     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3564   case ISD::AND:
3565     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3566                                               RISCVISD::AND_VL);
3567   case ISD::OR:
3568     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3569                                               RISCVISD::OR_VL);
3570   case ISD::XOR:
3571     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3572                                               RISCVISD::XOR_VL);
3573   case ISD::SDIV:
3574     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3575   case ISD::SREM:
3576     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3577   case ISD::UDIV:
3578     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3579   case ISD::UREM:
3580     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3581   case ISD::SHL:
3582   case ISD::SRA:
3583   case ISD::SRL:
3584     if (Op.getSimpleValueType().isFixedLengthVector())
3585       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3586     // This can be called for an i32 shift amount that needs to be promoted.
3587     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3588            "Unexpected custom legalisation");
3589     return SDValue();
3590   case ISD::SADDSAT:
3591     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3592   case ISD::UADDSAT:
3593     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3594   case ISD::SSUBSAT:
3595     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3596   case ISD::USUBSAT:
3597     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3598   case ISD::FADD:
3599     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3600   case ISD::FSUB:
3601     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3602   case ISD::FMUL:
3603     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3604   case ISD::FDIV:
3605     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3606   case ISD::FNEG:
3607     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3608   case ISD::FABS:
3609     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3610   case ISD::FSQRT:
3611     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3612   case ISD::FMA:
3613     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3614   case ISD::SMIN:
3615     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3616   case ISD::SMAX:
3617     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3618   case ISD::UMIN:
3619     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3620   case ISD::UMAX:
3621     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3622   case ISD::FMINNUM:
3623     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3624   case ISD::FMAXNUM:
3625     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3626   case ISD::ABS:
3627     return lowerABS(Op, DAG);
3628   case ISD::CTLZ_ZERO_UNDEF:
3629   case ISD::CTTZ_ZERO_UNDEF:
3630     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3631   case ISD::VSELECT:
3632     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3633   case ISD::FCOPYSIGN:
3634     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3635   case ISD::MGATHER:
3636   case ISD::VP_GATHER:
3637     return lowerMaskedGather(Op, DAG);
3638   case ISD::MSCATTER:
3639   case ISD::VP_SCATTER:
3640     return lowerMaskedScatter(Op, DAG);
3641   case ISD::FLT_ROUNDS_:
3642     return lowerGET_ROUNDING(Op, DAG);
3643   case ISD::SET_ROUNDING:
3644     return lowerSET_ROUNDING(Op, DAG);
3645   case ISD::VP_SELECT:
3646     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3647   case ISD::VP_MERGE:
3648     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3649   case ISD::VP_ADD:
3650     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3651   case ISD::VP_SUB:
3652     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3653   case ISD::VP_MUL:
3654     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3655   case ISD::VP_SDIV:
3656     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3657   case ISD::VP_UDIV:
3658     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3659   case ISD::VP_SREM:
3660     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3661   case ISD::VP_UREM:
3662     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3663   case ISD::VP_AND:
3664     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3665   case ISD::VP_OR:
3666     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3667   case ISD::VP_XOR:
3668     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3669   case ISD::VP_ASHR:
3670     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3671   case ISD::VP_LSHR:
3672     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3673   case ISD::VP_SHL:
3674     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3675   case ISD::VP_FADD:
3676     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3677   case ISD::VP_FSUB:
3678     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3679   case ISD::VP_FMUL:
3680     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3681   case ISD::VP_FDIV:
3682     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3683   case ISD::VP_FNEG:
3684     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3685   case ISD::VP_FMA:
3686     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3687   case ISD::VP_FPTOSI:
3688     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3689   case ISD::VP_SITOFP:
3690     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3691   }
3692 }
3693 
3694 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3695                              SelectionDAG &DAG, unsigned Flags) {
3696   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3697 }
3698 
3699 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3700                              SelectionDAG &DAG, unsigned Flags) {
3701   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3702                                    Flags);
3703 }
3704 
3705 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3706                              SelectionDAG &DAG, unsigned Flags) {
3707   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3708                                    N->getOffset(), Flags);
3709 }
3710 
3711 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3712                              SelectionDAG &DAG, unsigned Flags) {
3713   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3714 }
3715 
3716 template <class NodeTy>
3717 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3718                                      bool IsLocal) const {
3719   SDLoc DL(N);
3720   EVT Ty = getPointerTy(DAG.getDataLayout());
3721 
3722   if (isPositionIndependent()) {
3723     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3724     if (IsLocal)
3725       // Use PC-relative addressing to access the symbol. This generates the
3726       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3727       // %pcrel_lo(auipc)).
3728       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3729 
3730     // Use PC-relative addressing to access the GOT for this symbol, then load
3731     // the address from the GOT. This generates the pattern (PseudoLA sym),
3732     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3733     SDValue Load =
3734         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3735     MachineFunction &MF = DAG.getMachineFunction();
3736     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3737         MachinePointerInfo::getGOT(MF),
3738         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3739             MachineMemOperand::MOInvariant,
3740         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3741     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3742     return Load;
3743   }
3744 
3745   switch (getTargetMachine().getCodeModel()) {
3746   default:
3747     report_fatal_error("Unsupported code model for lowering");
3748   case CodeModel::Small: {
3749     // Generate a sequence for accessing addresses within the first 2 GiB of
3750     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3751     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3752     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3753     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3754     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3755   }
3756   case CodeModel::Medium: {
3757     // Generate a sequence for accessing addresses within any 2GiB range within
3758     // the address space. This generates the pattern (PseudoLLA sym), which
3759     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3760     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3761     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3762   }
3763   }
3764 }
3765 
3766 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3767     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3768 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3769     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3770 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3771     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3772 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3773     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3774 
3775 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3776                                                 SelectionDAG &DAG) const {
3777   SDLoc DL(Op);
3778   EVT Ty = Op.getValueType();
3779   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3780   int64_t Offset = N->getOffset();
3781   MVT XLenVT = Subtarget.getXLenVT();
3782 
3783   const GlobalValue *GV = N->getGlobal();
3784   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3785   SDValue Addr = getAddr(N, DAG, IsLocal);
3786 
3787   // In order to maximise the opportunity for common subexpression elimination,
3788   // emit a separate ADD node for the global address offset instead of folding
3789   // it in the global address node. Later peephole optimisations may choose to
3790   // fold it back in when profitable.
3791   if (Offset != 0)
3792     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3793                        DAG.getConstant(Offset, DL, XLenVT));
3794   return Addr;
3795 }
3796 
3797 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3798                                                SelectionDAG &DAG) const {
3799   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3800 
3801   return getAddr(N, DAG);
3802 }
3803 
3804 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3805                                                SelectionDAG &DAG) const {
3806   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3807 
3808   return getAddr(N, DAG);
3809 }
3810 
3811 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3812                                             SelectionDAG &DAG) const {
3813   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3814 
3815   return getAddr(N, DAG);
3816 }
3817 
3818 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3819                                               SelectionDAG &DAG,
3820                                               bool UseGOT) const {
3821   SDLoc DL(N);
3822   EVT Ty = getPointerTy(DAG.getDataLayout());
3823   const GlobalValue *GV = N->getGlobal();
3824   MVT XLenVT = Subtarget.getXLenVT();
3825 
3826   if (UseGOT) {
3827     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3828     // load the address from the GOT and add the thread pointer. This generates
3829     // the pattern (PseudoLA_TLS_IE sym), which expands to
3830     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3831     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3832     SDValue Load =
3833         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3834     MachineFunction &MF = DAG.getMachineFunction();
3835     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3836         MachinePointerInfo::getGOT(MF),
3837         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3838             MachineMemOperand::MOInvariant,
3839         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3840     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3841 
3842     // Add the thread pointer.
3843     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3844     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3845   }
3846 
3847   // Generate a sequence for accessing the address relative to the thread
3848   // pointer, with the appropriate adjustment for the thread pointer offset.
3849   // This generates the pattern
3850   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3851   SDValue AddrHi =
3852       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3853   SDValue AddrAdd =
3854       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3855   SDValue AddrLo =
3856       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3857 
3858   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3859   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3860   SDValue MNAdd = SDValue(
3861       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3862       0);
3863   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3864 }
3865 
3866 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3867                                                SelectionDAG &DAG) const {
3868   SDLoc DL(N);
3869   EVT Ty = getPointerTy(DAG.getDataLayout());
3870   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3871   const GlobalValue *GV = N->getGlobal();
3872 
3873   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3874   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3875   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3876   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3877   SDValue Load =
3878       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3879 
3880   // Prepare argument list to generate call.
3881   ArgListTy Args;
3882   ArgListEntry Entry;
3883   Entry.Node = Load;
3884   Entry.Ty = CallTy;
3885   Args.push_back(Entry);
3886 
3887   // Setup call to __tls_get_addr.
3888   TargetLowering::CallLoweringInfo CLI(DAG);
3889   CLI.setDebugLoc(DL)
3890       .setChain(DAG.getEntryNode())
3891       .setLibCallee(CallingConv::C, CallTy,
3892                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3893                     std::move(Args));
3894 
3895   return LowerCallTo(CLI).first;
3896 }
3897 
3898 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3899                                                    SelectionDAG &DAG) const {
3900   SDLoc DL(Op);
3901   EVT Ty = Op.getValueType();
3902   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3903   int64_t Offset = N->getOffset();
3904   MVT XLenVT = Subtarget.getXLenVT();
3905 
3906   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3907 
3908   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3909       CallingConv::GHC)
3910     report_fatal_error("In GHC calling convention TLS is not supported");
3911 
3912   SDValue Addr;
3913   switch (Model) {
3914   case TLSModel::LocalExec:
3915     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3916     break;
3917   case TLSModel::InitialExec:
3918     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3919     break;
3920   case TLSModel::LocalDynamic:
3921   case TLSModel::GeneralDynamic:
3922     Addr = getDynamicTLSAddr(N, DAG);
3923     break;
3924   }
3925 
3926   // In order to maximise the opportunity for common subexpression elimination,
3927   // emit a separate ADD node for the global address offset instead of folding
3928   // it in the global address node. Later peephole optimisations may choose to
3929   // fold it back in when profitable.
3930   if (Offset != 0)
3931     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3932                        DAG.getConstant(Offset, DL, XLenVT));
3933   return Addr;
3934 }
3935 
3936 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3937   SDValue CondV = Op.getOperand(0);
3938   SDValue TrueV = Op.getOperand(1);
3939   SDValue FalseV = Op.getOperand(2);
3940   SDLoc DL(Op);
3941   MVT VT = Op.getSimpleValueType();
3942   MVT XLenVT = Subtarget.getXLenVT();
3943 
3944   // Lower vector SELECTs to VSELECTs by splatting the condition.
3945   if (VT.isVector()) {
3946     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3947     SDValue CondSplat = VT.isScalableVector()
3948                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3949                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3950     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3951   }
3952 
3953   // If the result type is XLenVT and CondV is the output of a SETCC node
3954   // which also operated on XLenVT inputs, then merge the SETCC node into the
3955   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3956   // compare+branch instructions. i.e.:
3957   // (select (setcc lhs, rhs, cc), truev, falsev)
3958   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3959   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3960       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3961     SDValue LHS = CondV.getOperand(0);
3962     SDValue RHS = CondV.getOperand(1);
3963     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3964     ISD::CondCode CCVal = CC->get();
3965 
3966     // Special case for a select of 2 constants that have a diffence of 1.
3967     // Normally this is done by DAGCombine, but if the select is introduced by
3968     // type legalization or op legalization, we miss it. Restricting to SETLT
3969     // case for now because that is what signed saturating add/sub need.
3970     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3971     // but we would probably want to swap the true/false values if the condition
3972     // is SETGE/SETLE to avoid an XORI.
3973     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3974         CCVal == ISD::SETLT) {
3975       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3976       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3977       if (TrueVal - 1 == FalseVal)
3978         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3979       if (TrueVal + 1 == FalseVal)
3980         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3981     }
3982 
3983     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3984 
3985     SDValue TargetCC = DAG.getCondCode(CCVal);
3986     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3987     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3988   }
3989 
3990   // Otherwise:
3991   // (select condv, truev, falsev)
3992   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3993   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3994   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3995 
3996   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3997 
3998   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3999 }
4000 
4001 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4002   SDValue CondV = Op.getOperand(1);
4003   SDLoc DL(Op);
4004   MVT XLenVT = Subtarget.getXLenVT();
4005 
4006   if (CondV.getOpcode() == ISD::SETCC &&
4007       CondV.getOperand(0).getValueType() == XLenVT) {
4008     SDValue LHS = CondV.getOperand(0);
4009     SDValue RHS = CondV.getOperand(1);
4010     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4011 
4012     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4013 
4014     SDValue TargetCC = DAG.getCondCode(CCVal);
4015     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4016                        LHS, RHS, TargetCC, Op.getOperand(2));
4017   }
4018 
4019   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4020                      CondV, DAG.getConstant(0, DL, XLenVT),
4021                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4022 }
4023 
4024 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4025   MachineFunction &MF = DAG.getMachineFunction();
4026   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4027 
4028   SDLoc DL(Op);
4029   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4030                                  getPointerTy(MF.getDataLayout()));
4031 
4032   // vastart just stores the address of the VarArgsFrameIndex slot into the
4033   // memory location argument.
4034   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4035   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4036                       MachinePointerInfo(SV));
4037 }
4038 
4039 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4040                                             SelectionDAG &DAG) const {
4041   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4042   MachineFunction &MF = DAG.getMachineFunction();
4043   MachineFrameInfo &MFI = MF.getFrameInfo();
4044   MFI.setFrameAddressIsTaken(true);
4045   Register FrameReg = RI.getFrameRegister(MF);
4046   int XLenInBytes = Subtarget.getXLen() / 8;
4047 
4048   EVT VT = Op.getValueType();
4049   SDLoc DL(Op);
4050   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4051   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4052   while (Depth--) {
4053     int Offset = -(XLenInBytes * 2);
4054     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4055                               DAG.getIntPtrConstant(Offset, DL));
4056     FrameAddr =
4057         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4058   }
4059   return FrameAddr;
4060 }
4061 
4062 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4063                                              SelectionDAG &DAG) const {
4064   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4065   MachineFunction &MF = DAG.getMachineFunction();
4066   MachineFrameInfo &MFI = MF.getFrameInfo();
4067   MFI.setReturnAddressIsTaken(true);
4068   MVT XLenVT = Subtarget.getXLenVT();
4069   int XLenInBytes = Subtarget.getXLen() / 8;
4070 
4071   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4072     return SDValue();
4073 
4074   EVT VT = Op.getValueType();
4075   SDLoc DL(Op);
4076   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4077   if (Depth) {
4078     int Off = -XLenInBytes;
4079     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4080     SDValue Offset = DAG.getConstant(Off, DL, VT);
4081     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4082                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4083                        MachinePointerInfo());
4084   }
4085 
4086   // Return the value of the return address register, marking it an implicit
4087   // live-in.
4088   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4089   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4090 }
4091 
4092 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4093                                                  SelectionDAG &DAG) const {
4094   SDLoc DL(Op);
4095   SDValue Lo = Op.getOperand(0);
4096   SDValue Hi = Op.getOperand(1);
4097   SDValue Shamt = Op.getOperand(2);
4098   EVT VT = Lo.getValueType();
4099 
4100   // if Shamt-XLEN < 0: // Shamt < XLEN
4101   //   Lo = Lo << Shamt
4102   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4103   // else:
4104   //   Lo = 0
4105   //   Hi = Lo << (Shamt-XLEN)
4106 
4107   SDValue Zero = DAG.getConstant(0, DL, VT);
4108   SDValue One = DAG.getConstant(1, DL, VT);
4109   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4110   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4111   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4112   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4113 
4114   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4115   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4116   SDValue ShiftRightLo =
4117       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4118   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4119   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4120   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4121 
4122   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4123 
4124   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4125   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4126 
4127   SDValue Parts[2] = {Lo, Hi};
4128   return DAG.getMergeValues(Parts, DL);
4129 }
4130 
4131 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4132                                                   bool IsSRA) const {
4133   SDLoc DL(Op);
4134   SDValue Lo = Op.getOperand(0);
4135   SDValue Hi = Op.getOperand(1);
4136   SDValue Shamt = Op.getOperand(2);
4137   EVT VT = Lo.getValueType();
4138 
4139   // SRA expansion:
4140   //   if Shamt-XLEN < 0: // Shamt < XLEN
4141   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4142   //     Hi = Hi >>s Shamt
4143   //   else:
4144   //     Lo = Hi >>s (Shamt-XLEN);
4145   //     Hi = Hi >>s (XLEN-1)
4146   //
4147   // SRL expansion:
4148   //   if Shamt-XLEN < 0: // Shamt < XLEN
4149   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4150   //     Hi = Hi >>u Shamt
4151   //   else:
4152   //     Lo = Hi >>u (Shamt-XLEN);
4153   //     Hi = 0;
4154 
4155   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4156 
4157   SDValue Zero = DAG.getConstant(0, DL, VT);
4158   SDValue One = DAG.getConstant(1, DL, VT);
4159   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4160   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4161   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4162   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4163 
4164   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4165   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4166   SDValue ShiftLeftHi =
4167       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4168   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4169   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4170   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4171   SDValue HiFalse =
4172       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4173 
4174   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4175 
4176   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4177   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4178 
4179   SDValue Parts[2] = {Lo, Hi};
4180   return DAG.getMergeValues(Parts, DL);
4181 }
4182 
4183 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4184 // legal equivalently-sized i8 type, so we can use that as a go-between.
4185 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4186                                                   SelectionDAG &DAG) const {
4187   SDLoc DL(Op);
4188   MVT VT = Op.getSimpleValueType();
4189   SDValue SplatVal = Op.getOperand(0);
4190   // All-zeros or all-ones splats are handled specially.
4191   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4192     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4193     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4194   }
4195   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4196     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4197     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4198   }
4199   MVT XLenVT = Subtarget.getXLenVT();
4200   assert(SplatVal.getValueType() == XLenVT &&
4201          "Unexpected type for i1 splat value");
4202   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4203   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4204                          DAG.getConstant(1, DL, XLenVT));
4205   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4206   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4207   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4208 }
4209 
4210 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4211 // illegal (currently only vXi64 RV32).
4212 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4213 // them to VMV_V_X_VL.
4214 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4215                                                      SelectionDAG &DAG) const {
4216   SDLoc DL(Op);
4217   MVT VecVT = Op.getSimpleValueType();
4218   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4219          "Unexpected SPLAT_VECTOR_PARTS lowering");
4220 
4221   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4222   SDValue Lo = Op.getOperand(0);
4223   SDValue Hi = Op.getOperand(1);
4224 
4225   if (VecVT.isFixedLengthVector()) {
4226     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4227     SDLoc DL(Op);
4228     SDValue Mask, VL;
4229     std::tie(Mask, VL) =
4230         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4231 
4232     SDValue Res =
4233         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4234     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4235   }
4236 
4237   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4238     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4239     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4240     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4241     // node in order to try and match RVV vector/scalar instructions.
4242     if ((LoC >> 31) == HiC)
4243       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4244                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4245   }
4246 
4247   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4248   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4249       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4250       Hi.getConstantOperandVal(1) == 31)
4251     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4252                        DAG.getRegister(RISCV::X0, MVT::i32));
4253 
4254   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4255   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4256                      DAG.getUNDEF(VecVT), Lo, Hi,
4257                      DAG.getRegister(RISCV::X0, MVT::i32));
4258 }
4259 
4260 // Custom-lower extensions from mask vectors by using a vselect either with 1
4261 // for zero/any-extension or -1 for sign-extension:
4262 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4263 // Note that any-extension is lowered identically to zero-extension.
4264 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4265                                                 int64_t ExtTrueVal) const {
4266   SDLoc DL(Op);
4267   MVT VecVT = Op.getSimpleValueType();
4268   SDValue Src = Op.getOperand(0);
4269   // Only custom-lower extensions from mask types
4270   assert(Src.getValueType().isVector() &&
4271          Src.getValueType().getVectorElementType() == MVT::i1);
4272 
4273   if (VecVT.isScalableVector()) {
4274     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4275     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4276     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4277   }
4278 
4279   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4280   MVT I1ContainerVT =
4281       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4282 
4283   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4284 
4285   SDValue Mask, VL;
4286   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4287 
4288   MVT XLenVT = Subtarget.getXLenVT();
4289   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4290   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4291 
4292   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4293                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4294   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4295                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4296   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4297                                SplatTrueVal, SplatZero, VL);
4298 
4299   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4300 }
4301 
4302 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4303     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4304   MVT ExtVT = Op.getSimpleValueType();
4305   // Only custom-lower extensions from fixed-length vector types.
4306   if (!ExtVT.isFixedLengthVector())
4307     return Op;
4308   MVT VT = Op.getOperand(0).getSimpleValueType();
4309   // Grab the canonical container type for the extended type. Infer the smaller
4310   // type from that to ensure the same number of vector elements, as we know
4311   // the LMUL will be sufficient to hold the smaller type.
4312   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4313   // Get the extended container type manually to ensure the same number of
4314   // vector elements between source and dest.
4315   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4316                                      ContainerExtVT.getVectorElementCount());
4317 
4318   SDValue Op1 =
4319       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4320 
4321   SDLoc DL(Op);
4322   SDValue Mask, VL;
4323   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4324 
4325   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4326 
4327   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4328 }
4329 
4330 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4331 // setcc operation:
4332 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4333 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4334                                                   SelectionDAG &DAG) const {
4335   SDLoc DL(Op);
4336   EVT MaskVT = Op.getValueType();
4337   // Only expect to custom-lower truncations to mask types
4338   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4339          "Unexpected type for vector mask lowering");
4340   SDValue Src = Op.getOperand(0);
4341   MVT VecVT = Src.getSimpleValueType();
4342 
4343   // If this is a fixed vector, we need to convert it to a scalable vector.
4344   MVT ContainerVT = VecVT;
4345   if (VecVT.isFixedLengthVector()) {
4346     ContainerVT = getContainerForFixedLengthVector(VecVT);
4347     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4348   }
4349 
4350   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4351   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4352 
4353   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4354                          DAG.getUNDEF(ContainerVT), SplatOne);
4355   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4356                           DAG.getUNDEF(ContainerVT), SplatZero);
4357 
4358   if (VecVT.isScalableVector()) {
4359     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4360     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4361   }
4362 
4363   SDValue Mask, VL;
4364   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4365 
4366   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4367   SDValue Trunc =
4368       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4369   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4370                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4371   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4372 }
4373 
4374 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4375 // first position of a vector, and that vector is slid up to the insert index.
4376 // By limiting the active vector length to index+1 and merging with the
4377 // original vector (with an undisturbed tail policy for elements >= VL), we
4378 // achieve the desired result of leaving all elements untouched except the one
4379 // at VL-1, which is replaced with the desired value.
4380 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4381                                                     SelectionDAG &DAG) const {
4382   SDLoc DL(Op);
4383   MVT VecVT = Op.getSimpleValueType();
4384   SDValue Vec = Op.getOperand(0);
4385   SDValue Val = Op.getOperand(1);
4386   SDValue Idx = Op.getOperand(2);
4387 
4388   if (VecVT.getVectorElementType() == MVT::i1) {
4389     // FIXME: For now we just promote to an i8 vector and insert into that,
4390     // but this is probably not optimal.
4391     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4392     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4393     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4394     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4395   }
4396 
4397   MVT ContainerVT = VecVT;
4398   // If the operand is a fixed-length vector, convert to a scalable one.
4399   if (VecVT.isFixedLengthVector()) {
4400     ContainerVT = getContainerForFixedLengthVector(VecVT);
4401     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4402   }
4403 
4404   MVT XLenVT = Subtarget.getXLenVT();
4405 
4406   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4407   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4408   // Even i64-element vectors on RV32 can be lowered without scalar
4409   // legalization if the most-significant 32 bits of the value are not affected
4410   // by the sign-extension of the lower 32 bits.
4411   // TODO: We could also catch sign extensions of a 32-bit value.
4412   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4413     const auto *CVal = cast<ConstantSDNode>(Val);
4414     if (isInt<32>(CVal->getSExtValue())) {
4415       IsLegalInsert = true;
4416       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4417     }
4418   }
4419 
4420   SDValue Mask, VL;
4421   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4422 
4423   SDValue ValInVec;
4424 
4425   if (IsLegalInsert) {
4426     unsigned Opc =
4427         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4428     if (isNullConstant(Idx)) {
4429       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4430       if (!VecVT.isFixedLengthVector())
4431         return Vec;
4432       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4433     }
4434     ValInVec =
4435         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4436   } else {
4437     // On RV32, i64-element vectors must be specially handled to place the
4438     // value at element 0, by using two vslide1up instructions in sequence on
4439     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4440     // this.
4441     SDValue One = DAG.getConstant(1, DL, XLenVT);
4442     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4443     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4444     MVT I32ContainerVT =
4445         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4446     SDValue I32Mask =
4447         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4448     // Limit the active VL to two.
4449     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4450     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4451     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4452     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4453                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4454     // First slide in the hi value, then the lo in underneath it.
4455     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4456                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4457                            I32Mask, InsertI64VL);
4458     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4459                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4460                            I32Mask, InsertI64VL);
4461     // Bitcast back to the right container type.
4462     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4463   }
4464 
4465   // Now that the value is in a vector, slide it into position.
4466   SDValue InsertVL =
4467       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4468   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4469                                 ValInVec, Idx, Mask, InsertVL);
4470   if (!VecVT.isFixedLengthVector())
4471     return Slideup;
4472   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4473 }
4474 
4475 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4476 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4477 // types this is done using VMV_X_S to allow us to glean information about the
4478 // sign bits of the result.
4479 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4480                                                      SelectionDAG &DAG) const {
4481   SDLoc DL(Op);
4482   SDValue Idx = Op.getOperand(1);
4483   SDValue Vec = Op.getOperand(0);
4484   EVT EltVT = Op.getValueType();
4485   MVT VecVT = Vec.getSimpleValueType();
4486   MVT XLenVT = Subtarget.getXLenVT();
4487 
4488   if (VecVT.getVectorElementType() == MVT::i1) {
4489     if (VecVT.isFixedLengthVector()) {
4490       unsigned NumElts = VecVT.getVectorNumElements();
4491       if (NumElts >= 8) {
4492         MVT WideEltVT;
4493         unsigned WidenVecLen;
4494         SDValue ExtractElementIdx;
4495         SDValue ExtractBitIdx;
4496         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4497         MVT LargestEltVT = MVT::getIntegerVT(
4498             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4499         if (NumElts <= LargestEltVT.getSizeInBits()) {
4500           assert(isPowerOf2_32(NumElts) &&
4501                  "the number of elements should be power of 2");
4502           WideEltVT = MVT::getIntegerVT(NumElts);
4503           WidenVecLen = 1;
4504           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4505           ExtractBitIdx = Idx;
4506         } else {
4507           WideEltVT = LargestEltVT;
4508           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4509           // extract element index = index / element width
4510           ExtractElementIdx = DAG.getNode(
4511               ISD::SRL, DL, XLenVT, Idx,
4512               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4513           // mask bit index = index % element width
4514           ExtractBitIdx = DAG.getNode(
4515               ISD::AND, DL, XLenVT, Idx,
4516               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4517         }
4518         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4519         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4520         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4521                                          Vec, ExtractElementIdx);
4522         // Extract the bit from GPR.
4523         SDValue ShiftRight =
4524             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4525         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4526                            DAG.getConstant(1, DL, XLenVT));
4527       }
4528     }
4529     // Otherwise, promote to an i8 vector and extract from that.
4530     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4531     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4532     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4533   }
4534 
4535   // If this is a fixed vector, we need to convert it to a scalable vector.
4536   MVT ContainerVT = VecVT;
4537   if (VecVT.isFixedLengthVector()) {
4538     ContainerVT = getContainerForFixedLengthVector(VecVT);
4539     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4540   }
4541 
4542   // If the index is 0, the vector is already in the right position.
4543   if (!isNullConstant(Idx)) {
4544     // Use a VL of 1 to avoid processing more elements than we need.
4545     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4546     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4547     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4548     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4549                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4550   }
4551 
4552   if (!EltVT.isInteger()) {
4553     // Floating-point extracts are handled in TableGen.
4554     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4555                        DAG.getConstant(0, DL, XLenVT));
4556   }
4557 
4558   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4559   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4560 }
4561 
4562 // Some RVV intrinsics may claim that they want an integer operand to be
4563 // promoted or expanded.
4564 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4565                                            const RISCVSubtarget &Subtarget) {
4566   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4567           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4568          "Unexpected opcode");
4569 
4570   if (!Subtarget.hasVInstructions())
4571     return SDValue();
4572 
4573   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4574   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4575   SDLoc DL(Op);
4576 
4577   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4578       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4579   if (!II || !II->hasScalarOperand())
4580     return SDValue();
4581 
4582   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4583   assert(SplatOp < Op.getNumOperands());
4584 
4585   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4586   SDValue &ScalarOp = Operands[SplatOp];
4587   MVT OpVT = ScalarOp.getSimpleValueType();
4588   MVT XLenVT = Subtarget.getXLenVT();
4589 
4590   // If this isn't a scalar, or its type is XLenVT we're done.
4591   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4592     return SDValue();
4593 
4594   // Simplest case is that the operand needs to be promoted to XLenVT.
4595   if (OpVT.bitsLT(XLenVT)) {
4596     // If the operand is a constant, sign extend to increase our chances
4597     // of being able to use a .vi instruction. ANY_EXTEND would become a
4598     // a zero extend and the simm5 check in isel would fail.
4599     // FIXME: Should we ignore the upper bits in isel instead?
4600     unsigned ExtOpc =
4601         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4602     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4603     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4604   }
4605 
4606   // Use the previous operand to get the vXi64 VT. The result might be a mask
4607   // VT for compares. Using the previous operand assumes that the previous
4608   // operand will never have a smaller element size than a scalar operand and
4609   // that a widening operation never uses SEW=64.
4610   // NOTE: If this fails the below assert, we can probably just find the
4611   // element count from any operand or result and use it to construct the VT.
4612   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4613   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4614 
4615   // The more complex case is when the scalar is larger than XLenVT.
4616   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4617          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4618 
4619   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4620   // instruction to sign-extend since SEW>XLEN.
4621   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4622     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4623     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4624   }
4625 
4626   switch (IntNo) {
4627   case Intrinsic::riscv_vslide1up:
4628   case Intrinsic::riscv_vslide1down:
4629   case Intrinsic::riscv_vslide1up_mask:
4630   case Intrinsic::riscv_vslide1down_mask: {
4631     // We need to special case these when the scalar is larger than XLen.
4632     unsigned NumOps = Op.getNumOperands();
4633     bool IsMasked = NumOps == 7;
4634 
4635     // Convert the vector source to the equivalent nxvXi32 vector.
4636     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4637     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4638 
4639     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4640                                    DAG.getConstant(0, DL, XLenVT));
4641     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4642                                    DAG.getConstant(1, DL, XLenVT));
4643 
4644     // Double the VL since we halved SEW.
4645     SDValue AVL = getVLOperand(Op);
4646     SDValue I32VL;
4647 
4648     // Optimize for constant AVL
4649     if (isa<ConstantSDNode>(AVL)) {
4650       unsigned EltSize = VT.getScalarSizeInBits();
4651       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4652 
4653       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4654       unsigned MaxVLMAX =
4655           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4656 
4657       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4658       unsigned MinVLMAX =
4659           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4660 
4661       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4662       if (AVLInt <= MinVLMAX) {
4663         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4664       } else if (AVLInt >= 2 * MaxVLMAX) {
4665         // Just set vl to VLMAX in this situation
4666         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4667         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4668         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4669         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4670         SDValue SETVLMAX = DAG.getTargetConstant(
4671             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4672         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4673                             LMUL);
4674       } else {
4675         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4676         // is related to the hardware implementation.
4677         // So let the following code handle
4678       }
4679     }
4680     if (!I32VL) {
4681       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4682       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4683       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4684       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4685       SDValue SETVL =
4686           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4687       // Using vsetvli instruction to get actually used length which related to
4688       // the hardware implementation
4689       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4690                                SEW, LMUL);
4691       I32VL =
4692           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4693     }
4694 
4695     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4696     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4697 
4698     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4699     // instructions.
4700     SDValue Passthru;
4701     if (IsMasked)
4702       Passthru = DAG.getUNDEF(I32VT);
4703     else
4704       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4705 
4706     if (IntNo == Intrinsic::riscv_vslide1up ||
4707         IntNo == Intrinsic::riscv_vslide1up_mask) {
4708       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4709                         ScalarHi, I32Mask, I32VL);
4710       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4711                         ScalarLo, I32Mask, I32VL);
4712     } else {
4713       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4714                         ScalarLo, I32Mask, I32VL);
4715       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4716                         ScalarHi, I32Mask, I32VL);
4717     }
4718 
4719     // Convert back to nxvXi64.
4720     Vec = DAG.getBitcast(VT, Vec);
4721 
4722     if (!IsMasked)
4723       return Vec;
4724     // Apply mask after the operation.
4725     SDValue Mask = Operands[NumOps - 3];
4726     SDValue MaskedOff = Operands[1];
4727     // Assume Policy operand is the last operand.
4728     uint64_t Policy =
4729         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4730     // We don't need to select maskedoff if it's undef.
4731     if (MaskedOff.isUndef())
4732       return Vec;
4733     // TAMU
4734     if (Policy == RISCVII::TAIL_AGNOSTIC)
4735       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4736                          AVL);
4737     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4738     // It's fine because vmerge does not care mask policy.
4739     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4740                        AVL);
4741   }
4742   }
4743 
4744   // We need to convert the scalar to a splat vector.
4745   SDValue VL = getVLOperand(Op);
4746   assert(VL.getValueType() == XLenVT);
4747   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4748   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4749 }
4750 
4751 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4752                                                      SelectionDAG &DAG) const {
4753   unsigned IntNo = Op.getConstantOperandVal(0);
4754   SDLoc DL(Op);
4755   MVT XLenVT = Subtarget.getXLenVT();
4756 
4757   switch (IntNo) {
4758   default:
4759     break; // Don't custom lower most intrinsics.
4760   case Intrinsic::thread_pointer: {
4761     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4762     return DAG.getRegister(RISCV::X4, PtrVT);
4763   }
4764   case Intrinsic::riscv_orc_b:
4765   case Intrinsic::riscv_brev8: {
4766     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4767     unsigned Opc =
4768         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4769     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4770                        DAG.getConstant(7, DL, XLenVT));
4771   }
4772   case Intrinsic::riscv_grev:
4773   case Intrinsic::riscv_gorc: {
4774     unsigned Opc =
4775         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4776     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4777   }
4778   case Intrinsic::riscv_zip:
4779   case Intrinsic::riscv_unzip: {
4780     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4781     // For i32 the immediate is 15. For i64 the immediate is 31.
4782     unsigned Opc =
4783         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4784     unsigned BitWidth = Op.getValueSizeInBits();
4785     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4786     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4787                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4788   }
4789   case Intrinsic::riscv_shfl:
4790   case Intrinsic::riscv_unshfl: {
4791     unsigned Opc =
4792         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4793     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4794   }
4795   case Intrinsic::riscv_bcompress:
4796   case Intrinsic::riscv_bdecompress: {
4797     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4798                                                        : RISCVISD::BDECOMPRESS;
4799     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4800   }
4801   case Intrinsic::riscv_bfp:
4802     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4803                        Op.getOperand(2));
4804   case Intrinsic::riscv_fsl:
4805     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4806                        Op.getOperand(2), Op.getOperand(3));
4807   case Intrinsic::riscv_fsr:
4808     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4809                        Op.getOperand(2), Op.getOperand(3));
4810   case Intrinsic::riscv_vmv_x_s:
4811     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4812     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4813                        Op.getOperand(1));
4814   case Intrinsic::riscv_vmv_v_x:
4815     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4816                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4817                             Subtarget);
4818   case Intrinsic::riscv_vfmv_v_f:
4819     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4820                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4821   case Intrinsic::riscv_vmv_s_x: {
4822     SDValue Scalar = Op.getOperand(2);
4823 
4824     if (Scalar.getValueType().bitsLE(XLenVT)) {
4825       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4826       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4827                          Op.getOperand(1), Scalar, Op.getOperand(3));
4828     }
4829 
4830     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4831 
4832     // This is an i64 value that lives in two scalar registers. We have to
4833     // insert this in a convoluted way. First we build vXi64 splat containing
4834     // the two values that we assemble using some bit math. Next we'll use
4835     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4836     // to merge element 0 from our splat into the source vector.
4837     // FIXME: This is probably not the best way to do this, but it is
4838     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4839     // point.
4840     //   sw lo, (a0)
4841     //   sw hi, 4(a0)
4842     //   vlse vX, (a0)
4843     //
4844     //   vid.v      vVid
4845     //   vmseq.vx   mMask, vVid, 0
4846     //   vmerge.vvm vDest, vSrc, vVal, mMask
4847     MVT VT = Op.getSimpleValueType();
4848     SDValue Vec = Op.getOperand(1);
4849     SDValue VL = getVLOperand(Op);
4850 
4851     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4852     if (Op.getOperand(1).isUndef())
4853       return SplattedVal;
4854     SDValue SplattedIdx =
4855         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4856                     DAG.getConstant(0, DL, MVT::i32), VL);
4857 
4858     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4859     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4860     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4861     SDValue SelectCond =
4862         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4863                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4864     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4865                        Vec, VL);
4866   }
4867   }
4868 
4869   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4870 }
4871 
4872 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4873                                                     SelectionDAG &DAG) const {
4874   unsigned IntNo = Op.getConstantOperandVal(1);
4875   switch (IntNo) {
4876   default:
4877     break;
4878   case Intrinsic::riscv_masked_strided_load: {
4879     SDLoc DL(Op);
4880     MVT XLenVT = Subtarget.getXLenVT();
4881 
4882     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4883     // the selection of the masked intrinsics doesn't do this for us.
4884     SDValue Mask = Op.getOperand(5);
4885     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4886 
4887     MVT VT = Op->getSimpleValueType(0);
4888     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4889 
4890     SDValue PassThru = Op.getOperand(2);
4891     if (!IsUnmasked) {
4892       MVT MaskVT =
4893           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4894       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4895       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4896     }
4897 
4898     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4899 
4900     SDValue IntID = DAG.getTargetConstant(
4901         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4902         XLenVT);
4903 
4904     auto *Load = cast<MemIntrinsicSDNode>(Op);
4905     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4906     if (IsUnmasked)
4907       Ops.push_back(DAG.getUNDEF(ContainerVT));
4908     else
4909       Ops.push_back(PassThru);
4910     Ops.push_back(Op.getOperand(3)); // Ptr
4911     Ops.push_back(Op.getOperand(4)); // Stride
4912     if (!IsUnmasked)
4913       Ops.push_back(Mask);
4914     Ops.push_back(VL);
4915     if (!IsUnmasked) {
4916       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4917       Ops.push_back(Policy);
4918     }
4919 
4920     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4921     SDValue Result =
4922         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4923                                 Load->getMemoryVT(), Load->getMemOperand());
4924     SDValue Chain = Result.getValue(1);
4925     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4926     return DAG.getMergeValues({Result, Chain}, DL);
4927   }
4928   case Intrinsic::riscv_seg2_load:
4929   case Intrinsic::riscv_seg3_load:
4930   case Intrinsic::riscv_seg4_load:
4931   case Intrinsic::riscv_seg5_load:
4932   case Intrinsic::riscv_seg6_load:
4933   case Intrinsic::riscv_seg7_load:
4934   case Intrinsic::riscv_seg8_load: {
4935     SDLoc DL(Op);
4936     static const Intrinsic::ID VlsegInts[7] = {
4937         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4938         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4939         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4940         Intrinsic::riscv_vlseg8};
4941     unsigned NF = Op->getNumValues() - 1;
4942     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4943     MVT XLenVT = Subtarget.getXLenVT();
4944     MVT VT = Op->getSimpleValueType(0);
4945     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4946 
4947     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4948     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4949     auto *Load = cast<MemIntrinsicSDNode>(Op);
4950     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4951     ContainerVTs.push_back(MVT::Other);
4952     SDVTList VTs = DAG.getVTList(ContainerVTs);
4953     SDValue Result =
4954         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4955                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4956                                 Load->getMemoryVT(), Load->getMemOperand());
4957     SmallVector<SDValue, 9> Results;
4958     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4959       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4960                                                   DAG, Subtarget));
4961     Results.push_back(Result.getValue(NF));
4962     return DAG.getMergeValues(Results, DL);
4963   }
4964   }
4965 
4966   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4967 }
4968 
4969 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4970                                                  SelectionDAG &DAG) const {
4971   unsigned IntNo = Op.getConstantOperandVal(1);
4972   switch (IntNo) {
4973   default:
4974     break;
4975   case Intrinsic::riscv_masked_strided_store: {
4976     SDLoc DL(Op);
4977     MVT XLenVT = Subtarget.getXLenVT();
4978 
4979     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4980     // the selection of the masked intrinsics doesn't do this for us.
4981     SDValue Mask = Op.getOperand(5);
4982     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4983 
4984     SDValue Val = Op.getOperand(2);
4985     MVT VT = Val.getSimpleValueType();
4986     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4987 
4988     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4989     if (!IsUnmasked) {
4990       MVT MaskVT =
4991           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4992       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4993     }
4994 
4995     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4996 
4997     SDValue IntID = DAG.getTargetConstant(
4998         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4999         XLenVT);
5000 
5001     auto *Store = cast<MemIntrinsicSDNode>(Op);
5002     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5003     Ops.push_back(Val);
5004     Ops.push_back(Op.getOperand(3)); // Ptr
5005     Ops.push_back(Op.getOperand(4)); // Stride
5006     if (!IsUnmasked)
5007       Ops.push_back(Mask);
5008     Ops.push_back(VL);
5009 
5010     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5011                                    Ops, Store->getMemoryVT(),
5012                                    Store->getMemOperand());
5013   }
5014   }
5015 
5016   return SDValue();
5017 }
5018 
5019 static MVT getLMUL1VT(MVT VT) {
5020   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5021          "Unexpected vector MVT");
5022   return MVT::getScalableVectorVT(
5023       VT.getVectorElementType(),
5024       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5025 }
5026 
5027 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5028   switch (ISDOpcode) {
5029   default:
5030     llvm_unreachable("Unhandled reduction");
5031   case ISD::VECREDUCE_ADD:
5032     return RISCVISD::VECREDUCE_ADD_VL;
5033   case ISD::VECREDUCE_UMAX:
5034     return RISCVISD::VECREDUCE_UMAX_VL;
5035   case ISD::VECREDUCE_SMAX:
5036     return RISCVISD::VECREDUCE_SMAX_VL;
5037   case ISD::VECREDUCE_UMIN:
5038     return RISCVISD::VECREDUCE_UMIN_VL;
5039   case ISD::VECREDUCE_SMIN:
5040     return RISCVISD::VECREDUCE_SMIN_VL;
5041   case ISD::VECREDUCE_AND:
5042     return RISCVISD::VECREDUCE_AND_VL;
5043   case ISD::VECREDUCE_OR:
5044     return RISCVISD::VECREDUCE_OR_VL;
5045   case ISD::VECREDUCE_XOR:
5046     return RISCVISD::VECREDUCE_XOR_VL;
5047   }
5048 }
5049 
5050 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5051                                                          SelectionDAG &DAG,
5052                                                          bool IsVP) const {
5053   SDLoc DL(Op);
5054   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5055   MVT VecVT = Vec.getSimpleValueType();
5056   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5057           Op.getOpcode() == ISD::VECREDUCE_OR ||
5058           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5059           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5060           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5061           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5062          "Unexpected reduction lowering");
5063 
5064   MVT XLenVT = Subtarget.getXLenVT();
5065   assert(Op.getValueType() == XLenVT &&
5066          "Expected reduction output to be legalized to XLenVT");
5067 
5068   MVT ContainerVT = VecVT;
5069   if (VecVT.isFixedLengthVector()) {
5070     ContainerVT = getContainerForFixedLengthVector(VecVT);
5071     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5072   }
5073 
5074   SDValue Mask, VL;
5075   if (IsVP) {
5076     Mask = Op.getOperand(2);
5077     VL = Op.getOperand(3);
5078   } else {
5079     std::tie(Mask, VL) =
5080         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5081   }
5082 
5083   unsigned BaseOpc;
5084   ISD::CondCode CC;
5085   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5086 
5087   switch (Op.getOpcode()) {
5088   default:
5089     llvm_unreachable("Unhandled reduction");
5090   case ISD::VECREDUCE_AND:
5091   case ISD::VP_REDUCE_AND: {
5092     // vcpop ~x == 0
5093     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5094     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5095     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5096     CC = ISD::SETEQ;
5097     BaseOpc = ISD::AND;
5098     break;
5099   }
5100   case ISD::VECREDUCE_OR:
5101   case ISD::VP_REDUCE_OR:
5102     // vcpop x != 0
5103     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5104     CC = ISD::SETNE;
5105     BaseOpc = ISD::OR;
5106     break;
5107   case ISD::VECREDUCE_XOR:
5108   case ISD::VP_REDUCE_XOR: {
5109     // ((vcpop x) & 1) != 0
5110     SDValue One = DAG.getConstant(1, DL, XLenVT);
5111     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5112     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5113     CC = ISD::SETNE;
5114     BaseOpc = ISD::XOR;
5115     break;
5116   }
5117   }
5118 
5119   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5120 
5121   if (!IsVP)
5122     return SetCC;
5123 
5124   // Now include the start value in the operation.
5125   // Note that we must return the start value when no elements are operated
5126   // upon. The vcpop instructions we've emitted in each case above will return
5127   // 0 for an inactive vector, and so we've already received the neutral value:
5128   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5129   // can simply include the start value.
5130   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5131 }
5132 
5133 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5134                                             SelectionDAG &DAG) const {
5135   SDLoc DL(Op);
5136   SDValue Vec = Op.getOperand(0);
5137   EVT VecEVT = Vec.getValueType();
5138 
5139   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5140 
5141   // Due to ordering in legalize types we may have a vector type that needs to
5142   // be split. Do that manually so we can get down to a legal type.
5143   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5144          TargetLowering::TypeSplitVector) {
5145     SDValue Lo, Hi;
5146     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5147     VecEVT = Lo.getValueType();
5148     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5149   }
5150 
5151   // TODO: The type may need to be widened rather than split. Or widened before
5152   // it can be split.
5153   if (!isTypeLegal(VecEVT))
5154     return SDValue();
5155 
5156   MVT VecVT = VecEVT.getSimpleVT();
5157   MVT VecEltVT = VecVT.getVectorElementType();
5158   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5159 
5160   MVT ContainerVT = VecVT;
5161   if (VecVT.isFixedLengthVector()) {
5162     ContainerVT = getContainerForFixedLengthVector(VecVT);
5163     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5164   }
5165 
5166   MVT M1VT = getLMUL1VT(ContainerVT);
5167   MVT XLenVT = Subtarget.getXLenVT();
5168 
5169   SDValue Mask, VL;
5170   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5171 
5172   SDValue NeutralElem =
5173       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5174   SDValue IdentitySplat =
5175       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5176                        M1VT, DL, DAG, Subtarget);
5177   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5178                                   IdentitySplat, Mask, VL);
5179   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5180                              DAG.getConstant(0, DL, XLenVT));
5181   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5182 }
5183 
5184 // Given a reduction op, this function returns the matching reduction opcode,
5185 // the vector SDValue and the scalar SDValue required to lower this to a
5186 // RISCVISD node.
5187 static std::tuple<unsigned, SDValue, SDValue>
5188 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5189   SDLoc DL(Op);
5190   auto Flags = Op->getFlags();
5191   unsigned Opcode = Op.getOpcode();
5192   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5193   switch (Opcode) {
5194   default:
5195     llvm_unreachable("Unhandled reduction");
5196   case ISD::VECREDUCE_FADD: {
5197     // Use positive zero if we can. It is cheaper to materialize.
5198     SDValue Zero =
5199         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5200     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5201   }
5202   case ISD::VECREDUCE_SEQ_FADD:
5203     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5204                            Op.getOperand(0));
5205   case ISD::VECREDUCE_FMIN:
5206     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5207                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5208   case ISD::VECREDUCE_FMAX:
5209     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5210                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5211   }
5212 }
5213 
5214 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5215                                               SelectionDAG &DAG) const {
5216   SDLoc DL(Op);
5217   MVT VecEltVT = Op.getSimpleValueType();
5218 
5219   unsigned RVVOpcode;
5220   SDValue VectorVal, ScalarVal;
5221   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5222       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5223   MVT VecVT = VectorVal.getSimpleValueType();
5224 
5225   MVT ContainerVT = VecVT;
5226   if (VecVT.isFixedLengthVector()) {
5227     ContainerVT = getContainerForFixedLengthVector(VecVT);
5228     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5229   }
5230 
5231   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5232   MVT XLenVT = Subtarget.getXLenVT();
5233 
5234   SDValue Mask, VL;
5235   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5236 
5237   SDValue ScalarSplat =
5238       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5239                        M1VT, DL, DAG, Subtarget);
5240   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5241                                   VectorVal, ScalarSplat, Mask, VL);
5242   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5243                      DAG.getConstant(0, DL, XLenVT));
5244 }
5245 
5246 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5247   switch (ISDOpcode) {
5248   default:
5249     llvm_unreachable("Unhandled reduction");
5250   case ISD::VP_REDUCE_ADD:
5251     return RISCVISD::VECREDUCE_ADD_VL;
5252   case ISD::VP_REDUCE_UMAX:
5253     return RISCVISD::VECREDUCE_UMAX_VL;
5254   case ISD::VP_REDUCE_SMAX:
5255     return RISCVISD::VECREDUCE_SMAX_VL;
5256   case ISD::VP_REDUCE_UMIN:
5257     return RISCVISD::VECREDUCE_UMIN_VL;
5258   case ISD::VP_REDUCE_SMIN:
5259     return RISCVISD::VECREDUCE_SMIN_VL;
5260   case ISD::VP_REDUCE_AND:
5261     return RISCVISD::VECREDUCE_AND_VL;
5262   case ISD::VP_REDUCE_OR:
5263     return RISCVISD::VECREDUCE_OR_VL;
5264   case ISD::VP_REDUCE_XOR:
5265     return RISCVISD::VECREDUCE_XOR_VL;
5266   case ISD::VP_REDUCE_FADD:
5267     return RISCVISD::VECREDUCE_FADD_VL;
5268   case ISD::VP_REDUCE_SEQ_FADD:
5269     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5270   case ISD::VP_REDUCE_FMAX:
5271     return RISCVISD::VECREDUCE_FMAX_VL;
5272   case ISD::VP_REDUCE_FMIN:
5273     return RISCVISD::VECREDUCE_FMIN_VL;
5274   }
5275 }
5276 
5277 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5278                                            SelectionDAG &DAG) const {
5279   SDLoc DL(Op);
5280   SDValue Vec = Op.getOperand(1);
5281   EVT VecEVT = Vec.getValueType();
5282 
5283   // TODO: The type may need to be widened rather than split. Or widened before
5284   // it can be split.
5285   if (!isTypeLegal(VecEVT))
5286     return SDValue();
5287 
5288   MVT VecVT = VecEVT.getSimpleVT();
5289   MVT VecEltVT = VecVT.getVectorElementType();
5290   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5291 
5292   MVT ContainerVT = VecVT;
5293   if (VecVT.isFixedLengthVector()) {
5294     ContainerVT = getContainerForFixedLengthVector(VecVT);
5295     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5296   }
5297 
5298   SDValue VL = Op.getOperand(3);
5299   SDValue Mask = Op.getOperand(2);
5300 
5301   MVT M1VT = getLMUL1VT(ContainerVT);
5302   MVT XLenVT = Subtarget.getXLenVT();
5303   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5304 
5305   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5306                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5307                                         DL, DAG, Subtarget);
5308   SDValue Reduction =
5309       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5310   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5311                              DAG.getConstant(0, DL, XLenVT));
5312   if (!VecVT.isInteger())
5313     return Elt0;
5314   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5315 }
5316 
5317 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5318                                                    SelectionDAG &DAG) const {
5319   SDValue Vec = Op.getOperand(0);
5320   SDValue SubVec = Op.getOperand(1);
5321   MVT VecVT = Vec.getSimpleValueType();
5322   MVT SubVecVT = SubVec.getSimpleValueType();
5323 
5324   SDLoc DL(Op);
5325   MVT XLenVT = Subtarget.getXLenVT();
5326   unsigned OrigIdx = Op.getConstantOperandVal(2);
5327   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5328 
5329   // We don't have the ability to slide mask vectors up indexed by their i1
5330   // elements; the smallest we can do is i8. Often we are able to bitcast to
5331   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5332   // into a scalable one, we might not necessarily have enough scalable
5333   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5334   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5335       (OrigIdx != 0 || !Vec.isUndef())) {
5336     if (VecVT.getVectorMinNumElements() >= 8 &&
5337         SubVecVT.getVectorMinNumElements() >= 8) {
5338       assert(OrigIdx % 8 == 0 && "Invalid index");
5339       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5340              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5341              "Unexpected mask vector lowering");
5342       OrigIdx /= 8;
5343       SubVecVT =
5344           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5345                            SubVecVT.isScalableVector());
5346       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5347                                VecVT.isScalableVector());
5348       Vec = DAG.getBitcast(VecVT, Vec);
5349       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5350     } else {
5351       // We can't slide this mask vector up indexed by its i1 elements.
5352       // This poses a problem when we wish to insert a scalable vector which
5353       // can't be re-expressed as a larger type. Just choose the slow path and
5354       // extend to a larger type, then truncate back down.
5355       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5356       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5357       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5358       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5359       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5360                         Op.getOperand(2));
5361       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5362       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5363     }
5364   }
5365 
5366   // If the subvector vector is a fixed-length type, we cannot use subregister
5367   // manipulation to simplify the codegen; we don't know which register of a
5368   // LMUL group contains the specific subvector as we only know the minimum
5369   // register size. Therefore we must slide the vector group up the full
5370   // amount.
5371   if (SubVecVT.isFixedLengthVector()) {
5372     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5373       return Op;
5374     MVT ContainerVT = VecVT;
5375     if (VecVT.isFixedLengthVector()) {
5376       ContainerVT = getContainerForFixedLengthVector(VecVT);
5377       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5378     }
5379     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5380                          DAG.getUNDEF(ContainerVT), SubVec,
5381                          DAG.getConstant(0, DL, XLenVT));
5382     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5383       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5384       return DAG.getBitcast(Op.getValueType(), SubVec);
5385     }
5386     SDValue Mask =
5387         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5388     // Set the vector length to only the number of elements we care about. Note
5389     // that for slideup this includes the offset.
5390     SDValue VL =
5391         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5392     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5393     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5394                                   SubVec, SlideupAmt, Mask, VL);
5395     if (VecVT.isFixedLengthVector())
5396       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5397     return DAG.getBitcast(Op.getValueType(), Slideup);
5398   }
5399 
5400   unsigned SubRegIdx, RemIdx;
5401   std::tie(SubRegIdx, RemIdx) =
5402       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5403           VecVT, SubVecVT, OrigIdx, TRI);
5404 
5405   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5406   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5407                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5408                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5409 
5410   // 1. If the Idx has been completely eliminated and this subvector's size is
5411   // a vector register or a multiple thereof, or the surrounding elements are
5412   // undef, then this is a subvector insert which naturally aligns to a vector
5413   // register. These can easily be handled using subregister manipulation.
5414   // 2. If the subvector is smaller than a vector register, then the insertion
5415   // must preserve the undisturbed elements of the register. We do this by
5416   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5417   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5418   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5419   // LMUL=1 type back into the larger vector (resolving to another subregister
5420   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5421   // to avoid allocating a large register group to hold our subvector.
5422   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5423     return Op;
5424 
5425   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5426   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5427   // (in our case undisturbed). This means we can set up a subvector insertion
5428   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5429   // size of the subvector.
5430   MVT InterSubVT = VecVT;
5431   SDValue AlignedExtract = Vec;
5432   unsigned AlignedIdx = OrigIdx - RemIdx;
5433   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5434     InterSubVT = getLMUL1VT(VecVT);
5435     // Extract a subvector equal to the nearest full vector register type. This
5436     // should resolve to a EXTRACT_SUBREG instruction.
5437     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5438                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5439   }
5440 
5441   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5442   // For scalable vectors this must be further multiplied by vscale.
5443   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5444 
5445   SDValue Mask, VL;
5446   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5447 
5448   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5449   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5450   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5451   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5452 
5453   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5454                        DAG.getUNDEF(InterSubVT), SubVec,
5455                        DAG.getConstant(0, DL, XLenVT));
5456 
5457   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5458                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5459 
5460   // If required, insert this subvector back into the correct vector register.
5461   // This should resolve to an INSERT_SUBREG instruction.
5462   if (VecVT.bitsGT(InterSubVT))
5463     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5464                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5465 
5466   // We might have bitcast from a mask type: cast back to the original type if
5467   // required.
5468   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5469 }
5470 
5471 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5472                                                     SelectionDAG &DAG) const {
5473   SDValue Vec = Op.getOperand(0);
5474   MVT SubVecVT = Op.getSimpleValueType();
5475   MVT VecVT = Vec.getSimpleValueType();
5476 
5477   SDLoc DL(Op);
5478   MVT XLenVT = Subtarget.getXLenVT();
5479   unsigned OrigIdx = Op.getConstantOperandVal(1);
5480   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5481 
5482   // We don't have the ability to slide mask vectors down indexed by their i1
5483   // elements; the smallest we can do is i8. Often we are able to bitcast to
5484   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5485   // from a scalable one, we might not necessarily have enough scalable
5486   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5487   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5488     if (VecVT.getVectorMinNumElements() >= 8 &&
5489         SubVecVT.getVectorMinNumElements() >= 8) {
5490       assert(OrigIdx % 8 == 0 && "Invalid index");
5491       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5492              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5493              "Unexpected mask vector lowering");
5494       OrigIdx /= 8;
5495       SubVecVT =
5496           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5497                            SubVecVT.isScalableVector());
5498       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5499                                VecVT.isScalableVector());
5500       Vec = DAG.getBitcast(VecVT, Vec);
5501     } else {
5502       // We can't slide this mask vector down, indexed by its i1 elements.
5503       // This poses a problem when we wish to extract a scalable vector which
5504       // can't be re-expressed as a larger type. Just choose the slow path and
5505       // extend to a larger type, then truncate back down.
5506       // TODO: We could probably improve this when extracting certain fixed
5507       // from fixed, where we can extract as i8 and shift the correct element
5508       // right to reach the desired subvector?
5509       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5510       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5511       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5512       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5513                         Op.getOperand(1));
5514       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5515       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5516     }
5517   }
5518 
5519   // If the subvector vector is a fixed-length type, we cannot use subregister
5520   // manipulation to simplify the codegen; we don't know which register of a
5521   // LMUL group contains the specific subvector as we only know the minimum
5522   // register size. Therefore we must slide the vector group down the full
5523   // amount.
5524   if (SubVecVT.isFixedLengthVector()) {
5525     // With an index of 0 this is a cast-like subvector, which can be performed
5526     // with subregister operations.
5527     if (OrigIdx == 0)
5528       return Op;
5529     MVT ContainerVT = VecVT;
5530     if (VecVT.isFixedLengthVector()) {
5531       ContainerVT = getContainerForFixedLengthVector(VecVT);
5532       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5533     }
5534     SDValue Mask =
5535         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5536     // Set the vector length to only the number of elements we care about. This
5537     // avoids sliding down elements we're going to discard straight away.
5538     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5539     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5540     SDValue Slidedown =
5541         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5542                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5543     // Now we can use a cast-like subvector extract to get the result.
5544     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5545                             DAG.getConstant(0, DL, XLenVT));
5546     return DAG.getBitcast(Op.getValueType(), Slidedown);
5547   }
5548 
5549   unsigned SubRegIdx, RemIdx;
5550   std::tie(SubRegIdx, RemIdx) =
5551       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5552           VecVT, SubVecVT, OrigIdx, TRI);
5553 
5554   // If the Idx has been completely eliminated then this is a subvector extract
5555   // which naturally aligns to a vector register. These can easily be handled
5556   // using subregister manipulation.
5557   if (RemIdx == 0)
5558     return Op;
5559 
5560   // Else we must shift our vector register directly to extract the subvector.
5561   // Do this using VSLIDEDOWN.
5562 
5563   // If the vector type is an LMUL-group type, extract a subvector equal to the
5564   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5565   // instruction.
5566   MVT InterSubVT = VecVT;
5567   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5568     InterSubVT = getLMUL1VT(VecVT);
5569     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5570                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5571   }
5572 
5573   // Slide this vector register down by the desired number of elements in order
5574   // to place the desired subvector starting at element 0.
5575   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5576   // For scalable vectors this must be further multiplied by vscale.
5577   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5578 
5579   SDValue Mask, VL;
5580   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5581   SDValue Slidedown =
5582       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5583                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5584 
5585   // Now the vector is in the right position, extract our final subvector. This
5586   // should resolve to a COPY.
5587   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5588                           DAG.getConstant(0, DL, XLenVT));
5589 
5590   // We might have bitcast from a mask type: cast back to the original type if
5591   // required.
5592   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5593 }
5594 
5595 // Lower step_vector to the vid instruction. Any non-identity step value must
5596 // be accounted for my manual expansion.
5597 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5598                                               SelectionDAG &DAG) const {
5599   SDLoc DL(Op);
5600   MVT VT = Op.getSimpleValueType();
5601   MVT XLenVT = Subtarget.getXLenVT();
5602   SDValue Mask, VL;
5603   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5604   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5605   uint64_t StepValImm = Op.getConstantOperandVal(0);
5606   if (StepValImm != 1) {
5607     if (isPowerOf2_64(StepValImm)) {
5608       SDValue StepVal =
5609           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5610                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5611       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5612     } else {
5613       SDValue StepVal = lowerScalarSplat(
5614           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5615           VL, VT, DL, DAG, Subtarget);
5616       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5617     }
5618   }
5619   return StepVec;
5620 }
5621 
5622 // Implement vector_reverse using vrgather.vv with indices determined by
5623 // subtracting the id of each element from (VLMAX-1). This will convert
5624 // the indices like so:
5625 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5626 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5627 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5628                                                  SelectionDAG &DAG) const {
5629   SDLoc DL(Op);
5630   MVT VecVT = Op.getSimpleValueType();
5631   unsigned EltSize = VecVT.getScalarSizeInBits();
5632   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5633 
5634   unsigned MaxVLMAX = 0;
5635   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5636   if (VectorBitsMax != 0)
5637     MaxVLMAX =
5638         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5639 
5640   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5641   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5642 
5643   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5644   // to use vrgatherei16.vv.
5645   // TODO: It's also possible to use vrgatherei16.vv for other types to
5646   // decrease register width for the index calculation.
5647   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5648     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5649     // Reverse each half, then reassemble them in reverse order.
5650     // NOTE: It's also possible that after splitting that VLMAX no longer
5651     // requires vrgatherei16.vv.
5652     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5653       SDValue Lo, Hi;
5654       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5655       EVT LoVT, HiVT;
5656       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5657       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5658       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5659       // Reassemble the low and high pieces reversed.
5660       // FIXME: This is a CONCAT_VECTORS.
5661       SDValue Res =
5662           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5663                       DAG.getIntPtrConstant(0, DL));
5664       return DAG.getNode(
5665           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5666           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5667     }
5668 
5669     // Just promote the int type to i16 which will double the LMUL.
5670     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5671     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5672   }
5673 
5674   MVT XLenVT = Subtarget.getXLenVT();
5675   SDValue Mask, VL;
5676   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5677 
5678   // Calculate VLMAX-1 for the desired SEW.
5679   unsigned MinElts = VecVT.getVectorMinNumElements();
5680   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5681                               DAG.getConstant(MinElts, DL, XLenVT));
5682   SDValue VLMinus1 =
5683       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5684 
5685   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5686   bool IsRV32E64 =
5687       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5688   SDValue SplatVL;
5689   if (!IsRV32E64)
5690     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5691   else
5692     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5693                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5694 
5695   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5696   SDValue Indices =
5697       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5698 
5699   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5700 }
5701 
5702 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5703                                                 SelectionDAG &DAG) const {
5704   SDLoc DL(Op);
5705   SDValue V1 = Op.getOperand(0);
5706   SDValue V2 = Op.getOperand(1);
5707   MVT XLenVT = Subtarget.getXLenVT();
5708   MVT VecVT = Op.getSimpleValueType();
5709 
5710   unsigned MinElts = VecVT.getVectorMinNumElements();
5711   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5712                               DAG.getConstant(MinElts, DL, XLenVT));
5713 
5714   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5715   SDValue DownOffset, UpOffset;
5716   if (ImmValue >= 0) {
5717     // The operand is a TargetConstant, we need to rebuild it as a regular
5718     // constant.
5719     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5720     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5721   } else {
5722     // The operand is a TargetConstant, we need to rebuild it as a regular
5723     // constant rather than negating the original operand.
5724     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5725     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5726   }
5727 
5728   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5729   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5730 
5731   SDValue SlideDown =
5732       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5733                   DownOffset, TrueMask, UpOffset);
5734   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5735                      TrueMask,
5736                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5737 }
5738 
5739 SDValue
5740 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5741                                                      SelectionDAG &DAG) const {
5742   SDLoc DL(Op);
5743   auto *Load = cast<LoadSDNode>(Op);
5744 
5745   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5746                                         Load->getMemoryVT(),
5747                                         *Load->getMemOperand()) &&
5748          "Expecting a correctly-aligned load");
5749 
5750   MVT VT = Op.getSimpleValueType();
5751   MVT XLenVT = Subtarget.getXLenVT();
5752   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5753 
5754   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5755 
5756   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5757   SDValue IntID = DAG.getTargetConstant(
5758       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5759   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5760   if (!IsMaskOp)
5761     Ops.push_back(DAG.getUNDEF(ContainerVT));
5762   Ops.push_back(Load->getBasePtr());
5763   Ops.push_back(VL);
5764   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5765   SDValue NewLoad =
5766       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5767                               Load->getMemoryVT(), Load->getMemOperand());
5768 
5769   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5770   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5771 }
5772 
5773 SDValue
5774 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5775                                                       SelectionDAG &DAG) const {
5776   SDLoc DL(Op);
5777   auto *Store = cast<StoreSDNode>(Op);
5778 
5779   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5780                                         Store->getMemoryVT(),
5781                                         *Store->getMemOperand()) &&
5782          "Expecting a correctly-aligned store");
5783 
5784   SDValue StoreVal = Store->getValue();
5785   MVT VT = StoreVal.getSimpleValueType();
5786   MVT XLenVT = Subtarget.getXLenVT();
5787 
5788   // If the size less than a byte, we need to pad with zeros to make a byte.
5789   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5790     VT = MVT::v8i1;
5791     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5792                            DAG.getConstant(0, DL, VT), StoreVal,
5793                            DAG.getIntPtrConstant(0, DL));
5794   }
5795 
5796   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5797 
5798   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5799 
5800   SDValue NewValue =
5801       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5802 
5803   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5804   SDValue IntID = DAG.getTargetConstant(
5805       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5806   return DAG.getMemIntrinsicNode(
5807       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5808       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5809       Store->getMemoryVT(), Store->getMemOperand());
5810 }
5811 
5812 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5813                                              SelectionDAG &DAG) const {
5814   SDLoc DL(Op);
5815   MVT VT = Op.getSimpleValueType();
5816 
5817   const auto *MemSD = cast<MemSDNode>(Op);
5818   EVT MemVT = MemSD->getMemoryVT();
5819   MachineMemOperand *MMO = MemSD->getMemOperand();
5820   SDValue Chain = MemSD->getChain();
5821   SDValue BasePtr = MemSD->getBasePtr();
5822 
5823   SDValue Mask, PassThru, VL;
5824   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5825     Mask = VPLoad->getMask();
5826     PassThru = DAG.getUNDEF(VT);
5827     VL = VPLoad->getVectorLength();
5828   } else {
5829     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5830     Mask = MLoad->getMask();
5831     PassThru = MLoad->getPassThru();
5832   }
5833 
5834   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5835 
5836   MVT XLenVT = Subtarget.getXLenVT();
5837 
5838   MVT ContainerVT = VT;
5839   if (VT.isFixedLengthVector()) {
5840     ContainerVT = getContainerForFixedLengthVector(VT);
5841     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5842     if (!IsUnmasked) {
5843       MVT MaskVT =
5844           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5845       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5846     }
5847   }
5848 
5849   if (!VL)
5850     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5851 
5852   unsigned IntID =
5853       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5854   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5855   if (IsUnmasked)
5856     Ops.push_back(DAG.getUNDEF(ContainerVT));
5857   else
5858     Ops.push_back(PassThru);
5859   Ops.push_back(BasePtr);
5860   if (!IsUnmasked)
5861     Ops.push_back(Mask);
5862   Ops.push_back(VL);
5863   if (!IsUnmasked)
5864     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5865 
5866   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5867 
5868   SDValue Result =
5869       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5870   Chain = Result.getValue(1);
5871 
5872   if (VT.isFixedLengthVector())
5873     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5874 
5875   return DAG.getMergeValues({Result, Chain}, DL);
5876 }
5877 
5878 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5879                                               SelectionDAG &DAG) const {
5880   SDLoc DL(Op);
5881 
5882   const auto *MemSD = cast<MemSDNode>(Op);
5883   EVT MemVT = MemSD->getMemoryVT();
5884   MachineMemOperand *MMO = MemSD->getMemOperand();
5885   SDValue Chain = MemSD->getChain();
5886   SDValue BasePtr = MemSD->getBasePtr();
5887   SDValue Val, Mask, VL;
5888 
5889   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5890     Val = VPStore->getValue();
5891     Mask = VPStore->getMask();
5892     VL = VPStore->getVectorLength();
5893   } else {
5894     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5895     Val = MStore->getValue();
5896     Mask = MStore->getMask();
5897   }
5898 
5899   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5900 
5901   MVT VT = Val.getSimpleValueType();
5902   MVT XLenVT = Subtarget.getXLenVT();
5903 
5904   MVT ContainerVT = VT;
5905   if (VT.isFixedLengthVector()) {
5906     ContainerVT = getContainerForFixedLengthVector(VT);
5907 
5908     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5909     if (!IsUnmasked) {
5910       MVT MaskVT =
5911           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5912       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5913     }
5914   }
5915 
5916   if (!VL)
5917     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5918 
5919   unsigned IntID =
5920       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5921   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5922   Ops.push_back(Val);
5923   Ops.push_back(BasePtr);
5924   if (!IsUnmasked)
5925     Ops.push_back(Mask);
5926   Ops.push_back(VL);
5927 
5928   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5929                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5930 }
5931 
5932 SDValue
5933 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5934                                                       SelectionDAG &DAG) const {
5935   MVT InVT = Op.getOperand(0).getSimpleValueType();
5936   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5937 
5938   MVT VT = Op.getSimpleValueType();
5939 
5940   SDValue Op1 =
5941       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5942   SDValue Op2 =
5943       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5944 
5945   SDLoc DL(Op);
5946   SDValue VL =
5947       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5948 
5949   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5950   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5951 
5952   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5953                             Op.getOperand(2), Mask, VL);
5954 
5955   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5956 }
5957 
5958 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5959     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5960   MVT VT = Op.getSimpleValueType();
5961 
5962   if (VT.getVectorElementType() == MVT::i1)
5963     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5964 
5965   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5966 }
5967 
5968 SDValue
5969 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5970                                                       SelectionDAG &DAG) const {
5971   unsigned Opc;
5972   switch (Op.getOpcode()) {
5973   default: llvm_unreachable("Unexpected opcode!");
5974   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5975   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5976   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5977   }
5978 
5979   return lowerToScalableOp(Op, DAG, Opc);
5980 }
5981 
5982 // Lower vector ABS to smax(X, sub(0, X)).
5983 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5984   SDLoc DL(Op);
5985   MVT VT = Op.getSimpleValueType();
5986   SDValue X = Op.getOperand(0);
5987 
5988   assert(VT.isFixedLengthVector() && "Unexpected type");
5989 
5990   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5991   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5992 
5993   SDValue Mask, VL;
5994   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5995 
5996   SDValue SplatZero = DAG.getNode(
5997       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5998       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5999   SDValue NegX =
6000       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6001   SDValue Max =
6002       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6003 
6004   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6005 }
6006 
6007 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6008     SDValue Op, SelectionDAG &DAG) const {
6009   SDLoc DL(Op);
6010   MVT VT = Op.getSimpleValueType();
6011   SDValue Mag = Op.getOperand(0);
6012   SDValue Sign = Op.getOperand(1);
6013   assert(Mag.getValueType() == Sign.getValueType() &&
6014          "Can only handle COPYSIGN with matching types.");
6015 
6016   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6017   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6018   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6019 
6020   SDValue Mask, VL;
6021   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6022 
6023   SDValue CopySign =
6024       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6025 
6026   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6027 }
6028 
6029 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6030     SDValue Op, SelectionDAG &DAG) const {
6031   MVT VT = Op.getSimpleValueType();
6032   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6033 
6034   MVT I1ContainerVT =
6035       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6036 
6037   SDValue CC =
6038       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6039   SDValue Op1 =
6040       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6041   SDValue Op2 =
6042       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6043 
6044   SDLoc DL(Op);
6045   SDValue Mask, VL;
6046   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6047 
6048   SDValue Select =
6049       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6050 
6051   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6052 }
6053 
6054 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6055                                                unsigned NewOpc,
6056                                                bool HasMask) const {
6057   MVT VT = Op.getSimpleValueType();
6058   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6059 
6060   // Create list of operands by converting existing ones to scalable types.
6061   SmallVector<SDValue, 6> Ops;
6062   for (const SDValue &V : Op->op_values()) {
6063     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6064 
6065     // Pass through non-vector operands.
6066     if (!V.getValueType().isVector()) {
6067       Ops.push_back(V);
6068       continue;
6069     }
6070 
6071     // "cast" fixed length vector to a scalable vector.
6072     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6073            "Only fixed length vectors are supported!");
6074     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6075   }
6076 
6077   SDLoc DL(Op);
6078   SDValue Mask, VL;
6079   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6080   if (HasMask)
6081     Ops.push_back(Mask);
6082   Ops.push_back(VL);
6083 
6084   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6085   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6086 }
6087 
6088 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6089 // * Operands of each node are assumed to be in the same order.
6090 // * The EVL operand is promoted from i32 to i64 on RV64.
6091 // * Fixed-length vectors are converted to their scalable-vector container
6092 //   types.
6093 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6094                                        unsigned RISCVISDOpc) const {
6095   SDLoc DL(Op);
6096   MVT VT = Op.getSimpleValueType();
6097   SmallVector<SDValue, 4> Ops;
6098 
6099   for (const auto &OpIdx : enumerate(Op->ops())) {
6100     SDValue V = OpIdx.value();
6101     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6102     // Pass through operands which aren't fixed-length vectors.
6103     if (!V.getValueType().isFixedLengthVector()) {
6104       Ops.push_back(V);
6105       continue;
6106     }
6107     // "cast" fixed length vector to a scalable vector.
6108     MVT OpVT = V.getSimpleValueType();
6109     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6110     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6111            "Only fixed length vectors are supported!");
6112     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6113   }
6114 
6115   if (!VT.isFixedLengthVector())
6116     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6117 
6118   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6119 
6120   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6121 
6122   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6123 }
6124 
6125 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6126 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6127                                                 unsigned RISCVISDOpc) const {
6128   SDLoc DL(Op);
6129 
6130   SDValue Src = Op.getOperand(0);
6131   SDValue Mask = Op.getOperand(1);
6132   SDValue VL = Op.getOperand(2);
6133 
6134   MVT DstVT = Op.getSimpleValueType();
6135   MVT SrcVT = Src.getSimpleValueType();
6136   if (DstVT.isFixedLengthVector()) {
6137     DstVT = getContainerForFixedLengthVector(DstVT);
6138     SrcVT = getContainerForFixedLengthVector(SrcVT);
6139     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6140     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6141     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6142   }
6143 
6144   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6145                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6146                                 ? RISCVISD::VSEXT_VL
6147                                 : RISCVISD::VZEXT_VL;
6148 
6149   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6150   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6151 
6152   SDValue Result;
6153   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6154     if (SrcVT.isInteger()) {
6155       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6156 
6157       // Do we need to do any pre-widening before converting?
6158       if (SrcEltSize == 1) {
6159         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6160         MVT XLenVT = Subtarget.getXLenVT();
6161         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6162         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6163                                         DAG.getUNDEF(IntVT), Zero, VL);
6164         SDValue One = DAG.getConstant(
6165             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6166         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6167                                        DAG.getUNDEF(IntVT), One, VL);
6168         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6169                           ZeroSplat, VL);
6170       } else if (DstEltSize > (2 * SrcEltSize)) {
6171         // Widen before converting.
6172         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6173                                      DstVT.getVectorElementCount());
6174         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, {Src, Mask, VL});
6175       }
6176 
6177       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, {Src, Mask, VL});
6178     } else {
6179       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6180              "Wrong input/output vector types");
6181 
6182       // Convert f16 to f32 then convert f32 to i64.
6183       if (DstEltSize > (2 * SrcEltSize)) {
6184         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6185         MVT InterimFVT =
6186             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6187         Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT,
6188                           {Src, Mask, VL});
6189       }
6190 
6191       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, {Src, Mask, VL});
6192     }
6193   } else { // Narrowing + Conversion
6194     if (SrcVT.isInteger()) {
6195       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6196       // First do a narrowing convert to an FP type half the size, then round
6197       // the FP type to a small FP type if needed.
6198 
6199       MVT InterimFVT = DstVT;
6200       if (SrcEltSize > (2 * DstEltSize)) {
6201         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6202         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6203         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6204       }
6205 
6206       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, {Src, Mask, VL});
6207 
6208       if (InterimFVT != DstVT) {
6209         Src = Result;
6210         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, {Src, Mask, VL});
6211       }
6212     } else {
6213       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6214              "Wrong input/output vector types");
6215       // First do a narrowing conversion to an integer half the size, then
6216       // truncate if needed.
6217 
6218       // TODO: Handle mask vectors
6219       assert(DstVT.getVectorElementType() != MVT::i1 &&
6220              "Don't know how to handle masks yet!");
6221       MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6222                                         DstVT.getVectorElementCount());
6223 
6224       Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, {Src, Mask, VL});
6225 
6226       while (InterimIVT != DstVT) {
6227         SrcEltSize /= 2;
6228         Src = Result;
6229         InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6230                                       DstVT.getVectorElementCount());
6231         Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6232                              {Src, Mask, VL});
6233       }
6234     }
6235   }
6236 
6237   MVT VT = Op.getSimpleValueType();
6238   if (!VT.isFixedLengthVector())
6239     return Result;
6240   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6241 }
6242 
6243 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6244                                             unsigned MaskOpc,
6245                                             unsigned VecOpc) const {
6246   MVT VT = Op.getSimpleValueType();
6247   if (VT.getVectorElementType() != MVT::i1)
6248     return lowerVPOp(Op, DAG, VecOpc);
6249 
6250   // It is safe to drop mask parameter as masked-off elements are undef.
6251   SDValue Op1 = Op->getOperand(0);
6252   SDValue Op2 = Op->getOperand(1);
6253   SDValue VL = Op->getOperand(3);
6254 
6255   MVT ContainerVT = VT;
6256   const bool IsFixed = VT.isFixedLengthVector();
6257   if (IsFixed) {
6258     ContainerVT = getContainerForFixedLengthVector(VT);
6259     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6260     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6261   }
6262 
6263   SDLoc DL(Op);
6264   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6265   if (!IsFixed)
6266     return Val;
6267   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6268 }
6269 
6270 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6271 // matched to a RVV indexed load. The RVV indexed load instructions only
6272 // support the "unsigned unscaled" addressing mode; indices are implicitly
6273 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6274 // signed or scaled indexing is extended to the XLEN value type and scaled
6275 // accordingly.
6276 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6277                                                SelectionDAG &DAG) const {
6278   SDLoc DL(Op);
6279   MVT VT = Op.getSimpleValueType();
6280 
6281   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6282   EVT MemVT = MemSD->getMemoryVT();
6283   MachineMemOperand *MMO = MemSD->getMemOperand();
6284   SDValue Chain = MemSD->getChain();
6285   SDValue BasePtr = MemSD->getBasePtr();
6286 
6287   ISD::LoadExtType LoadExtType;
6288   SDValue Index, Mask, PassThru, VL;
6289 
6290   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6291     Index = VPGN->getIndex();
6292     Mask = VPGN->getMask();
6293     PassThru = DAG.getUNDEF(VT);
6294     VL = VPGN->getVectorLength();
6295     // VP doesn't support extending loads.
6296     LoadExtType = ISD::NON_EXTLOAD;
6297   } else {
6298     // Else it must be a MGATHER.
6299     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6300     Index = MGN->getIndex();
6301     Mask = MGN->getMask();
6302     PassThru = MGN->getPassThru();
6303     LoadExtType = MGN->getExtensionType();
6304   }
6305 
6306   MVT IndexVT = Index.getSimpleValueType();
6307   MVT XLenVT = Subtarget.getXLenVT();
6308 
6309   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6310          "Unexpected VTs!");
6311   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6312   // Targets have to explicitly opt-in for extending vector loads.
6313   assert(LoadExtType == ISD::NON_EXTLOAD &&
6314          "Unexpected extending MGATHER/VP_GATHER");
6315   (void)LoadExtType;
6316 
6317   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6318   // the selection of the masked intrinsics doesn't do this for us.
6319   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6320 
6321   MVT ContainerVT = VT;
6322   if (VT.isFixedLengthVector()) {
6323     // We need to use the larger of the result and index type to determine the
6324     // scalable type to use so we don't increase LMUL for any operand/result.
6325     if (VT.bitsGE(IndexVT)) {
6326       ContainerVT = getContainerForFixedLengthVector(VT);
6327       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6328                                  ContainerVT.getVectorElementCount());
6329     } else {
6330       IndexVT = getContainerForFixedLengthVector(IndexVT);
6331       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6332                                      IndexVT.getVectorElementCount());
6333     }
6334 
6335     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6336 
6337     if (!IsUnmasked) {
6338       MVT MaskVT =
6339           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6340       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6341       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6342     }
6343   }
6344 
6345   if (!VL)
6346     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6347 
6348   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6349     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6350     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6351                                    VL);
6352     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6353                         TrueMask, VL);
6354   }
6355 
6356   unsigned IntID =
6357       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6358   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6359   if (IsUnmasked)
6360     Ops.push_back(DAG.getUNDEF(ContainerVT));
6361   else
6362     Ops.push_back(PassThru);
6363   Ops.push_back(BasePtr);
6364   Ops.push_back(Index);
6365   if (!IsUnmasked)
6366     Ops.push_back(Mask);
6367   Ops.push_back(VL);
6368   if (!IsUnmasked)
6369     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6370 
6371   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6372   SDValue Result =
6373       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6374   Chain = Result.getValue(1);
6375 
6376   if (VT.isFixedLengthVector())
6377     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6378 
6379   return DAG.getMergeValues({Result, Chain}, DL);
6380 }
6381 
6382 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6383 // matched to a RVV indexed store. The RVV indexed store instructions only
6384 // support the "unsigned unscaled" addressing mode; indices are implicitly
6385 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6386 // signed or scaled indexing is extended to the XLEN value type and scaled
6387 // accordingly.
6388 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6389                                                 SelectionDAG &DAG) const {
6390   SDLoc DL(Op);
6391   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6392   EVT MemVT = MemSD->getMemoryVT();
6393   MachineMemOperand *MMO = MemSD->getMemOperand();
6394   SDValue Chain = MemSD->getChain();
6395   SDValue BasePtr = MemSD->getBasePtr();
6396 
6397   bool IsTruncatingStore = false;
6398   SDValue Index, Mask, Val, VL;
6399 
6400   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6401     Index = VPSN->getIndex();
6402     Mask = VPSN->getMask();
6403     Val = VPSN->getValue();
6404     VL = VPSN->getVectorLength();
6405     // VP doesn't support truncating stores.
6406     IsTruncatingStore = false;
6407   } else {
6408     // Else it must be a MSCATTER.
6409     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6410     Index = MSN->getIndex();
6411     Mask = MSN->getMask();
6412     Val = MSN->getValue();
6413     IsTruncatingStore = MSN->isTruncatingStore();
6414   }
6415 
6416   MVT VT = Val.getSimpleValueType();
6417   MVT IndexVT = Index.getSimpleValueType();
6418   MVT XLenVT = Subtarget.getXLenVT();
6419 
6420   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6421          "Unexpected VTs!");
6422   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6423   // Targets have to explicitly opt-in for extending vector loads and
6424   // truncating vector stores.
6425   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6426   (void)IsTruncatingStore;
6427 
6428   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6429   // the selection of the masked intrinsics doesn't do this for us.
6430   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6431 
6432   MVT ContainerVT = VT;
6433   if (VT.isFixedLengthVector()) {
6434     // We need to use the larger of the value and index type to determine the
6435     // scalable type to use so we don't increase LMUL for any operand/result.
6436     if (VT.bitsGE(IndexVT)) {
6437       ContainerVT = getContainerForFixedLengthVector(VT);
6438       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6439                                  ContainerVT.getVectorElementCount());
6440     } else {
6441       IndexVT = getContainerForFixedLengthVector(IndexVT);
6442       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6443                                      IndexVT.getVectorElementCount());
6444     }
6445 
6446     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6447     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6448 
6449     if (!IsUnmasked) {
6450       MVT MaskVT =
6451           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6452       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6453     }
6454   }
6455 
6456   if (!VL)
6457     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6458 
6459   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6460     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6461     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6462                                    VL);
6463     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6464                         TrueMask, VL);
6465   }
6466 
6467   unsigned IntID =
6468       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6469   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6470   Ops.push_back(Val);
6471   Ops.push_back(BasePtr);
6472   Ops.push_back(Index);
6473   if (!IsUnmasked)
6474     Ops.push_back(Mask);
6475   Ops.push_back(VL);
6476 
6477   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6478                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6479 }
6480 
6481 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6482                                                SelectionDAG &DAG) const {
6483   const MVT XLenVT = Subtarget.getXLenVT();
6484   SDLoc DL(Op);
6485   SDValue Chain = Op->getOperand(0);
6486   SDValue SysRegNo = DAG.getTargetConstant(
6487       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6488   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6489   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6490 
6491   // Encoding used for rounding mode in RISCV differs from that used in
6492   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6493   // table, which consists of a sequence of 4-bit fields, each representing
6494   // corresponding FLT_ROUNDS mode.
6495   static const int Table =
6496       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6497       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6498       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6499       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6500       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6501 
6502   SDValue Shift =
6503       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6504   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6505                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6506   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6507                                DAG.getConstant(7, DL, XLenVT));
6508 
6509   return DAG.getMergeValues({Masked, Chain}, DL);
6510 }
6511 
6512 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6513                                                SelectionDAG &DAG) const {
6514   const MVT XLenVT = Subtarget.getXLenVT();
6515   SDLoc DL(Op);
6516   SDValue Chain = Op->getOperand(0);
6517   SDValue RMValue = Op->getOperand(1);
6518   SDValue SysRegNo = DAG.getTargetConstant(
6519       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6520 
6521   // Encoding used for rounding mode in RISCV differs from that used in
6522   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6523   // a table, which consists of a sequence of 4-bit fields, each representing
6524   // corresponding RISCV mode.
6525   static const unsigned Table =
6526       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6527       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6528       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6529       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6530       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6531 
6532   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6533                               DAG.getConstant(2, DL, XLenVT));
6534   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6535                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6536   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6537                         DAG.getConstant(0x7, DL, XLenVT));
6538   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6539                      RMValue);
6540 }
6541 
6542 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6543   switch (IntNo) {
6544   default:
6545     llvm_unreachable("Unexpected Intrinsic");
6546   case Intrinsic::riscv_bcompress:
6547     return RISCVISD::BCOMPRESSW;
6548   case Intrinsic::riscv_bdecompress:
6549     return RISCVISD::BDECOMPRESSW;
6550   case Intrinsic::riscv_bfp:
6551     return RISCVISD::BFPW;
6552   case Intrinsic::riscv_fsl:
6553     return RISCVISD::FSLW;
6554   case Intrinsic::riscv_fsr:
6555     return RISCVISD::FSRW;
6556   }
6557 }
6558 
6559 // Converts the given intrinsic to a i64 operation with any extension.
6560 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6561                                          unsigned IntNo) {
6562   SDLoc DL(N);
6563   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6564   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6565   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6566   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6567   // ReplaceNodeResults requires we maintain the same type for the return value.
6568   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6569 }
6570 
6571 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6572 // form of the given Opcode.
6573 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6574   switch (Opcode) {
6575   default:
6576     llvm_unreachable("Unexpected opcode");
6577   case ISD::SHL:
6578     return RISCVISD::SLLW;
6579   case ISD::SRA:
6580     return RISCVISD::SRAW;
6581   case ISD::SRL:
6582     return RISCVISD::SRLW;
6583   case ISD::SDIV:
6584     return RISCVISD::DIVW;
6585   case ISD::UDIV:
6586     return RISCVISD::DIVUW;
6587   case ISD::UREM:
6588     return RISCVISD::REMUW;
6589   case ISD::ROTL:
6590     return RISCVISD::ROLW;
6591   case ISD::ROTR:
6592     return RISCVISD::RORW;
6593   }
6594 }
6595 
6596 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6597 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6598 // otherwise be promoted to i64, making it difficult to select the
6599 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6600 // type i8/i16/i32 is lost.
6601 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6602                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6603   SDLoc DL(N);
6604   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6605   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6606   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6607   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6608   // ReplaceNodeResults requires we maintain the same type for the return value.
6609   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6610 }
6611 
6612 // Converts the given 32-bit operation to a i64 operation with signed extension
6613 // semantic to reduce the signed extension instructions.
6614 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6615   SDLoc DL(N);
6616   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6617   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6618   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6619   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6620                                DAG.getValueType(MVT::i32));
6621   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6622 }
6623 
6624 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6625                                              SmallVectorImpl<SDValue> &Results,
6626                                              SelectionDAG &DAG) const {
6627   SDLoc DL(N);
6628   switch (N->getOpcode()) {
6629   default:
6630     llvm_unreachable("Don't know how to custom type legalize this operation!");
6631   case ISD::STRICT_FP_TO_SINT:
6632   case ISD::STRICT_FP_TO_UINT:
6633   case ISD::FP_TO_SINT:
6634   case ISD::FP_TO_UINT: {
6635     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6636            "Unexpected custom legalisation");
6637     bool IsStrict = N->isStrictFPOpcode();
6638     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6639                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6640     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6641     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6642         TargetLowering::TypeSoftenFloat) {
6643       if (!isTypeLegal(Op0.getValueType()))
6644         return;
6645       if (IsStrict) {
6646         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6647                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6648         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6649         SDValue Res = DAG.getNode(
6650             Opc, DL, VTs, N->getOperand(0), Op0,
6651             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6652         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6653         Results.push_back(Res.getValue(1));
6654         return;
6655       }
6656       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6657       SDValue Res =
6658           DAG.getNode(Opc, DL, MVT::i64, Op0,
6659                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6660       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6661       return;
6662     }
6663     // If the FP type needs to be softened, emit a library call using the 'si'
6664     // version. If we left it to default legalization we'd end up with 'di'. If
6665     // the FP type doesn't need to be softened just let generic type
6666     // legalization promote the result type.
6667     RTLIB::Libcall LC;
6668     if (IsSigned)
6669       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6670     else
6671       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6672     MakeLibCallOptions CallOptions;
6673     EVT OpVT = Op0.getValueType();
6674     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6675     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6676     SDValue Result;
6677     std::tie(Result, Chain) =
6678         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6679     Results.push_back(Result);
6680     if (IsStrict)
6681       Results.push_back(Chain);
6682     break;
6683   }
6684   case ISD::READCYCLECOUNTER: {
6685     assert(!Subtarget.is64Bit() &&
6686            "READCYCLECOUNTER only has custom type legalization on riscv32");
6687 
6688     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6689     SDValue RCW =
6690         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6691 
6692     Results.push_back(
6693         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6694     Results.push_back(RCW.getValue(2));
6695     break;
6696   }
6697   case ISD::MUL: {
6698     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6699     unsigned XLen = Subtarget.getXLen();
6700     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6701     if (Size > XLen) {
6702       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6703       SDValue LHS = N->getOperand(0);
6704       SDValue RHS = N->getOperand(1);
6705       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6706 
6707       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6708       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6709       // We need exactly one side to be unsigned.
6710       if (LHSIsU == RHSIsU)
6711         return;
6712 
6713       auto MakeMULPair = [&](SDValue S, SDValue U) {
6714         MVT XLenVT = Subtarget.getXLenVT();
6715         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6716         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6717         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6718         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6719         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6720       };
6721 
6722       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6723       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6724 
6725       // The other operand should be signed, but still prefer MULH when
6726       // possible.
6727       if (RHSIsU && LHSIsS && !RHSIsS)
6728         Results.push_back(MakeMULPair(LHS, RHS));
6729       else if (LHSIsU && RHSIsS && !LHSIsS)
6730         Results.push_back(MakeMULPair(RHS, LHS));
6731 
6732       return;
6733     }
6734     LLVM_FALLTHROUGH;
6735   }
6736   case ISD::ADD:
6737   case ISD::SUB:
6738     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6739            "Unexpected custom legalisation");
6740     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6741     break;
6742   case ISD::SHL:
6743   case ISD::SRA:
6744   case ISD::SRL:
6745     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6746            "Unexpected custom legalisation");
6747     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6748       Results.push_back(customLegalizeToWOp(N, DAG));
6749       break;
6750     }
6751 
6752     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6753     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6754     // shift amount.
6755     if (N->getOpcode() == ISD::SHL) {
6756       SDLoc DL(N);
6757       SDValue NewOp0 =
6758           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6759       SDValue NewOp1 =
6760           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6761       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6762       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6763                                    DAG.getValueType(MVT::i32));
6764       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6765     }
6766 
6767     break;
6768   case ISD::ROTL:
6769   case ISD::ROTR:
6770     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6771            "Unexpected custom legalisation");
6772     Results.push_back(customLegalizeToWOp(N, DAG));
6773     break;
6774   case ISD::CTTZ:
6775   case ISD::CTTZ_ZERO_UNDEF:
6776   case ISD::CTLZ:
6777   case ISD::CTLZ_ZERO_UNDEF: {
6778     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6779            "Unexpected custom legalisation");
6780 
6781     SDValue NewOp0 =
6782         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6783     bool IsCTZ =
6784         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6785     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6786     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6787     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6788     return;
6789   }
6790   case ISD::SDIV:
6791   case ISD::UDIV:
6792   case ISD::UREM: {
6793     MVT VT = N->getSimpleValueType(0);
6794     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6795            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6796            "Unexpected custom legalisation");
6797     // Don't promote division/remainder by constant since we should expand those
6798     // to multiply by magic constant.
6799     // FIXME: What if the expansion is disabled for minsize.
6800     if (N->getOperand(1).getOpcode() == ISD::Constant)
6801       return;
6802 
6803     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6804     // the upper 32 bits. For other types we need to sign or zero extend
6805     // based on the opcode.
6806     unsigned ExtOpc = ISD::ANY_EXTEND;
6807     if (VT != MVT::i32)
6808       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6809                                            : ISD::ZERO_EXTEND;
6810 
6811     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6812     break;
6813   }
6814   case ISD::UADDO:
6815   case ISD::USUBO: {
6816     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6817            "Unexpected custom legalisation");
6818     bool IsAdd = N->getOpcode() == ISD::UADDO;
6819     // Create an ADDW or SUBW.
6820     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6821     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6822     SDValue Res =
6823         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6824     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6825                       DAG.getValueType(MVT::i32));
6826 
6827     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6828     // Since the inputs are sign extended from i32, this is equivalent to
6829     // comparing the lower 32 bits.
6830     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6831     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6832                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6833 
6834     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6835     Results.push_back(Overflow);
6836     return;
6837   }
6838   case ISD::UADDSAT:
6839   case ISD::USUBSAT: {
6840     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6841            "Unexpected custom legalisation");
6842     if (Subtarget.hasStdExtZbb()) {
6843       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6844       // sign extend allows overflow of the lower 32 bits to be detected on
6845       // the promoted size.
6846       SDValue LHS =
6847           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6848       SDValue RHS =
6849           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6850       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6851       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6852       return;
6853     }
6854 
6855     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6856     // promotion for UADDO/USUBO.
6857     Results.push_back(expandAddSubSat(N, DAG));
6858     return;
6859   }
6860   case ISD::ABS: {
6861     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6862            "Unexpected custom legalisation");
6863           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6864 
6865     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6866 
6867     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6868 
6869     // Freeze the source so we can increase it's use count.
6870     Src = DAG.getFreeze(Src);
6871 
6872     // Copy sign bit to all bits using the sraiw pattern.
6873     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6874                                    DAG.getValueType(MVT::i32));
6875     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6876                            DAG.getConstant(31, DL, MVT::i64));
6877 
6878     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6879     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6880 
6881     // NOTE: The result is only required to be anyextended, but sext is
6882     // consistent with type legalization of sub.
6883     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6884                          DAG.getValueType(MVT::i32));
6885     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6886     return;
6887   }
6888   case ISD::BITCAST: {
6889     EVT VT = N->getValueType(0);
6890     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6891     SDValue Op0 = N->getOperand(0);
6892     EVT Op0VT = Op0.getValueType();
6893     MVT XLenVT = Subtarget.getXLenVT();
6894     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6895       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6896       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6897     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6898                Subtarget.hasStdExtF()) {
6899       SDValue FPConv =
6900           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6901       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6902     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6903                isTypeLegal(Op0VT)) {
6904       // Custom-legalize bitcasts from fixed-length vector types to illegal
6905       // scalar types in order to improve codegen. Bitcast the vector to a
6906       // one-element vector type whose element type is the same as the result
6907       // type, and extract the first element.
6908       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6909       if (isTypeLegal(BVT)) {
6910         SDValue BVec = DAG.getBitcast(BVT, Op0);
6911         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6912                                       DAG.getConstant(0, DL, XLenVT)));
6913       }
6914     }
6915     break;
6916   }
6917   case RISCVISD::GREV:
6918   case RISCVISD::GORC:
6919   case RISCVISD::SHFL: {
6920     MVT VT = N->getSimpleValueType(0);
6921     MVT XLenVT = Subtarget.getXLenVT();
6922     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
6923            "Unexpected custom legalisation");
6924     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6925     assert((Subtarget.hasStdExtZbp() ||
6926             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
6927              N->getConstantOperandVal(1) == 7)) &&
6928            "Unexpected extension");
6929     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6930     SDValue NewOp1 =
6931         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
6932     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
6933     // ReplaceNodeResults requires we maintain the same type for the return
6934     // value.
6935     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
6936     break;
6937   }
6938   case ISD::BSWAP:
6939   case ISD::BITREVERSE: {
6940     MVT VT = N->getSimpleValueType(0);
6941     MVT XLenVT = Subtarget.getXLenVT();
6942     assert((VT == MVT::i8 || VT == MVT::i16 ||
6943             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6944            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6945     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6946     unsigned Imm = VT.getSizeInBits() - 1;
6947     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6948     if (N->getOpcode() == ISD::BSWAP)
6949       Imm &= ~0x7U;
6950     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
6951                                 DAG.getConstant(Imm, DL, XLenVT));
6952     // ReplaceNodeResults requires we maintain the same type for the return
6953     // value.
6954     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6955     break;
6956   }
6957   case ISD::FSHL:
6958   case ISD::FSHR: {
6959     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6960            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6961     SDValue NewOp0 =
6962         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6963     SDValue NewOp1 =
6964         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6965     SDValue NewShAmt =
6966         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6967     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6968     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6969     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6970                            DAG.getConstant(0x1f, DL, MVT::i64));
6971     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6972     // instruction use different orders. fshl will return its first operand for
6973     // shift of zero, fshr will return its second operand. fsl and fsr both
6974     // return rs1 so the ISD nodes need to have different operand orders.
6975     // Shift amount is in rs2.
6976     unsigned Opc = RISCVISD::FSLW;
6977     if (N->getOpcode() == ISD::FSHR) {
6978       std::swap(NewOp0, NewOp1);
6979       Opc = RISCVISD::FSRW;
6980     }
6981     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6982     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6983     break;
6984   }
6985   case ISD::EXTRACT_VECTOR_ELT: {
6986     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6987     // type is illegal (currently only vXi64 RV32).
6988     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6989     // transferred to the destination register. We issue two of these from the
6990     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6991     // first element.
6992     SDValue Vec = N->getOperand(0);
6993     SDValue Idx = N->getOperand(1);
6994 
6995     // The vector type hasn't been legalized yet so we can't issue target
6996     // specific nodes if it needs legalization.
6997     // FIXME: We would manually legalize if it's important.
6998     if (!isTypeLegal(Vec.getValueType()))
6999       return;
7000 
7001     MVT VecVT = Vec.getSimpleValueType();
7002 
7003     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7004            VecVT.getVectorElementType() == MVT::i64 &&
7005            "Unexpected EXTRACT_VECTOR_ELT legalization");
7006 
7007     // If this is a fixed vector, we need to convert it to a scalable vector.
7008     MVT ContainerVT = VecVT;
7009     if (VecVT.isFixedLengthVector()) {
7010       ContainerVT = getContainerForFixedLengthVector(VecVT);
7011       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7012     }
7013 
7014     MVT XLenVT = Subtarget.getXLenVT();
7015 
7016     // Use a VL of 1 to avoid processing more elements than we need.
7017     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7018     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7019     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7020 
7021     // Unless the index is known to be 0, we must slide the vector down to get
7022     // the desired element into index 0.
7023     if (!isNullConstant(Idx)) {
7024       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7025                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7026     }
7027 
7028     // Extract the lower XLEN bits of the correct vector element.
7029     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7030 
7031     // To extract the upper XLEN bits of the vector element, shift the first
7032     // element right by 32 bits and re-extract the lower XLEN bits.
7033     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7034                                      DAG.getUNDEF(ContainerVT),
7035                                      DAG.getConstant(32, DL, XLenVT), VL);
7036     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7037                                  ThirtyTwoV, Mask, VL);
7038 
7039     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7040 
7041     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7042     break;
7043   }
7044   case ISD::INTRINSIC_WO_CHAIN: {
7045     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7046     switch (IntNo) {
7047     default:
7048       llvm_unreachable(
7049           "Don't know how to custom type legalize this intrinsic!");
7050     case Intrinsic::riscv_grev:
7051     case Intrinsic::riscv_gorc: {
7052       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7053              "Unexpected custom legalisation");
7054       SDValue NewOp1 =
7055           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7056       SDValue NewOp2 =
7057           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7058       unsigned Opc =
7059           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7060       // If the control is a constant, promote the node by clearing any extra
7061       // bits bits in the control. isel will form greviw/gorciw if the result is
7062       // sign extended.
7063       if (isa<ConstantSDNode>(NewOp2)) {
7064         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7065                              DAG.getConstant(0x1f, DL, MVT::i64));
7066         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7067       }
7068       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7069       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7070       break;
7071     }
7072     case Intrinsic::riscv_bcompress:
7073     case Intrinsic::riscv_bdecompress:
7074     case Intrinsic::riscv_bfp: {
7075       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7076              "Unexpected custom legalisation");
7077       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7078       break;
7079     }
7080     case Intrinsic::riscv_fsl:
7081     case Intrinsic::riscv_fsr: {
7082       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7083              "Unexpected custom legalisation");
7084       SDValue NewOp1 =
7085           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7086       SDValue NewOp2 =
7087           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7088       SDValue NewOp3 =
7089           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
7090       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
7091       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
7092       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7093       break;
7094     }
7095     case Intrinsic::riscv_orc_b: {
7096       // Lower to the GORCI encoding for orc.b with the operand extended.
7097       SDValue NewOp =
7098           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7099       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7100                                 DAG.getConstant(7, DL, MVT::i64));
7101       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7102       return;
7103     }
7104     case Intrinsic::riscv_shfl:
7105     case Intrinsic::riscv_unshfl: {
7106       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7107              "Unexpected custom legalisation");
7108       SDValue NewOp1 =
7109           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7110       SDValue NewOp2 =
7111           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7112       unsigned Opc =
7113           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7114       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7115       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7116       // will be shuffled the same way as the lower 32 bit half, but the two
7117       // halves won't cross.
7118       if (isa<ConstantSDNode>(NewOp2)) {
7119         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7120                              DAG.getConstant(0xf, DL, MVT::i64));
7121         Opc =
7122             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7123       }
7124       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7125       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7126       break;
7127     }
7128     case Intrinsic::riscv_vmv_x_s: {
7129       EVT VT = N->getValueType(0);
7130       MVT XLenVT = Subtarget.getXLenVT();
7131       if (VT.bitsLT(XLenVT)) {
7132         // Simple case just extract using vmv.x.s and truncate.
7133         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7134                                       Subtarget.getXLenVT(), N->getOperand(1));
7135         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7136         return;
7137       }
7138 
7139       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7140              "Unexpected custom legalization");
7141 
7142       // We need to do the move in two steps.
7143       SDValue Vec = N->getOperand(1);
7144       MVT VecVT = Vec.getSimpleValueType();
7145 
7146       // First extract the lower XLEN bits of the element.
7147       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7148 
7149       // To extract the upper XLEN bits of the vector element, shift the first
7150       // element right by 32 bits and re-extract the lower XLEN bits.
7151       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7152       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7153       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7154       SDValue ThirtyTwoV =
7155           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7156                       DAG.getConstant(32, DL, XLenVT), VL);
7157       SDValue LShr32 =
7158           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7159       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7160 
7161       Results.push_back(
7162           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7163       break;
7164     }
7165     }
7166     break;
7167   }
7168   case ISD::VECREDUCE_ADD:
7169   case ISD::VECREDUCE_AND:
7170   case ISD::VECREDUCE_OR:
7171   case ISD::VECREDUCE_XOR:
7172   case ISD::VECREDUCE_SMAX:
7173   case ISD::VECREDUCE_UMAX:
7174   case ISD::VECREDUCE_SMIN:
7175   case ISD::VECREDUCE_UMIN:
7176     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7177       Results.push_back(V);
7178     break;
7179   case ISD::VP_REDUCE_ADD:
7180   case ISD::VP_REDUCE_AND:
7181   case ISD::VP_REDUCE_OR:
7182   case ISD::VP_REDUCE_XOR:
7183   case ISD::VP_REDUCE_SMAX:
7184   case ISD::VP_REDUCE_UMAX:
7185   case ISD::VP_REDUCE_SMIN:
7186   case ISD::VP_REDUCE_UMIN:
7187     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7188       Results.push_back(V);
7189     break;
7190   case ISD::FLT_ROUNDS_: {
7191     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7192     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7193     Results.push_back(Res.getValue(0));
7194     Results.push_back(Res.getValue(1));
7195     break;
7196   }
7197   }
7198 }
7199 
7200 // A structure to hold one of the bit-manipulation patterns below. Together, a
7201 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7202 //   (or (and (shl x, 1), 0xAAAAAAAA),
7203 //       (and (srl x, 1), 0x55555555))
7204 struct RISCVBitmanipPat {
7205   SDValue Op;
7206   unsigned ShAmt;
7207   bool IsSHL;
7208 
7209   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7210     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7211   }
7212 };
7213 
7214 // Matches patterns of the form
7215 //   (and (shl x, C2), (C1 << C2))
7216 //   (and (srl x, C2), C1)
7217 //   (shl (and x, C1), C2)
7218 //   (srl (and x, (C1 << C2)), C2)
7219 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7220 // The expected masks for each shift amount are specified in BitmanipMasks where
7221 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7222 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7223 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7224 // XLen is 64.
7225 static Optional<RISCVBitmanipPat>
7226 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7227   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7228          "Unexpected number of masks");
7229   Optional<uint64_t> Mask;
7230   // Optionally consume a mask around the shift operation.
7231   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7232     Mask = Op.getConstantOperandVal(1);
7233     Op = Op.getOperand(0);
7234   }
7235   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7236     return None;
7237   bool IsSHL = Op.getOpcode() == ISD::SHL;
7238 
7239   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7240     return None;
7241   uint64_t ShAmt = Op.getConstantOperandVal(1);
7242 
7243   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7244   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7245     return None;
7246   // If we don't have enough masks for 64 bit, then we must be trying to
7247   // match SHFL so we're only allowed to shift 1/4 of the width.
7248   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7249     return None;
7250 
7251   SDValue Src = Op.getOperand(0);
7252 
7253   // The expected mask is shifted left when the AND is found around SHL
7254   // patterns.
7255   //   ((x >> 1) & 0x55555555)
7256   //   ((x << 1) & 0xAAAAAAAA)
7257   bool SHLExpMask = IsSHL;
7258 
7259   if (!Mask) {
7260     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7261     // the mask is all ones: consume that now.
7262     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7263       Mask = Src.getConstantOperandVal(1);
7264       Src = Src.getOperand(0);
7265       // The expected mask is now in fact shifted left for SRL, so reverse the
7266       // decision.
7267       //   ((x & 0xAAAAAAAA) >> 1)
7268       //   ((x & 0x55555555) << 1)
7269       SHLExpMask = !SHLExpMask;
7270     } else {
7271       // Use a default shifted mask of all-ones if there's no AND, truncated
7272       // down to the expected width. This simplifies the logic later on.
7273       Mask = maskTrailingOnes<uint64_t>(Width);
7274       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7275     }
7276   }
7277 
7278   unsigned MaskIdx = Log2_32(ShAmt);
7279   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7280 
7281   if (SHLExpMask)
7282     ExpMask <<= ShAmt;
7283 
7284   if (Mask != ExpMask)
7285     return None;
7286 
7287   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7288 }
7289 
7290 // Matches any of the following bit-manipulation patterns:
7291 //   (and (shl x, 1), (0x55555555 << 1))
7292 //   (and (srl x, 1), 0x55555555)
7293 //   (shl (and x, 0x55555555), 1)
7294 //   (srl (and x, (0x55555555 << 1)), 1)
7295 // where the shift amount and mask may vary thus:
7296 //   [1]  = 0x55555555 / 0xAAAAAAAA
7297 //   [2]  = 0x33333333 / 0xCCCCCCCC
7298 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7299 //   [8]  = 0x00FF00FF / 0xFF00FF00
7300 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7301 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7302 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7303   // These are the unshifted masks which we use to match bit-manipulation
7304   // patterns. They may be shifted left in certain circumstances.
7305   static const uint64_t BitmanipMasks[] = {
7306       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7307       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7308 
7309   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7310 }
7311 
7312 // Match the following pattern as a GREVI(W) operation
7313 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7314 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7315                                const RISCVSubtarget &Subtarget) {
7316   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7317   EVT VT = Op.getValueType();
7318 
7319   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7320     auto LHS = matchGREVIPat(Op.getOperand(0));
7321     auto RHS = matchGREVIPat(Op.getOperand(1));
7322     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7323       SDLoc DL(Op);
7324       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7325                          DAG.getConstant(LHS->ShAmt, DL, VT));
7326     }
7327   }
7328   return SDValue();
7329 }
7330 
7331 // Matches any the following pattern as a GORCI(W) operation
7332 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7333 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7334 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7335 // Note that with the variant of 3.,
7336 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7337 // the inner pattern will first be matched as GREVI and then the outer
7338 // pattern will be matched to GORC via the first rule above.
7339 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7340 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7341                                const RISCVSubtarget &Subtarget) {
7342   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7343   EVT VT = Op.getValueType();
7344 
7345   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7346     SDLoc DL(Op);
7347     SDValue Op0 = Op.getOperand(0);
7348     SDValue Op1 = Op.getOperand(1);
7349 
7350     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7351       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7352           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7353           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7354         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7355       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7356       if ((Reverse.getOpcode() == ISD::ROTL ||
7357            Reverse.getOpcode() == ISD::ROTR) &&
7358           Reverse.getOperand(0) == X &&
7359           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7360         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7361         if (RotAmt == (VT.getSizeInBits() / 2))
7362           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7363                              DAG.getConstant(RotAmt, DL, VT));
7364       }
7365       return SDValue();
7366     };
7367 
7368     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7369     if (SDValue V = MatchOROfReverse(Op0, Op1))
7370       return V;
7371     if (SDValue V = MatchOROfReverse(Op1, Op0))
7372       return V;
7373 
7374     // OR is commutable so canonicalize its OR operand to the left
7375     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7376       std::swap(Op0, Op1);
7377     if (Op0.getOpcode() != ISD::OR)
7378       return SDValue();
7379     SDValue OrOp0 = Op0.getOperand(0);
7380     SDValue OrOp1 = Op0.getOperand(1);
7381     auto LHS = matchGREVIPat(OrOp0);
7382     // OR is commutable so swap the operands and try again: x might have been
7383     // on the left
7384     if (!LHS) {
7385       std::swap(OrOp0, OrOp1);
7386       LHS = matchGREVIPat(OrOp0);
7387     }
7388     auto RHS = matchGREVIPat(Op1);
7389     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7390       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7391                          DAG.getConstant(LHS->ShAmt, DL, VT));
7392     }
7393   }
7394   return SDValue();
7395 }
7396 
7397 // Matches any of the following bit-manipulation patterns:
7398 //   (and (shl x, 1), (0x22222222 << 1))
7399 //   (and (srl x, 1), 0x22222222)
7400 //   (shl (and x, 0x22222222), 1)
7401 //   (srl (and x, (0x22222222 << 1)), 1)
7402 // where the shift amount and mask may vary thus:
7403 //   [1]  = 0x22222222 / 0x44444444
7404 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7405 //   [4]  = 0x00F000F0 / 0x0F000F00
7406 //   [8]  = 0x0000FF00 / 0x00FF0000
7407 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7408 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7409   // These are the unshifted masks which we use to match bit-manipulation
7410   // patterns. They may be shifted left in certain circumstances.
7411   static const uint64_t BitmanipMasks[] = {
7412       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7413       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7414 
7415   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7416 }
7417 
7418 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7419 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7420                                const RISCVSubtarget &Subtarget) {
7421   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7422   EVT VT = Op.getValueType();
7423 
7424   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7425     return SDValue();
7426 
7427   SDValue Op0 = Op.getOperand(0);
7428   SDValue Op1 = Op.getOperand(1);
7429 
7430   // Or is commutable so canonicalize the second OR to the LHS.
7431   if (Op0.getOpcode() != ISD::OR)
7432     std::swap(Op0, Op1);
7433   if (Op0.getOpcode() != ISD::OR)
7434     return SDValue();
7435 
7436   // We found an inner OR, so our operands are the operands of the inner OR
7437   // and the other operand of the outer OR.
7438   SDValue A = Op0.getOperand(0);
7439   SDValue B = Op0.getOperand(1);
7440   SDValue C = Op1;
7441 
7442   auto Match1 = matchSHFLPat(A);
7443   auto Match2 = matchSHFLPat(B);
7444 
7445   // If neither matched, we failed.
7446   if (!Match1 && !Match2)
7447     return SDValue();
7448 
7449   // We had at least one match. if one failed, try the remaining C operand.
7450   if (!Match1) {
7451     std::swap(A, C);
7452     Match1 = matchSHFLPat(A);
7453     if (!Match1)
7454       return SDValue();
7455   } else if (!Match2) {
7456     std::swap(B, C);
7457     Match2 = matchSHFLPat(B);
7458     if (!Match2)
7459       return SDValue();
7460   }
7461   assert(Match1 && Match2);
7462 
7463   // Make sure our matches pair up.
7464   if (!Match1->formsPairWith(*Match2))
7465     return SDValue();
7466 
7467   // All the remains is to make sure C is an AND with the same input, that masks
7468   // out the bits that are being shuffled.
7469   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7470       C.getOperand(0) != Match1->Op)
7471     return SDValue();
7472 
7473   uint64_t Mask = C.getConstantOperandVal(1);
7474 
7475   static const uint64_t BitmanipMasks[] = {
7476       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7477       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7478   };
7479 
7480   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7481   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7482   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7483 
7484   if (Mask != ExpMask)
7485     return SDValue();
7486 
7487   SDLoc DL(Op);
7488   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7489                      DAG.getConstant(Match1->ShAmt, DL, VT));
7490 }
7491 
7492 // Optimize (add (shl x, c0), (shl y, c1)) ->
7493 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7494 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7495                                   const RISCVSubtarget &Subtarget) {
7496   // Perform this optimization only in the zba extension.
7497   if (!Subtarget.hasStdExtZba())
7498     return SDValue();
7499 
7500   // Skip for vector types and larger types.
7501   EVT VT = N->getValueType(0);
7502   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7503     return SDValue();
7504 
7505   // The two operand nodes must be SHL and have no other use.
7506   SDValue N0 = N->getOperand(0);
7507   SDValue N1 = N->getOperand(1);
7508   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7509       !N0->hasOneUse() || !N1->hasOneUse())
7510     return SDValue();
7511 
7512   // Check c0 and c1.
7513   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7514   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7515   if (!N0C || !N1C)
7516     return SDValue();
7517   int64_t C0 = N0C->getSExtValue();
7518   int64_t C1 = N1C->getSExtValue();
7519   if (C0 <= 0 || C1 <= 0)
7520     return SDValue();
7521 
7522   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7523   int64_t Bits = std::min(C0, C1);
7524   int64_t Diff = std::abs(C0 - C1);
7525   if (Diff != 1 && Diff != 2 && Diff != 3)
7526     return SDValue();
7527 
7528   // Build nodes.
7529   SDLoc DL(N);
7530   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7531   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7532   SDValue NA0 =
7533       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7534   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7535   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7536 }
7537 
7538 // Combine
7539 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7540 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7541 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7542 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7543 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7544 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7545 // The grev patterns represents BSWAP.
7546 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7547 // off the grev.
7548 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7549                                           const RISCVSubtarget &Subtarget) {
7550   bool IsWInstruction =
7551       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7552   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7553           IsWInstruction) &&
7554          "Unexpected opcode!");
7555   SDValue Src = N->getOperand(0);
7556   EVT VT = N->getValueType(0);
7557   SDLoc DL(N);
7558 
7559   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7560     return SDValue();
7561 
7562   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7563       !isa<ConstantSDNode>(Src.getOperand(1)))
7564     return SDValue();
7565 
7566   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7567   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7568 
7569   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7570   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7571   unsigned ShAmt1 = N->getConstantOperandVal(1);
7572   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7573   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7574     return SDValue();
7575 
7576   Src = Src.getOperand(0);
7577 
7578   // Toggle bit the MSB of the shift.
7579   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7580   if (CombinedShAmt == 0)
7581     return Src;
7582 
7583   SDValue Res = DAG.getNode(
7584       RISCVISD::GREV, DL, VT, Src,
7585       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7586   if (!IsWInstruction)
7587     return Res;
7588 
7589   // Sign extend the result to match the behavior of the rotate. This will be
7590   // selected to GREVIW in isel.
7591   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7592                      DAG.getValueType(MVT::i32));
7593 }
7594 
7595 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7596 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7597 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7598 // not undo itself, but they are redundant.
7599 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7600   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7601   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7602   SDValue Src = N->getOperand(0);
7603 
7604   if (Src.getOpcode() != N->getOpcode())
7605     return SDValue();
7606 
7607   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7608       !isa<ConstantSDNode>(Src.getOperand(1)))
7609     return SDValue();
7610 
7611   unsigned ShAmt1 = N->getConstantOperandVal(1);
7612   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7613   Src = Src.getOperand(0);
7614 
7615   unsigned CombinedShAmt;
7616   if (IsGORC)
7617     CombinedShAmt = ShAmt1 | ShAmt2;
7618   else
7619     CombinedShAmt = ShAmt1 ^ ShAmt2;
7620 
7621   if (CombinedShAmt == 0)
7622     return Src;
7623 
7624   SDLoc DL(N);
7625   return DAG.getNode(
7626       N->getOpcode(), DL, N->getValueType(0), Src,
7627       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7628 }
7629 
7630 // Combine a constant select operand into its use:
7631 //
7632 // (and (select cond, -1, c), x)
7633 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7634 // (or  (select cond, 0, c), x)
7635 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7636 // (xor (select cond, 0, c), x)
7637 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7638 // (add (select cond, 0, c), x)
7639 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7640 // (sub x, (select cond, 0, c))
7641 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7642 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7643                                    SelectionDAG &DAG, bool AllOnes) {
7644   EVT VT = N->getValueType(0);
7645 
7646   // Skip vectors.
7647   if (VT.isVector())
7648     return SDValue();
7649 
7650   if ((Slct.getOpcode() != ISD::SELECT &&
7651        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7652       !Slct.hasOneUse())
7653     return SDValue();
7654 
7655   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7656     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7657   };
7658 
7659   bool SwapSelectOps;
7660   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7661   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7662   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7663   SDValue NonConstantVal;
7664   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7665     SwapSelectOps = false;
7666     NonConstantVal = FalseVal;
7667   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7668     SwapSelectOps = true;
7669     NonConstantVal = TrueVal;
7670   } else
7671     return SDValue();
7672 
7673   // Slct is now know to be the desired identity constant when CC is true.
7674   TrueVal = OtherOp;
7675   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7676   // Unless SwapSelectOps says the condition should be false.
7677   if (SwapSelectOps)
7678     std::swap(TrueVal, FalseVal);
7679 
7680   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7681     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7682                        {Slct.getOperand(0), Slct.getOperand(1),
7683                         Slct.getOperand(2), TrueVal, FalseVal});
7684 
7685   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7686                      {Slct.getOperand(0), TrueVal, FalseVal});
7687 }
7688 
7689 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7690 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7691                                               bool AllOnes) {
7692   SDValue N0 = N->getOperand(0);
7693   SDValue N1 = N->getOperand(1);
7694   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7695     return Result;
7696   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7697     return Result;
7698   return SDValue();
7699 }
7700 
7701 // Transform (add (mul x, c0), c1) ->
7702 //           (add (mul (add x, c1/c0), c0), c1%c0).
7703 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7704 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7705 // to an infinite loop in DAGCombine if transformed.
7706 // Or transform (add (mul x, c0), c1) ->
7707 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7708 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7709 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7710 // lead to an infinite loop in DAGCombine if transformed.
7711 // Or transform (add (mul x, c0), c1) ->
7712 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7713 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7714 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7715 // lead to an infinite loop in DAGCombine if transformed.
7716 // Or transform (add (mul x, c0), c1) ->
7717 //              (mul (add x, c1/c0), c0).
7718 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7719 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7720                                      const RISCVSubtarget &Subtarget) {
7721   // Skip for vector types and larger types.
7722   EVT VT = N->getValueType(0);
7723   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7724     return SDValue();
7725   // The first operand node must be a MUL and has no other use.
7726   SDValue N0 = N->getOperand(0);
7727   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7728     return SDValue();
7729   // Check if c0 and c1 match above conditions.
7730   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7731   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7732   if (!N0C || !N1C)
7733     return SDValue();
7734   // If N0C has multiple uses it's possible one of the cases in
7735   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7736   // in an infinite loop.
7737   if (!N0C->hasOneUse())
7738     return SDValue();
7739   int64_t C0 = N0C->getSExtValue();
7740   int64_t C1 = N1C->getSExtValue();
7741   int64_t CA, CB;
7742   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7743     return SDValue();
7744   // Search for proper CA (non-zero) and CB that both are simm12.
7745   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7746       !isInt<12>(C0 * (C1 / C0))) {
7747     CA = C1 / C0;
7748     CB = C1 % C0;
7749   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7750              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7751     CA = C1 / C0 + 1;
7752     CB = C1 % C0 - C0;
7753   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7754              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7755     CA = C1 / C0 - 1;
7756     CB = C1 % C0 + C0;
7757   } else
7758     return SDValue();
7759   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7760   SDLoc DL(N);
7761   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7762                              DAG.getConstant(CA, DL, VT));
7763   SDValue New1 =
7764       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7765   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7766 }
7767 
7768 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7769                                  const RISCVSubtarget &Subtarget) {
7770   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7771     return V;
7772   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7773     return V;
7774   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7775   //      (select lhs, rhs, cc, x, (add x, y))
7776   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7777 }
7778 
7779 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7780   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7781   //      (select lhs, rhs, cc, x, (sub x, y))
7782   SDValue N0 = N->getOperand(0);
7783   SDValue N1 = N->getOperand(1);
7784   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7785 }
7786 
7787 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7788   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7789   //      (select lhs, rhs, cc, x, (and x, y))
7790   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7791 }
7792 
7793 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7794                                 const RISCVSubtarget &Subtarget) {
7795   if (Subtarget.hasStdExtZbp()) {
7796     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7797       return GREV;
7798     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7799       return GORC;
7800     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7801       return SHFL;
7802   }
7803 
7804   // fold (or (select cond, 0, y), x) ->
7805   //      (select cond, x, (or x, y))
7806   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7807 }
7808 
7809 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7810   // fold (xor (select cond, 0, y), x) ->
7811   //      (select cond, x, (xor x, y))
7812   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7813 }
7814 
7815 static SDValue
7816 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7817                                 const RISCVSubtarget &Subtarget) {
7818   SDValue Src = N->getOperand(0);
7819   EVT VT = N->getValueType(0);
7820 
7821   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7822   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7823       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7824     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7825                        Src.getOperand(0));
7826 
7827   // Fold (i64 (sext_inreg (abs X), i32)) ->
7828   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7829   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7830   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7831   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7832   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7833   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7834   // may get combined into an earlier operation so we need to use
7835   // ComputeNumSignBits.
7836   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7837   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7838   // we can't assume that X has 33 sign bits. We must check.
7839   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7840       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7841       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7842       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7843     SDLoc DL(N);
7844     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7845     SDValue Neg =
7846         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7847     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7848                       DAG.getValueType(MVT::i32));
7849     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7850   }
7851 
7852   return SDValue();
7853 }
7854 
7855 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7856 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7857 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7858                                              bool Commute = false) {
7859   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7860           N->getOpcode() == RISCVISD::SUB_VL) &&
7861          "Unexpected opcode");
7862   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7863   SDValue Op0 = N->getOperand(0);
7864   SDValue Op1 = N->getOperand(1);
7865   if (Commute)
7866     std::swap(Op0, Op1);
7867 
7868   MVT VT = N->getSimpleValueType(0);
7869 
7870   // Determine the narrow size for a widening add/sub.
7871   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7872   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7873                                   VT.getVectorElementCount());
7874 
7875   SDValue Mask = N->getOperand(2);
7876   SDValue VL = N->getOperand(3);
7877 
7878   SDLoc DL(N);
7879 
7880   // If the RHS is a sext or zext, we can form a widening op.
7881   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7882        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7883       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7884     unsigned ExtOpc = Op1.getOpcode();
7885     Op1 = Op1.getOperand(0);
7886     // Re-introduce narrower extends if needed.
7887     if (Op1.getValueType() != NarrowVT)
7888       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7889 
7890     unsigned WOpc;
7891     if (ExtOpc == RISCVISD::VSEXT_VL)
7892       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7893     else
7894       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7895 
7896     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7897   }
7898 
7899   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7900   // sext/zext?
7901 
7902   return SDValue();
7903 }
7904 
7905 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7906 // vwsub(u).vv/vx.
7907 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7908   SDValue Op0 = N->getOperand(0);
7909   SDValue Op1 = N->getOperand(1);
7910   SDValue Mask = N->getOperand(2);
7911   SDValue VL = N->getOperand(3);
7912 
7913   MVT VT = N->getSimpleValueType(0);
7914   MVT NarrowVT = Op1.getSimpleValueType();
7915   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7916 
7917   unsigned VOpc;
7918   switch (N->getOpcode()) {
7919   default: llvm_unreachable("Unexpected opcode");
7920   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7921   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7922   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7923   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7924   }
7925 
7926   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7927                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7928 
7929   SDLoc DL(N);
7930 
7931   // If the LHS is a sext or zext, we can narrow this op to the same size as
7932   // the RHS.
7933   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7934        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7935       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7936     unsigned ExtOpc = Op0.getOpcode();
7937     Op0 = Op0.getOperand(0);
7938     // Re-introduce narrower extends if needed.
7939     if (Op0.getValueType() != NarrowVT)
7940       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7941     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7942   }
7943 
7944   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7945                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7946 
7947   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7948   // to commute and use a vwadd(u).vx instead.
7949   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7950       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7951     Op0 = Op0.getOperand(1);
7952 
7953     // See if have enough sign bits or zero bits in the scalar to use a
7954     // widening add/sub by splatting to smaller element size.
7955     unsigned EltBits = VT.getScalarSizeInBits();
7956     unsigned ScalarBits = Op0.getValueSizeInBits();
7957     // Make sure we're getting all element bits from the scalar register.
7958     // FIXME: Support implicit sign extension of vmv.v.x?
7959     if (ScalarBits < EltBits)
7960       return SDValue();
7961 
7962     if (IsSigned) {
7963       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7964         return SDValue();
7965     } else {
7966       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7967       if (!DAG.MaskedValueIsZero(Op0, Mask))
7968         return SDValue();
7969     }
7970 
7971     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7972                       DAG.getUNDEF(NarrowVT), Op0, VL);
7973     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7974   }
7975 
7976   return SDValue();
7977 }
7978 
7979 // Try to form VWMUL, VWMULU or VWMULSU.
7980 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7981 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7982                                        bool Commute) {
7983   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7984   SDValue Op0 = N->getOperand(0);
7985   SDValue Op1 = N->getOperand(1);
7986   if (Commute)
7987     std::swap(Op0, Op1);
7988 
7989   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7990   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7991   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7992   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7993     return SDValue();
7994 
7995   SDValue Mask = N->getOperand(2);
7996   SDValue VL = N->getOperand(3);
7997 
7998   // Make sure the mask and VL match.
7999   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8000     return SDValue();
8001 
8002   MVT VT = N->getSimpleValueType(0);
8003 
8004   // Determine the narrow size for a widening multiply.
8005   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8006   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8007                                   VT.getVectorElementCount());
8008 
8009   SDLoc DL(N);
8010 
8011   // See if the other operand is the same opcode.
8012   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8013     if (!Op1.hasOneUse())
8014       return SDValue();
8015 
8016     // Make sure the mask and VL match.
8017     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8018       return SDValue();
8019 
8020     Op1 = Op1.getOperand(0);
8021   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8022     // The operand is a splat of a scalar.
8023 
8024     // The pasthru must be undef for tail agnostic
8025     if (!Op1.getOperand(0).isUndef())
8026       return SDValue();
8027     // The VL must be the same.
8028     if (Op1.getOperand(2) != VL)
8029       return SDValue();
8030 
8031     // Get the scalar value.
8032     Op1 = Op1.getOperand(1);
8033 
8034     // See if have enough sign bits or zero bits in the scalar to use a
8035     // widening multiply by splatting to smaller element size.
8036     unsigned EltBits = VT.getScalarSizeInBits();
8037     unsigned ScalarBits = Op1.getValueSizeInBits();
8038     // Make sure we're getting all element bits from the scalar register.
8039     // FIXME: Support implicit sign extension of vmv.v.x?
8040     if (ScalarBits < EltBits)
8041       return SDValue();
8042 
8043     // If the LHS is a sign extend, try to use vwmul.
8044     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8045       // Can use vwmul.
8046     } else {
8047       // Otherwise try to use vwmulu or vwmulsu.
8048       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8049       if (DAG.MaskedValueIsZero(Op1, Mask))
8050         IsVWMULSU = IsSignExt;
8051       else
8052         return SDValue();
8053     }
8054 
8055     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8056                       DAG.getUNDEF(NarrowVT), Op1, VL);
8057   } else
8058     return SDValue();
8059 
8060   Op0 = Op0.getOperand(0);
8061 
8062   // Re-introduce narrower extends if needed.
8063   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8064   if (Op0.getValueType() != NarrowVT)
8065     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8066   // vwmulsu requires second operand to be zero extended.
8067   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8068   if (Op1.getValueType() != NarrowVT)
8069     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8070 
8071   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8072   if (!IsVWMULSU)
8073     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8074   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8075 }
8076 
8077 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8078   switch (Op.getOpcode()) {
8079   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8080   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8081   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8082   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8083   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8084   }
8085 
8086   return RISCVFPRndMode::Invalid;
8087 }
8088 
8089 // Fold
8090 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8091 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8092 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8093 //   (fp_to_int (fceil X))      -> fcvt X, rup
8094 //   (fp_to_int (fround X))     -> fcvt X, rmm
8095 static SDValue performFP_TO_INTCombine(SDNode *N,
8096                                        TargetLowering::DAGCombinerInfo &DCI,
8097                                        const RISCVSubtarget &Subtarget) {
8098   SelectionDAG &DAG = DCI.DAG;
8099   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8100   MVT XLenVT = Subtarget.getXLenVT();
8101 
8102   // Only handle XLen or i32 types. Other types narrower than XLen will
8103   // eventually be legalized to XLenVT.
8104   EVT VT = N->getValueType(0);
8105   if (VT != MVT::i32 && VT != XLenVT)
8106     return SDValue();
8107 
8108   SDValue Src = N->getOperand(0);
8109 
8110   // Ensure the FP type is also legal.
8111   if (!TLI.isTypeLegal(Src.getValueType()))
8112     return SDValue();
8113 
8114   // Don't do this for f16 with Zfhmin and not Zfh.
8115   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8116     return SDValue();
8117 
8118   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8119   if (FRM == RISCVFPRndMode::Invalid)
8120     return SDValue();
8121 
8122   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8123 
8124   unsigned Opc;
8125   if (VT == XLenVT)
8126     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8127   else
8128     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8129 
8130   SDLoc DL(N);
8131   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8132                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8133   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8134 }
8135 
8136 // Fold
8137 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8138 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8139 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8140 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8141 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8142 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8143                                        TargetLowering::DAGCombinerInfo &DCI,
8144                                        const RISCVSubtarget &Subtarget) {
8145   SelectionDAG &DAG = DCI.DAG;
8146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8147   MVT XLenVT = Subtarget.getXLenVT();
8148 
8149   // Only handle XLen types. Other types narrower than XLen will eventually be
8150   // legalized to XLenVT.
8151   EVT DstVT = N->getValueType(0);
8152   if (DstVT != XLenVT)
8153     return SDValue();
8154 
8155   SDValue Src = N->getOperand(0);
8156 
8157   // Ensure the FP type is also legal.
8158   if (!TLI.isTypeLegal(Src.getValueType()))
8159     return SDValue();
8160 
8161   // Don't do this for f16 with Zfhmin and not Zfh.
8162   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8163     return SDValue();
8164 
8165   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8166 
8167   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8168   if (FRM == RISCVFPRndMode::Invalid)
8169     return SDValue();
8170 
8171   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8172 
8173   unsigned Opc;
8174   if (SatVT == DstVT)
8175     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8176   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8177     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8178   else
8179     return SDValue();
8180   // FIXME: Support other SatVTs by clamping before or after the conversion.
8181 
8182   Src = Src.getOperand(0);
8183 
8184   SDLoc DL(N);
8185   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8186                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8187 
8188   // RISCV FP-to-int conversions saturate to the destination register size, but
8189   // don't produce 0 for nan.
8190   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8191   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8192 }
8193 
8194 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8195 // smaller than XLenVT.
8196 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8197                                         const RISCVSubtarget &Subtarget) {
8198   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8199 
8200   SDValue Src = N->getOperand(0);
8201   if (Src.getOpcode() != ISD::BSWAP)
8202     return SDValue();
8203 
8204   EVT VT = N->getValueType(0);
8205   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8206       !isPowerOf2_32(VT.getSizeInBits()))
8207     return SDValue();
8208 
8209   SDLoc DL(N);
8210   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8211                      DAG.getConstant(7, DL, VT));
8212 }
8213 
8214 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8215                                                DAGCombinerInfo &DCI) const {
8216   SelectionDAG &DAG = DCI.DAG;
8217 
8218   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8219   // bits are demanded. N will be added to the Worklist if it was not deleted.
8220   // Caller should return SDValue(N, 0) if this returns true.
8221   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8222     SDValue Op = N->getOperand(OpNo);
8223     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8224     if (!SimplifyDemandedBits(Op, Mask, DCI))
8225       return false;
8226 
8227     if (N->getOpcode() != ISD::DELETED_NODE)
8228       DCI.AddToWorklist(N);
8229     return true;
8230   };
8231 
8232   switch (N->getOpcode()) {
8233   default:
8234     break;
8235   case RISCVISD::SplitF64: {
8236     SDValue Op0 = N->getOperand(0);
8237     // If the input to SplitF64 is just BuildPairF64 then the operation is
8238     // redundant. Instead, use BuildPairF64's operands directly.
8239     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8240       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8241 
8242     if (Op0->isUndef()) {
8243       SDValue Lo = DAG.getUNDEF(MVT::i32);
8244       SDValue Hi = DAG.getUNDEF(MVT::i32);
8245       return DCI.CombineTo(N, Lo, Hi);
8246     }
8247 
8248     SDLoc DL(N);
8249 
8250     // It's cheaper to materialise two 32-bit integers than to load a double
8251     // from the constant pool and transfer it to integer registers through the
8252     // stack.
8253     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8254       APInt V = C->getValueAPF().bitcastToAPInt();
8255       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8256       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8257       return DCI.CombineTo(N, Lo, Hi);
8258     }
8259 
8260     // This is a target-specific version of a DAGCombine performed in
8261     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8262     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8263     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8264     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8265         !Op0.getNode()->hasOneUse())
8266       break;
8267     SDValue NewSplitF64 =
8268         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8269                     Op0.getOperand(0));
8270     SDValue Lo = NewSplitF64.getValue(0);
8271     SDValue Hi = NewSplitF64.getValue(1);
8272     APInt SignBit = APInt::getSignMask(32);
8273     if (Op0.getOpcode() == ISD::FNEG) {
8274       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8275                                   DAG.getConstant(SignBit, DL, MVT::i32));
8276       return DCI.CombineTo(N, Lo, NewHi);
8277     }
8278     assert(Op0.getOpcode() == ISD::FABS);
8279     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8280                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8281     return DCI.CombineTo(N, Lo, NewHi);
8282   }
8283   case RISCVISD::SLLW:
8284   case RISCVISD::SRAW:
8285   case RISCVISD::SRLW: {
8286     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8287     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8288         SimplifyDemandedLowBitsHelper(1, 5))
8289       return SDValue(N, 0);
8290 
8291     break;
8292   }
8293   case ISD::ROTR:
8294   case ISD::ROTL:
8295   case RISCVISD::RORW:
8296   case RISCVISD::ROLW: {
8297     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8298       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8299       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8300           SimplifyDemandedLowBitsHelper(1, 5))
8301         return SDValue(N, 0);
8302     }
8303 
8304     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8305   }
8306   case RISCVISD::CLZW:
8307   case RISCVISD::CTZW: {
8308     // Only the lower 32 bits of the first operand are read
8309     if (SimplifyDemandedLowBitsHelper(0, 32))
8310       return SDValue(N, 0);
8311     break;
8312   }
8313   case RISCVISD::GREV:
8314   case RISCVISD::GORC: {
8315     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8316     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8317     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8318     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8319       return SDValue(N, 0);
8320 
8321     return combineGREVI_GORCI(N, DAG);
8322   }
8323   case RISCVISD::GREVW:
8324   case RISCVISD::GORCW: {
8325     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8326     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8327         SimplifyDemandedLowBitsHelper(1, 5))
8328       return SDValue(N, 0);
8329 
8330     break;
8331   }
8332   case RISCVISD::SHFL:
8333   case RISCVISD::UNSHFL: {
8334     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8335     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8336     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8337     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8338       return SDValue(N, 0);
8339 
8340     break;
8341   }
8342   case RISCVISD::SHFLW:
8343   case RISCVISD::UNSHFLW: {
8344     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8345     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8346         SimplifyDemandedLowBitsHelper(1, 4))
8347       return SDValue(N, 0);
8348 
8349     break;
8350   }
8351   case RISCVISD::BCOMPRESSW:
8352   case RISCVISD::BDECOMPRESSW: {
8353     // Only the lower 32 bits of LHS and RHS are read.
8354     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8355         SimplifyDemandedLowBitsHelper(1, 32))
8356       return SDValue(N, 0);
8357 
8358     break;
8359   }
8360   case RISCVISD::FSR:
8361   case RISCVISD::FSL:
8362   case RISCVISD::FSRW:
8363   case RISCVISD::FSLW: {
8364     bool IsWInstruction =
8365         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8366     unsigned BitWidth =
8367         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8368     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8369     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8370     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8371       return SDValue(N, 0);
8372 
8373     break;
8374   }
8375   case RISCVISD::FMV_X_ANYEXTH:
8376   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8377     SDLoc DL(N);
8378     SDValue Op0 = N->getOperand(0);
8379     MVT VT = N->getSimpleValueType(0);
8380     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8381     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8382     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8383     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8384          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8385         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8386          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8387       assert(Op0.getOperand(0).getValueType() == VT &&
8388              "Unexpected value type!");
8389       return Op0.getOperand(0);
8390     }
8391 
8392     // This is a target-specific version of a DAGCombine performed in
8393     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8394     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8395     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8396     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8397         !Op0.getNode()->hasOneUse())
8398       break;
8399     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8400     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8401     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8402     if (Op0.getOpcode() == ISD::FNEG)
8403       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8404                          DAG.getConstant(SignBit, DL, VT));
8405 
8406     assert(Op0.getOpcode() == ISD::FABS);
8407     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8408                        DAG.getConstant(~SignBit, DL, VT));
8409   }
8410   case ISD::ADD:
8411     return performADDCombine(N, DAG, Subtarget);
8412   case ISD::SUB:
8413     return performSUBCombine(N, DAG);
8414   case ISD::AND:
8415     return performANDCombine(N, DAG);
8416   case ISD::OR:
8417     return performORCombine(N, DAG, Subtarget);
8418   case ISD::XOR:
8419     return performXORCombine(N, DAG);
8420   case ISD::SIGN_EXTEND_INREG:
8421     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8422   case ISD::ZERO_EXTEND:
8423     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8424     // type legalization. This is safe because fp_to_uint produces poison if
8425     // it overflows.
8426     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8427       SDValue Src = N->getOperand(0);
8428       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8429           isTypeLegal(Src.getOperand(0).getValueType()))
8430         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8431                            Src.getOperand(0));
8432       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8433           isTypeLegal(Src.getOperand(1).getValueType())) {
8434         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8435         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8436                                   Src.getOperand(0), Src.getOperand(1));
8437         DCI.CombineTo(N, Res);
8438         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8439         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8440         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8441       }
8442     }
8443     return SDValue();
8444   case RISCVISD::SELECT_CC: {
8445     // Transform
8446     SDValue LHS = N->getOperand(0);
8447     SDValue RHS = N->getOperand(1);
8448     SDValue TrueV = N->getOperand(3);
8449     SDValue FalseV = N->getOperand(4);
8450 
8451     // If the True and False values are the same, we don't need a select_cc.
8452     if (TrueV == FalseV)
8453       return TrueV;
8454 
8455     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8456     if (!ISD::isIntEqualitySetCC(CCVal))
8457       break;
8458 
8459     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8460     //      (select_cc X, Y, lt, trueV, falseV)
8461     // Sometimes the setcc is introduced after select_cc has been formed.
8462     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8463         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8464       // If we're looking for eq 0 instead of ne 0, we need to invert the
8465       // condition.
8466       bool Invert = CCVal == ISD::SETEQ;
8467       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8468       if (Invert)
8469         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8470 
8471       SDLoc DL(N);
8472       RHS = LHS.getOperand(1);
8473       LHS = LHS.getOperand(0);
8474       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8475 
8476       SDValue TargetCC = DAG.getCondCode(CCVal);
8477       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8478                          {LHS, RHS, TargetCC, TrueV, FalseV});
8479     }
8480 
8481     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8482     //      (select_cc X, Y, eq/ne, trueV, falseV)
8483     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8484       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8485                          {LHS.getOperand(0), LHS.getOperand(1),
8486                           N->getOperand(2), TrueV, FalseV});
8487     // (select_cc X, 1, setne, trueV, falseV) ->
8488     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8489     // This can occur when legalizing some floating point comparisons.
8490     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8491     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8492       SDLoc DL(N);
8493       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8494       SDValue TargetCC = DAG.getCondCode(CCVal);
8495       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8496       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8497                          {LHS, RHS, TargetCC, TrueV, FalseV});
8498     }
8499 
8500     break;
8501   }
8502   case RISCVISD::BR_CC: {
8503     SDValue LHS = N->getOperand(1);
8504     SDValue RHS = N->getOperand(2);
8505     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8506     if (!ISD::isIntEqualitySetCC(CCVal))
8507       break;
8508 
8509     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8510     //      (br_cc X, Y, lt, dest)
8511     // Sometimes the setcc is introduced after br_cc has been formed.
8512     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8513         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8514       // If we're looking for eq 0 instead of ne 0, we need to invert the
8515       // condition.
8516       bool Invert = CCVal == ISD::SETEQ;
8517       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8518       if (Invert)
8519         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8520 
8521       SDLoc DL(N);
8522       RHS = LHS.getOperand(1);
8523       LHS = LHS.getOperand(0);
8524       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8525 
8526       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8527                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8528                          N->getOperand(4));
8529     }
8530 
8531     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8532     //      (br_cc X, Y, eq/ne, trueV, falseV)
8533     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8534       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8535                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8536                          N->getOperand(3), N->getOperand(4));
8537 
8538     // (br_cc X, 1, setne, br_cc) ->
8539     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8540     // This can occur when legalizing some floating point comparisons.
8541     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8542     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8543       SDLoc DL(N);
8544       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8545       SDValue TargetCC = DAG.getCondCode(CCVal);
8546       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8547       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8548                          N->getOperand(0), LHS, RHS, TargetCC,
8549                          N->getOperand(4));
8550     }
8551     break;
8552   }
8553   case ISD::BITREVERSE:
8554     return performBITREVERSECombine(N, DAG, Subtarget);
8555   case ISD::FP_TO_SINT:
8556   case ISD::FP_TO_UINT:
8557     return performFP_TO_INTCombine(N, DCI, Subtarget);
8558   case ISD::FP_TO_SINT_SAT:
8559   case ISD::FP_TO_UINT_SAT:
8560     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8561   case ISD::FCOPYSIGN: {
8562     EVT VT = N->getValueType(0);
8563     if (!VT.isVector())
8564       break;
8565     // There is a form of VFSGNJ which injects the negated sign of its second
8566     // operand. Try and bubble any FNEG up after the extend/round to produce
8567     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8568     // TRUNC=1.
8569     SDValue In2 = N->getOperand(1);
8570     // Avoid cases where the extend/round has multiple uses, as duplicating
8571     // those is typically more expensive than removing a fneg.
8572     if (!In2.hasOneUse())
8573       break;
8574     if (In2.getOpcode() != ISD::FP_EXTEND &&
8575         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8576       break;
8577     In2 = In2.getOperand(0);
8578     if (In2.getOpcode() != ISD::FNEG)
8579       break;
8580     SDLoc DL(N);
8581     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8582     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8583                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8584   }
8585   case ISD::MGATHER:
8586   case ISD::MSCATTER:
8587   case ISD::VP_GATHER:
8588   case ISD::VP_SCATTER: {
8589     if (!DCI.isBeforeLegalize())
8590       break;
8591     SDValue Index, ScaleOp;
8592     bool IsIndexScaled = false;
8593     bool IsIndexSigned = false;
8594     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8595       Index = VPGSN->getIndex();
8596       ScaleOp = VPGSN->getScale();
8597       IsIndexScaled = VPGSN->isIndexScaled();
8598       IsIndexSigned = VPGSN->isIndexSigned();
8599     } else {
8600       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8601       Index = MGSN->getIndex();
8602       ScaleOp = MGSN->getScale();
8603       IsIndexScaled = MGSN->isIndexScaled();
8604       IsIndexSigned = MGSN->isIndexSigned();
8605     }
8606     EVT IndexVT = Index.getValueType();
8607     MVT XLenVT = Subtarget.getXLenVT();
8608     // RISCV indexed loads only support the "unsigned unscaled" addressing
8609     // mode, so anything else must be manually legalized.
8610     bool NeedsIdxLegalization =
8611         IsIndexScaled ||
8612         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8613     if (!NeedsIdxLegalization)
8614       break;
8615 
8616     SDLoc DL(N);
8617 
8618     // Any index legalization should first promote to XLenVT, so we don't lose
8619     // bits when scaling. This may create an illegal index type so we let
8620     // LLVM's legalization take care of the splitting.
8621     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8622     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8623       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8624       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8625                           DL, IndexVT, Index);
8626     }
8627 
8628     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8629     if (IsIndexScaled && Scale != 1) {
8630       // Manually scale the indices by the element size.
8631       // TODO: Sanitize the scale operand here?
8632       // TODO: For VP nodes, should we use VP_SHL here?
8633       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8634       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8635       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8636     }
8637 
8638     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8639     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8640       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8641                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8642                               VPGN->getScale(), VPGN->getMask(),
8643                               VPGN->getVectorLength()},
8644                              VPGN->getMemOperand(), NewIndexTy);
8645     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8646       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8647                               {VPSN->getChain(), VPSN->getValue(),
8648                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8649                                VPSN->getMask(), VPSN->getVectorLength()},
8650                               VPSN->getMemOperand(), NewIndexTy);
8651     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8652       return DAG.getMaskedGather(
8653           N->getVTList(), MGN->getMemoryVT(), DL,
8654           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8655            MGN->getBasePtr(), Index, MGN->getScale()},
8656           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8657     const auto *MSN = cast<MaskedScatterSDNode>(N);
8658     return DAG.getMaskedScatter(
8659         N->getVTList(), MSN->getMemoryVT(), DL,
8660         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8661          Index, MSN->getScale()},
8662         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8663   }
8664   case RISCVISD::SRA_VL:
8665   case RISCVISD::SRL_VL:
8666   case RISCVISD::SHL_VL: {
8667     SDValue ShAmt = N->getOperand(1);
8668     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8669       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8670       SDLoc DL(N);
8671       SDValue VL = N->getOperand(3);
8672       EVT VT = N->getValueType(0);
8673       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8674                           ShAmt.getOperand(1), VL);
8675       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8676                          N->getOperand(2), N->getOperand(3));
8677     }
8678     break;
8679   }
8680   case ISD::SRA:
8681   case ISD::SRL:
8682   case ISD::SHL: {
8683     SDValue ShAmt = N->getOperand(1);
8684     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8685       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8686       SDLoc DL(N);
8687       EVT VT = N->getValueType(0);
8688       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8689                           ShAmt.getOperand(1),
8690                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8691       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8692     }
8693     break;
8694   }
8695   case RISCVISD::ADD_VL:
8696     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8697       return V;
8698     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8699   case RISCVISD::SUB_VL:
8700     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8701   case RISCVISD::VWADD_W_VL:
8702   case RISCVISD::VWADDU_W_VL:
8703   case RISCVISD::VWSUB_W_VL:
8704   case RISCVISD::VWSUBU_W_VL:
8705     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8706   case RISCVISD::MUL_VL:
8707     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8708       return V;
8709     // Mul is commutative.
8710     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8711   case ISD::STORE: {
8712     auto *Store = cast<StoreSDNode>(N);
8713     SDValue Val = Store->getValue();
8714     // Combine store of vmv.x.s to vse with VL of 1.
8715     // FIXME: Support FP.
8716     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8717       SDValue Src = Val.getOperand(0);
8718       EVT VecVT = Src.getValueType();
8719       EVT MemVT = Store->getMemoryVT();
8720       // The memory VT and the element type must match.
8721       if (VecVT.getVectorElementType() == MemVT) {
8722         SDLoc DL(N);
8723         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8724         return DAG.getStoreVP(
8725             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8726             DAG.getConstant(1, DL, MaskVT),
8727             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8728             Store->getMemOperand(), Store->getAddressingMode(),
8729             Store->isTruncatingStore(), /*IsCompress*/ false);
8730       }
8731     }
8732 
8733     break;
8734   }
8735   case ISD::SPLAT_VECTOR: {
8736     EVT VT = N->getValueType(0);
8737     // Only perform this combine on legal MVT types.
8738     if (!isTypeLegal(VT))
8739       break;
8740     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8741                                          DAG, Subtarget))
8742       return Gather;
8743     break;
8744   }
8745   case RISCVISD::VMV_V_X_VL: {
8746     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8747     // scalar input.
8748     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8749     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8750     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8751       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8752         return SDValue(N, 0);
8753 
8754     break;
8755   }
8756   case ISD::INTRINSIC_WO_CHAIN: {
8757     unsigned IntNo = N->getConstantOperandVal(0);
8758     switch (IntNo) {
8759       // By default we do not combine any intrinsic.
8760     default:
8761       return SDValue();
8762     case Intrinsic::riscv_vcpop:
8763     case Intrinsic::riscv_vcpop_mask:
8764     case Intrinsic::riscv_vfirst:
8765     case Intrinsic::riscv_vfirst_mask: {
8766       SDValue VL = N->getOperand(2);
8767       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8768           IntNo == Intrinsic::riscv_vfirst_mask)
8769         VL = N->getOperand(3);
8770       if (!isNullConstant(VL))
8771         return SDValue();
8772       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8773       SDLoc DL(N);
8774       EVT VT = N->getValueType(0);
8775       if (IntNo == Intrinsic::riscv_vfirst ||
8776           IntNo == Intrinsic::riscv_vfirst_mask)
8777         return DAG.getConstant(-1, DL, VT);
8778       return DAG.getConstant(0, DL, VT);
8779     }
8780     }
8781   }
8782   }
8783 
8784   return SDValue();
8785 }
8786 
8787 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8788     const SDNode *N, CombineLevel Level) const {
8789   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8790   // materialised in fewer instructions than `(OP _, c1)`:
8791   //
8792   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8793   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8794   SDValue N0 = N->getOperand(0);
8795   EVT Ty = N0.getValueType();
8796   if (Ty.isScalarInteger() &&
8797       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8798     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8799     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8800     if (C1 && C2) {
8801       const APInt &C1Int = C1->getAPIntValue();
8802       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8803 
8804       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8805       // and the combine should happen, to potentially allow further combines
8806       // later.
8807       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8808           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8809         return true;
8810 
8811       // We can materialise `c1` in an add immediate, so it's "free", and the
8812       // combine should be prevented.
8813       if (C1Int.getMinSignedBits() <= 64 &&
8814           isLegalAddImmediate(C1Int.getSExtValue()))
8815         return false;
8816 
8817       // Neither constant will fit into an immediate, so find materialisation
8818       // costs.
8819       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8820                                               Subtarget.getFeatureBits(),
8821                                               /*CompressionCost*/true);
8822       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8823           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8824           /*CompressionCost*/true);
8825 
8826       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8827       // combine should be prevented.
8828       if (C1Cost < ShiftedC1Cost)
8829         return false;
8830     }
8831   }
8832   return true;
8833 }
8834 
8835 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8836     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8837     TargetLoweringOpt &TLO) const {
8838   // Delay this optimization as late as possible.
8839   if (!TLO.LegalOps)
8840     return false;
8841 
8842   EVT VT = Op.getValueType();
8843   if (VT.isVector())
8844     return false;
8845 
8846   // Only handle AND for now.
8847   if (Op.getOpcode() != ISD::AND)
8848     return false;
8849 
8850   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8851   if (!C)
8852     return false;
8853 
8854   const APInt &Mask = C->getAPIntValue();
8855 
8856   // Clear all non-demanded bits initially.
8857   APInt ShrunkMask = Mask & DemandedBits;
8858 
8859   // Try to make a smaller immediate by setting undemanded bits.
8860 
8861   APInt ExpandedMask = Mask | ~DemandedBits;
8862 
8863   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8864     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8865   };
8866   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8867     if (NewMask == Mask)
8868       return true;
8869     SDLoc DL(Op);
8870     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8871     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8872     return TLO.CombineTo(Op, NewOp);
8873   };
8874 
8875   // If the shrunk mask fits in sign extended 12 bits, let the target
8876   // independent code apply it.
8877   if (ShrunkMask.isSignedIntN(12))
8878     return false;
8879 
8880   // Preserve (and X, 0xffff) when zext.h is supported.
8881   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8882     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8883     if (IsLegalMask(NewMask))
8884       return UseMask(NewMask);
8885   }
8886 
8887   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8888   if (VT == MVT::i64) {
8889     APInt NewMask = APInt(64, 0xffffffff);
8890     if (IsLegalMask(NewMask))
8891       return UseMask(NewMask);
8892   }
8893 
8894   // For the remaining optimizations, we need to be able to make a negative
8895   // number through a combination of mask and undemanded bits.
8896   if (!ExpandedMask.isNegative())
8897     return false;
8898 
8899   // What is the fewest number of bits we need to represent the negative number.
8900   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8901 
8902   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8903   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8904   APInt NewMask = ShrunkMask;
8905   if (MinSignedBits <= 12)
8906     NewMask.setBitsFrom(11);
8907   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8908     NewMask.setBitsFrom(31);
8909   else
8910     return false;
8911 
8912   // Check that our new mask is a subset of the demanded mask.
8913   assert(IsLegalMask(NewMask));
8914   return UseMask(NewMask);
8915 }
8916 
8917 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
8918   static const uint64_t GREVMasks[] = {
8919       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
8920       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
8921 
8922   for (unsigned Stage = 0; Stage != 6; ++Stage) {
8923     unsigned Shift = 1 << Stage;
8924     if (ShAmt & Shift) {
8925       uint64_t Mask = GREVMasks[Stage];
8926       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
8927       if (IsGORC)
8928         Res |= x;
8929       x = Res;
8930     }
8931   }
8932 
8933   return x;
8934 }
8935 
8936 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8937                                                         KnownBits &Known,
8938                                                         const APInt &DemandedElts,
8939                                                         const SelectionDAG &DAG,
8940                                                         unsigned Depth) const {
8941   unsigned BitWidth = Known.getBitWidth();
8942   unsigned Opc = Op.getOpcode();
8943   assert((Opc >= ISD::BUILTIN_OP_END ||
8944           Opc == ISD::INTRINSIC_WO_CHAIN ||
8945           Opc == ISD::INTRINSIC_W_CHAIN ||
8946           Opc == ISD::INTRINSIC_VOID) &&
8947          "Should use MaskedValueIsZero if you don't know whether Op"
8948          " is a target node!");
8949 
8950   Known.resetAll();
8951   switch (Opc) {
8952   default: break;
8953   case RISCVISD::SELECT_CC: {
8954     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8955     // If we don't know any bits, early out.
8956     if (Known.isUnknown())
8957       break;
8958     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8959 
8960     // Only known if known in both the LHS and RHS.
8961     Known = KnownBits::commonBits(Known, Known2);
8962     break;
8963   }
8964   case RISCVISD::REMUW: {
8965     KnownBits Known2;
8966     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8967     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8968     // We only care about the lower 32 bits.
8969     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8970     // Restore the original width by sign extending.
8971     Known = Known.sext(BitWidth);
8972     break;
8973   }
8974   case RISCVISD::DIVUW: {
8975     KnownBits Known2;
8976     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8977     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8978     // We only care about the lower 32 bits.
8979     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8980     // Restore the original width by sign extending.
8981     Known = Known.sext(BitWidth);
8982     break;
8983   }
8984   case RISCVISD::CTZW: {
8985     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8986     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8987     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8988     Known.Zero.setBitsFrom(LowBits);
8989     break;
8990   }
8991   case RISCVISD::CLZW: {
8992     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8993     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8994     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8995     Known.Zero.setBitsFrom(LowBits);
8996     break;
8997   }
8998   case RISCVISD::GREV:
8999   case RISCVISD::GORC: {
9000     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9001       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9002       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9003       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9004       // To compute zeros, we need to invert the value and invert it back after.
9005       Known.Zero =
9006           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9007       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9008     }
9009     break;
9010   }
9011   case RISCVISD::READ_VLENB: {
9012     // If we know the minimum VLen from Zvl extensions, we can use that to
9013     // determine the trailing zeros of VLENB.
9014     // FIXME: Limit to 128 bit vectors until we have more testing.
9015     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9016     if (MinVLenB > 0)
9017       Known.Zero.setLowBits(Log2_32(MinVLenB));
9018     // We assume VLENB is no more than 65536 / 8 bytes.
9019     Known.Zero.setBitsFrom(14);
9020     break;
9021   }
9022   case ISD::INTRINSIC_W_CHAIN:
9023   case ISD::INTRINSIC_WO_CHAIN: {
9024     unsigned IntNo =
9025         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9026     switch (IntNo) {
9027     default:
9028       // We can't do anything for most intrinsics.
9029       break;
9030     case Intrinsic::riscv_vsetvli:
9031     case Intrinsic::riscv_vsetvlimax:
9032     case Intrinsic::riscv_vsetvli_opt:
9033     case Intrinsic::riscv_vsetvlimax_opt:
9034       // Assume that VL output is positive and would fit in an int32_t.
9035       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9036       if (BitWidth >= 32)
9037         Known.Zero.setBitsFrom(31);
9038       break;
9039     }
9040     break;
9041   }
9042   }
9043 }
9044 
9045 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9046     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9047     unsigned Depth) const {
9048   switch (Op.getOpcode()) {
9049   default:
9050     break;
9051   case RISCVISD::SELECT_CC: {
9052     unsigned Tmp =
9053         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9054     if (Tmp == 1) return 1;  // Early out.
9055     unsigned Tmp2 =
9056         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9057     return std::min(Tmp, Tmp2);
9058   }
9059   case RISCVISD::SLLW:
9060   case RISCVISD::SRAW:
9061   case RISCVISD::SRLW:
9062   case RISCVISD::DIVW:
9063   case RISCVISD::DIVUW:
9064   case RISCVISD::REMUW:
9065   case RISCVISD::ROLW:
9066   case RISCVISD::RORW:
9067   case RISCVISD::GREVW:
9068   case RISCVISD::GORCW:
9069   case RISCVISD::FSLW:
9070   case RISCVISD::FSRW:
9071   case RISCVISD::SHFLW:
9072   case RISCVISD::UNSHFLW:
9073   case RISCVISD::BCOMPRESSW:
9074   case RISCVISD::BDECOMPRESSW:
9075   case RISCVISD::BFPW:
9076   case RISCVISD::FCVT_W_RV64:
9077   case RISCVISD::FCVT_WU_RV64:
9078   case RISCVISD::STRICT_FCVT_W_RV64:
9079   case RISCVISD::STRICT_FCVT_WU_RV64:
9080     // TODO: As the result is sign-extended, this is conservatively correct. A
9081     // more precise answer could be calculated for SRAW depending on known
9082     // bits in the shift amount.
9083     return 33;
9084   case RISCVISD::SHFL:
9085   case RISCVISD::UNSHFL: {
9086     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9087     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9088     // will stay within the upper 32 bits. If there were more than 32 sign bits
9089     // before there will be at least 33 sign bits after.
9090     if (Op.getValueType() == MVT::i64 &&
9091         isa<ConstantSDNode>(Op.getOperand(1)) &&
9092         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9093       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9094       if (Tmp > 32)
9095         return 33;
9096     }
9097     break;
9098   }
9099   case RISCVISD::VMV_X_S: {
9100     // The number of sign bits of the scalar result is computed by obtaining the
9101     // element type of the input vector operand, subtracting its width from the
9102     // XLEN, and then adding one (sign bit within the element type). If the
9103     // element type is wider than XLen, the least-significant XLEN bits are
9104     // taken.
9105     unsigned XLen = Subtarget.getXLen();
9106     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9107     if (EltBits <= XLen)
9108       return XLen - EltBits + 1;
9109     break;
9110   }
9111   }
9112 
9113   return 1;
9114 }
9115 
9116 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9117                                                   MachineBasicBlock *BB) {
9118   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9119 
9120   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9121   // Should the count have wrapped while it was being read, we need to try
9122   // again.
9123   // ...
9124   // read:
9125   // rdcycleh x3 # load high word of cycle
9126   // rdcycle  x2 # load low word of cycle
9127   // rdcycleh x4 # load high word of cycle
9128   // bne x3, x4, read # check if high word reads match, otherwise try again
9129   // ...
9130 
9131   MachineFunction &MF = *BB->getParent();
9132   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9133   MachineFunction::iterator It = ++BB->getIterator();
9134 
9135   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9136   MF.insert(It, LoopMBB);
9137 
9138   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9139   MF.insert(It, DoneMBB);
9140 
9141   // Transfer the remainder of BB and its successor edges to DoneMBB.
9142   DoneMBB->splice(DoneMBB->begin(), BB,
9143                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9144   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9145 
9146   BB->addSuccessor(LoopMBB);
9147 
9148   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9149   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9150   Register LoReg = MI.getOperand(0).getReg();
9151   Register HiReg = MI.getOperand(1).getReg();
9152   DebugLoc DL = MI.getDebugLoc();
9153 
9154   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9155   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9156       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9157       .addReg(RISCV::X0);
9158   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9159       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9160       .addReg(RISCV::X0);
9161   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9162       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9163       .addReg(RISCV::X0);
9164 
9165   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9166       .addReg(HiReg)
9167       .addReg(ReadAgainReg)
9168       .addMBB(LoopMBB);
9169 
9170   LoopMBB->addSuccessor(LoopMBB);
9171   LoopMBB->addSuccessor(DoneMBB);
9172 
9173   MI.eraseFromParent();
9174 
9175   return DoneMBB;
9176 }
9177 
9178 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9179                                              MachineBasicBlock *BB) {
9180   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9181 
9182   MachineFunction &MF = *BB->getParent();
9183   DebugLoc DL = MI.getDebugLoc();
9184   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9185   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9186   Register LoReg = MI.getOperand(0).getReg();
9187   Register HiReg = MI.getOperand(1).getReg();
9188   Register SrcReg = MI.getOperand(2).getReg();
9189   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9190   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9191 
9192   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9193                           RI);
9194   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9195   MachineMemOperand *MMOLo =
9196       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9197   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9198       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9199   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9200       .addFrameIndex(FI)
9201       .addImm(0)
9202       .addMemOperand(MMOLo);
9203   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9204       .addFrameIndex(FI)
9205       .addImm(4)
9206       .addMemOperand(MMOHi);
9207   MI.eraseFromParent(); // The pseudo instruction is gone now.
9208   return BB;
9209 }
9210 
9211 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9212                                                  MachineBasicBlock *BB) {
9213   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9214          "Unexpected instruction");
9215 
9216   MachineFunction &MF = *BB->getParent();
9217   DebugLoc DL = MI.getDebugLoc();
9218   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9219   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9220   Register DstReg = MI.getOperand(0).getReg();
9221   Register LoReg = MI.getOperand(1).getReg();
9222   Register HiReg = MI.getOperand(2).getReg();
9223   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9224   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9225 
9226   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9227   MachineMemOperand *MMOLo =
9228       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9229   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9230       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9231   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9232       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9233       .addFrameIndex(FI)
9234       .addImm(0)
9235       .addMemOperand(MMOLo);
9236   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9237       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9238       .addFrameIndex(FI)
9239       .addImm(4)
9240       .addMemOperand(MMOHi);
9241   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9242   MI.eraseFromParent(); // The pseudo instruction is gone now.
9243   return BB;
9244 }
9245 
9246 static bool isSelectPseudo(MachineInstr &MI) {
9247   switch (MI.getOpcode()) {
9248   default:
9249     return false;
9250   case RISCV::Select_GPR_Using_CC_GPR:
9251   case RISCV::Select_FPR16_Using_CC_GPR:
9252   case RISCV::Select_FPR32_Using_CC_GPR:
9253   case RISCV::Select_FPR64_Using_CC_GPR:
9254     return true;
9255   }
9256 }
9257 
9258 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9259                                         unsigned RelOpcode, unsigned EqOpcode,
9260                                         const RISCVSubtarget &Subtarget) {
9261   DebugLoc DL = MI.getDebugLoc();
9262   Register DstReg = MI.getOperand(0).getReg();
9263   Register Src1Reg = MI.getOperand(1).getReg();
9264   Register Src2Reg = MI.getOperand(2).getReg();
9265   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9266   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9267   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9268 
9269   // Save the current FFLAGS.
9270   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9271 
9272   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9273                  .addReg(Src1Reg)
9274                  .addReg(Src2Reg);
9275   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9276     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9277 
9278   // Restore the FFLAGS.
9279   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9280       .addReg(SavedFFlags, RegState::Kill);
9281 
9282   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9283   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9284                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9285                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9286   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9287     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9288 
9289   // Erase the pseudoinstruction.
9290   MI.eraseFromParent();
9291   return BB;
9292 }
9293 
9294 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9295                                            MachineBasicBlock *BB,
9296                                            const RISCVSubtarget &Subtarget) {
9297   // To "insert" Select_* instructions, we actually have to insert the triangle
9298   // control-flow pattern.  The incoming instructions know the destination vreg
9299   // to set, the condition code register to branch on, the true/false values to
9300   // select between, and the condcode to use to select the appropriate branch.
9301   //
9302   // We produce the following control flow:
9303   //     HeadMBB
9304   //     |  \
9305   //     |  IfFalseMBB
9306   //     | /
9307   //    TailMBB
9308   //
9309   // When we find a sequence of selects we attempt to optimize their emission
9310   // by sharing the control flow. Currently we only handle cases where we have
9311   // multiple selects with the exact same condition (same LHS, RHS and CC).
9312   // The selects may be interleaved with other instructions if the other
9313   // instructions meet some requirements we deem safe:
9314   // - They are debug instructions. Otherwise,
9315   // - They do not have side-effects, do not access memory and their inputs do
9316   //   not depend on the results of the select pseudo-instructions.
9317   // The TrueV/FalseV operands of the selects cannot depend on the result of
9318   // previous selects in the sequence.
9319   // These conditions could be further relaxed. See the X86 target for a
9320   // related approach and more information.
9321   Register LHS = MI.getOperand(1).getReg();
9322   Register RHS = MI.getOperand(2).getReg();
9323   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9324 
9325   SmallVector<MachineInstr *, 4> SelectDebugValues;
9326   SmallSet<Register, 4> SelectDests;
9327   SelectDests.insert(MI.getOperand(0).getReg());
9328 
9329   MachineInstr *LastSelectPseudo = &MI;
9330 
9331   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9332        SequenceMBBI != E; ++SequenceMBBI) {
9333     if (SequenceMBBI->isDebugInstr())
9334       continue;
9335     else if (isSelectPseudo(*SequenceMBBI)) {
9336       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9337           SequenceMBBI->getOperand(2).getReg() != RHS ||
9338           SequenceMBBI->getOperand(3).getImm() != CC ||
9339           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9340           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9341         break;
9342       LastSelectPseudo = &*SequenceMBBI;
9343       SequenceMBBI->collectDebugValues(SelectDebugValues);
9344       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9345     } else {
9346       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9347           SequenceMBBI->mayLoadOrStore())
9348         break;
9349       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9350             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9351           }))
9352         break;
9353     }
9354   }
9355 
9356   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9357   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9358   DebugLoc DL = MI.getDebugLoc();
9359   MachineFunction::iterator I = ++BB->getIterator();
9360 
9361   MachineBasicBlock *HeadMBB = BB;
9362   MachineFunction *F = BB->getParent();
9363   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9364   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9365 
9366   F->insert(I, IfFalseMBB);
9367   F->insert(I, TailMBB);
9368 
9369   // Transfer debug instructions associated with the selects to TailMBB.
9370   for (MachineInstr *DebugInstr : SelectDebugValues) {
9371     TailMBB->push_back(DebugInstr->removeFromParent());
9372   }
9373 
9374   // Move all instructions after the sequence to TailMBB.
9375   TailMBB->splice(TailMBB->end(), HeadMBB,
9376                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9377   // Update machine-CFG edges by transferring all successors of the current
9378   // block to the new block which will contain the Phi nodes for the selects.
9379   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9380   // Set the successors for HeadMBB.
9381   HeadMBB->addSuccessor(IfFalseMBB);
9382   HeadMBB->addSuccessor(TailMBB);
9383 
9384   // Insert appropriate branch.
9385   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9386     .addReg(LHS)
9387     .addReg(RHS)
9388     .addMBB(TailMBB);
9389 
9390   // IfFalseMBB just falls through to TailMBB.
9391   IfFalseMBB->addSuccessor(TailMBB);
9392 
9393   // Create PHIs for all of the select pseudo-instructions.
9394   auto SelectMBBI = MI.getIterator();
9395   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9396   auto InsertionPoint = TailMBB->begin();
9397   while (SelectMBBI != SelectEnd) {
9398     auto Next = std::next(SelectMBBI);
9399     if (isSelectPseudo(*SelectMBBI)) {
9400       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9401       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9402               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9403           .addReg(SelectMBBI->getOperand(4).getReg())
9404           .addMBB(HeadMBB)
9405           .addReg(SelectMBBI->getOperand(5).getReg())
9406           .addMBB(IfFalseMBB);
9407       SelectMBBI->eraseFromParent();
9408     }
9409     SelectMBBI = Next;
9410   }
9411 
9412   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9413   return TailMBB;
9414 }
9415 
9416 MachineBasicBlock *
9417 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9418                                                  MachineBasicBlock *BB) const {
9419   switch (MI.getOpcode()) {
9420   default:
9421     llvm_unreachable("Unexpected instr type to insert");
9422   case RISCV::ReadCycleWide:
9423     assert(!Subtarget.is64Bit() &&
9424            "ReadCycleWrite is only to be used on riscv32");
9425     return emitReadCycleWidePseudo(MI, BB);
9426   case RISCV::Select_GPR_Using_CC_GPR:
9427   case RISCV::Select_FPR16_Using_CC_GPR:
9428   case RISCV::Select_FPR32_Using_CC_GPR:
9429   case RISCV::Select_FPR64_Using_CC_GPR:
9430     return emitSelectPseudo(MI, BB, Subtarget);
9431   case RISCV::BuildPairF64Pseudo:
9432     return emitBuildPairF64Pseudo(MI, BB);
9433   case RISCV::SplitF64Pseudo:
9434     return emitSplitF64Pseudo(MI, BB);
9435   case RISCV::PseudoQuietFLE_H:
9436     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9437   case RISCV::PseudoQuietFLT_H:
9438     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9439   case RISCV::PseudoQuietFLE_S:
9440     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9441   case RISCV::PseudoQuietFLT_S:
9442     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9443   case RISCV::PseudoQuietFLE_D:
9444     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9445   case RISCV::PseudoQuietFLT_D:
9446     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9447   }
9448 }
9449 
9450 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9451                                                         SDNode *Node) const {
9452   // Add FRM dependency to any instructions with dynamic rounding mode.
9453   unsigned Opc = MI.getOpcode();
9454   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9455   if (Idx < 0)
9456     return;
9457   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9458     return;
9459   // If the instruction already reads FRM, don't add another read.
9460   if (MI.readsRegister(RISCV::FRM))
9461     return;
9462   MI.addOperand(
9463       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9464 }
9465 
9466 // Calling Convention Implementation.
9467 // The expectations for frontend ABI lowering vary from target to target.
9468 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9469 // details, but this is a longer term goal. For now, we simply try to keep the
9470 // role of the frontend as simple and well-defined as possible. The rules can
9471 // be summarised as:
9472 // * Never split up large scalar arguments. We handle them here.
9473 // * If a hardfloat calling convention is being used, and the struct may be
9474 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9475 // available, then pass as two separate arguments. If either the GPRs or FPRs
9476 // are exhausted, then pass according to the rule below.
9477 // * If a struct could never be passed in registers or directly in a stack
9478 // slot (as it is larger than 2*XLEN and the floating point rules don't
9479 // apply), then pass it using a pointer with the byval attribute.
9480 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9481 // word-sized array or a 2*XLEN scalar (depending on alignment).
9482 // * The frontend can determine whether a struct is returned by reference or
9483 // not based on its size and fields. If it will be returned by reference, the
9484 // frontend must modify the prototype so a pointer with the sret annotation is
9485 // passed as the first argument. This is not necessary for large scalar
9486 // returns.
9487 // * Struct return values and varargs should be coerced to structs containing
9488 // register-size fields in the same situations they would be for fixed
9489 // arguments.
9490 
9491 static const MCPhysReg ArgGPRs[] = {
9492   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9493   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9494 };
9495 static const MCPhysReg ArgFPR16s[] = {
9496   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9497   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9498 };
9499 static const MCPhysReg ArgFPR32s[] = {
9500   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9501   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9502 };
9503 static const MCPhysReg ArgFPR64s[] = {
9504   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9505   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9506 };
9507 // This is an interim calling convention and it may be changed in the future.
9508 static const MCPhysReg ArgVRs[] = {
9509     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9510     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9511     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9512 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9513                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9514                                      RISCV::V20M2, RISCV::V22M2};
9515 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9516                                      RISCV::V20M4};
9517 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9518 
9519 // Pass a 2*XLEN argument that has been split into two XLEN values through
9520 // registers or the stack as necessary.
9521 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9522                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9523                                 MVT ValVT2, MVT LocVT2,
9524                                 ISD::ArgFlagsTy ArgFlags2) {
9525   unsigned XLenInBytes = XLen / 8;
9526   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9527     // At least one half can be passed via register.
9528     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9529                                      VA1.getLocVT(), CCValAssign::Full));
9530   } else {
9531     // Both halves must be passed on the stack, with proper alignment.
9532     Align StackAlign =
9533         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9534     State.addLoc(
9535         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9536                             State.AllocateStack(XLenInBytes, StackAlign),
9537                             VA1.getLocVT(), CCValAssign::Full));
9538     State.addLoc(CCValAssign::getMem(
9539         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9540         LocVT2, CCValAssign::Full));
9541     return false;
9542   }
9543 
9544   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9545     // The second half can also be passed via register.
9546     State.addLoc(
9547         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9548   } else {
9549     // The second half is passed via the stack, without additional alignment.
9550     State.addLoc(CCValAssign::getMem(
9551         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9552         LocVT2, CCValAssign::Full));
9553   }
9554 
9555   return false;
9556 }
9557 
9558 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9559                                Optional<unsigned> FirstMaskArgument,
9560                                CCState &State, const RISCVTargetLowering &TLI) {
9561   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9562   if (RC == &RISCV::VRRegClass) {
9563     // Assign the first mask argument to V0.
9564     // This is an interim calling convention and it may be changed in the
9565     // future.
9566     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9567       return State.AllocateReg(RISCV::V0);
9568     return State.AllocateReg(ArgVRs);
9569   }
9570   if (RC == &RISCV::VRM2RegClass)
9571     return State.AllocateReg(ArgVRM2s);
9572   if (RC == &RISCV::VRM4RegClass)
9573     return State.AllocateReg(ArgVRM4s);
9574   if (RC == &RISCV::VRM8RegClass)
9575     return State.AllocateReg(ArgVRM8s);
9576   llvm_unreachable("Unhandled register class for ValueType");
9577 }
9578 
9579 // Implements the RISC-V calling convention. Returns true upon failure.
9580 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9581                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9582                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9583                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9584                      Optional<unsigned> FirstMaskArgument) {
9585   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9586   assert(XLen == 32 || XLen == 64);
9587   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9588 
9589   // Any return value split in to more than two values can't be returned
9590   // directly. Vectors are returned via the available vector registers.
9591   if (!LocVT.isVector() && IsRet && ValNo > 1)
9592     return true;
9593 
9594   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9595   // variadic argument, or if no F16/F32 argument registers are available.
9596   bool UseGPRForF16_F32 = true;
9597   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9598   // variadic argument, or if no F64 argument registers are available.
9599   bool UseGPRForF64 = true;
9600 
9601   switch (ABI) {
9602   default:
9603     llvm_unreachable("Unexpected ABI");
9604   case RISCVABI::ABI_ILP32:
9605   case RISCVABI::ABI_LP64:
9606     break;
9607   case RISCVABI::ABI_ILP32F:
9608   case RISCVABI::ABI_LP64F:
9609     UseGPRForF16_F32 = !IsFixed;
9610     break;
9611   case RISCVABI::ABI_ILP32D:
9612   case RISCVABI::ABI_LP64D:
9613     UseGPRForF16_F32 = !IsFixed;
9614     UseGPRForF64 = !IsFixed;
9615     break;
9616   }
9617 
9618   // FPR16, FPR32, and FPR64 alias each other.
9619   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9620     UseGPRForF16_F32 = true;
9621     UseGPRForF64 = true;
9622   }
9623 
9624   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9625   // similar local variables rather than directly checking against the target
9626   // ABI.
9627 
9628   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9629     LocVT = XLenVT;
9630     LocInfo = CCValAssign::BCvt;
9631   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9632     LocVT = MVT::i64;
9633     LocInfo = CCValAssign::BCvt;
9634   }
9635 
9636   // If this is a variadic argument, the RISC-V calling convention requires
9637   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9638   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9639   // be used regardless of whether the original argument was split during
9640   // legalisation or not. The argument will not be passed by registers if the
9641   // original type is larger than 2*XLEN, so the register alignment rule does
9642   // not apply.
9643   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9644   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9645       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9646     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9647     // Skip 'odd' register if necessary.
9648     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9649       State.AllocateReg(ArgGPRs);
9650   }
9651 
9652   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9653   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9654       State.getPendingArgFlags();
9655 
9656   assert(PendingLocs.size() == PendingArgFlags.size() &&
9657          "PendingLocs and PendingArgFlags out of sync");
9658 
9659   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9660   // registers are exhausted.
9661   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9662     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9663            "Can't lower f64 if it is split");
9664     // Depending on available argument GPRS, f64 may be passed in a pair of
9665     // GPRs, split between a GPR and the stack, or passed completely on the
9666     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9667     // cases.
9668     Register Reg = State.AllocateReg(ArgGPRs);
9669     LocVT = MVT::i32;
9670     if (!Reg) {
9671       unsigned StackOffset = State.AllocateStack(8, Align(8));
9672       State.addLoc(
9673           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9674       return false;
9675     }
9676     if (!State.AllocateReg(ArgGPRs))
9677       State.AllocateStack(4, Align(4));
9678     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9679     return false;
9680   }
9681 
9682   // Fixed-length vectors are located in the corresponding scalable-vector
9683   // container types.
9684   if (ValVT.isFixedLengthVector())
9685     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9686 
9687   // Split arguments might be passed indirectly, so keep track of the pending
9688   // values. Split vectors are passed via a mix of registers and indirectly, so
9689   // treat them as we would any other argument.
9690   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9691     LocVT = XLenVT;
9692     LocInfo = CCValAssign::Indirect;
9693     PendingLocs.push_back(
9694         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9695     PendingArgFlags.push_back(ArgFlags);
9696     if (!ArgFlags.isSplitEnd()) {
9697       return false;
9698     }
9699   }
9700 
9701   // If the split argument only had two elements, it should be passed directly
9702   // in registers or on the stack.
9703   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9704       PendingLocs.size() <= 2) {
9705     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9706     // Apply the normal calling convention rules to the first half of the
9707     // split argument.
9708     CCValAssign VA = PendingLocs[0];
9709     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9710     PendingLocs.clear();
9711     PendingArgFlags.clear();
9712     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9713                                ArgFlags);
9714   }
9715 
9716   // Allocate to a register if possible, or else a stack slot.
9717   Register Reg;
9718   unsigned StoreSizeBytes = XLen / 8;
9719   Align StackAlign = Align(XLen / 8);
9720 
9721   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9722     Reg = State.AllocateReg(ArgFPR16s);
9723   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9724     Reg = State.AllocateReg(ArgFPR32s);
9725   else if (ValVT == MVT::f64 && !UseGPRForF64)
9726     Reg = State.AllocateReg(ArgFPR64s);
9727   else if (ValVT.isVector()) {
9728     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9729     if (!Reg) {
9730       // For return values, the vector must be passed fully via registers or
9731       // via the stack.
9732       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9733       // but we're using all of them.
9734       if (IsRet)
9735         return true;
9736       // Try using a GPR to pass the address
9737       if ((Reg = State.AllocateReg(ArgGPRs))) {
9738         LocVT = XLenVT;
9739         LocInfo = CCValAssign::Indirect;
9740       } else if (ValVT.isScalableVector()) {
9741         LocVT = XLenVT;
9742         LocInfo = CCValAssign::Indirect;
9743       } else {
9744         // Pass fixed-length vectors on the stack.
9745         LocVT = ValVT;
9746         StoreSizeBytes = ValVT.getStoreSize();
9747         // Align vectors to their element sizes, being careful for vXi1
9748         // vectors.
9749         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9750       }
9751     }
9752   } else {
9753     Reg = State.AllocateReg(ArgGPRs);
9754   }
9755 
9756   unsigned StackOffset =
9757       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9758 
9759   // If we reach this point and PendingLocs is non-empty, we must be at the
9760   // end of a split argument that must be passed indirectly.
9761   if (!PendingLocs.empty()) {
9762     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9763     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9764 
9765     for (auto &It : PendingLocs) {
9766       if (Reg)
9767         It.convertToReg(Reg);
9768       else
9769         It.convertToMem(StackOffset);
9770       State.addLoc(It);
9771     }
9772     PendingLocs.clear();
9773     PendingArgFlags.clear();
9774     return false;
9775   }
9776 
9777   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9778           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9779          "Expected an XLenVT or vector types at this stage");
9780 
9781   if (Reg) {
9782     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9783     return false;
9784   }
9785 
9786   // When a floating-point value is passed on the stack, no bit-conversion is
9787   // needed.
9788   if (ValVT.isFloatingPoint()) {
9789     LocVT = ValVT;
9790     LocInfo = CCValAssign::Full;
9791   }
9792   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9793   return false;
9794 }
9795 
9796 template <typename ArgTy>
9797 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9798   for (const auto &ArgIdx : enumerate(Args)) {
9799     MVT ArgVT = ArgIdx.value().VT;
9800     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9801       return ArgIdx.index();
9802   }
9803   return None;
9804 }
9805 
9806 void RISCVTargetLowering::analyzeInputArgs(
9807     MachineFunction &MF, CCState &CCInfo,
9808     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9809     RISCVCCAssignFn Fn) const {
9810   unsigned NumArgs = Ins.size();
9811   FunctionType *FType = MF.getFunction().getFunctionType();
9812 
9813   Optional<unsigned> FirstMaskArgument;
9814   if (Subtarget.hasVInstructions())
9815     FirstMaskArgument = preAssignMask(Ins);
9816 
9817   for (unsigned i = 0; i != NumArgs; ++i) {
9818     MVT ArgVT = Ins[i].VT;
9819     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9820 
9821     Type *ArgTy = nullptr;
9822     if (IsRet)
9823       ArgTy = FType->getReturnType();
9824     else if (Ins[i].isOrigArg())
9825       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9826 
9827     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9828     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9829            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9830            FirstMaskArgument)) {
9831       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9832                         << EVT(ArgVT).getEVTString() << '\n');
9833       llvm_unreachable(nullptr);
9834     }
9835   }
9836 }
9837 
9838 void RISCVTargetLowering::analyzeOutputArgs(
9839     MachineFunction &MF, CCState &CCInfo,
9840     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9841     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9842   unsigned NumArgs = Outs.size();
9843 
9844   Optional<unsigned> FirstMaskArgument;
9845   if (Subtarget.hasVInstructions())
9846     FirstMaskArgument = preAssignMask(Outs);
9847 
9848   for (unsigned i = 0; i != NumArgs; i++) {
9849     MVT ArgVT = Outs[i].VT;
9850     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9851     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9852 
9853     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9854     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9855            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9856            FirstMaskArgument)) {
9857       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9858                         << EVT(ArgVT).getEVTString() << "\n");
9859       llvm_unreachable(nullptr);
9860     }
9861   }
9862 }
9863 
9864 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9865 // values.
9866 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9867                                    const CCValAssign &VA, const SDLoc &DL,
9868                                    const RISCVSubtarget &Subtarget) {
9869   switch (VA.getLocInfo()) {
9870   default:
9871     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9872   case CCValAssign::Full:
9873     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9874       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9875     break;
9876   case CCValAssign::BCvt:
9877     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9878       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9879     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9880       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9881     else
9882       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9883     break;
9884   }
9885   return Val;
9886 }
9887 
9888 // The caller is responsible for loading the full value if the argument is
9889 // passed with CCValAssign::Indirect.
9890 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9891                                 const CCValAssign &VA, const SDLoc &DL,
9892                                 const RISCVTargetLowering &TLI) {
9893   MachineFunction &MF = DAG.getMachineFunction();
9894   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9895   EVT LocVT = VA.getLocVT();
9896   SDValue Val;
9897   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9898   Register VReg = RegInfo.createVirtualRegister(RC);
9899   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9900   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9901 
9902   if (VA.getLocInfo() == CCValAssign::Indirect)
9903     return Val;
9904 
9905   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9906 }
9907 
9908 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9909                                    const CCValAssign &VA, const SDLoc &DL,
9910                                    const RISCVSubtarget &Subtarget) {
9911   EVT LocVT = VA.getLocVT();
9912 
9913   switch (VA.getLocInfo()) {
9914   default:
9915     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9916   case CCValAssign::Full:
9917     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9918       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9919     break;
9920   case CCValAssign::BCvt:
9921     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9922       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9923     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9924       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9925     else
9926       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9927     break;
9928   }
9929   return Val;
9930 }
9931 
9932 // The caller is responsible for loading the full value if the argument is
9933 // passed with CCValAssign::Indirect.
9934 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9935                                 const CCValAssign &VA, const SDLoc &DL) {
9936   MachineFunction &MF = DAG.getMachineFunction();
9937   MachineFrameInfo &MFI = MF.getFrameInfo();
9938   EVT LocVT = VA.getLocVT();
9939   EVT ValVT = VA.getValVT();
9940   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9941   if (ValVT.isScalableVector()) {
9942     // When the value is a scalable vector, we save the pointer which points to
9943     // the scalable vector value in the stack. The ValVT will be the pointer
9944     // type, instead of the scalable vector type.
9945     ValVT = LocVT;
9946   }
9947   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9948                                  /*IsImmutable=*/true);
9949   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9950   SDValue Val;
9951 
9952   ISD::LoadExtType ExtType;
9953   switch (VA.getLocInfo()) {
9954   default:
9955     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9956   case CCValAssign::Full:
9957   case CCValAssign::Indirect:
9958   case CCValAssign::BCvt:
9959     ExtType = ISD::NON_EXTLOAD;
9960     break;
9961   }
9962   Val = DAG.getExtLoad(
9963       ExtType, DL, LocVT, Chain, FIN,
9964       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9965   return Val;
9966 }
9967 
9968 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9969                                        const CCValAssign &VA, const SDLoc &DL) {
9970   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9971          "Unexpected VA");
9972   MachineFunction &MF = DAG.getMachineFunction();
9973   MachineFrameInfo &MFI = MF.getFrameInfo();
9974   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9975 
9976   if (VA.isMemLoc()) {
9977     // f64 is passed on the stack.
9978     int FI =
9979         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9980     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9981     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9982                        MachinePointerInfo::getFixedStack(MF, FI));
9983   }
9984 
9985   assert(VA.isRegLoc() && "Expected register VA assignment");
9986 
9987   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9988   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9989   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9990   SDValue Hi;
9991   if (VA.getLocReg() == RISCV::X17) {
9992     // Second half of f64 is passed on the stack.
9993     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9994     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9995     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9996                      MachinePointerInfo::getFixedStack(MF, FI));
9997   } else {
9998     // Second half of f64 is passed in another GPR.
9999     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10000     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10001     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10002   }
10003   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10004 }
10005 
10006 // FastCC has less than 1% performance improvement for some particular
10007 // benchmark. But theoretically, it may has benenfit for some cases.
10008 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10009                             unsigned ValNo, MVT ValVT, MVT LocVT,
10010                             CCValAssign::LocInfo LocInfo,
10011                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10012                             bool IsFixed, bool IsRet, Type *OrigTy,
10013                             const RISCVTargetLowering &TLI,
10014                             Optional<unsigned> FirstMaskArgument) {
10015 
10016   // X5 and X6 might be used for save-restore libcall.
10017   static const MCPhysReg GPRList[] = {
10018       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10019       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10020       RISCV::X29, RISCV::X30, RISCV::X31};
10021 
10022   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10023     if (unsigned Reg = State.AllocateReg(GPRList)) {
10024       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10025       return false;
10026     }
10027   }
10028 
10029   if (LocVT == MVT::f16) {
10030     static const MCPhysReg FPR16List[] = {
10031         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10032         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10033         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10034         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10035     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10036       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10037       return false;
10038     }
10039   }
10040 
10041   if (LocVT == MVT::f32) {
10042     static const MCPhysReg FPR32List[] = {
10043         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10044         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10045         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10046         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10047     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10048       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10049       return false;
10050     }
10051   }
10052 
10053   if (LocVT == MVT::f64) {
10054     static const MCPhysReg FPR64List[] = {
10055         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10056         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10057         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10058         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10059     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10060       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10061       return false;
10062     }
10063   }
10064 
10065   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10066     unsigned Offset4 = State.AllocateStack(4, Align(4));
10067     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10068     return false;
10069   }
10070 
10071   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10072     unsigned Offset5 = State.AllocateStack(8, Align(8));
10073     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10074     return false;
10075   }
10076 
10077   if (LocVT.isVector()) {
10078     if (unsigned Reg =
10079             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10080       // Fixed-length vectors are located in the corresponding scalable-vector
10081       // container types.
10082       if (ValVT.isFixedLengthVector())
10083         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10084       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10085     } else {
10086       // Try and pass the address via a "fast" GPR.
10087       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10088         LocInfo = CCValAssign::Indirect;
10089         LocVT = TLI.getSubtarget().getXLenVT();
10090         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10091       } else if (ValVT.isFixedLengthVector()) {
10092         auto StackAlign =
10093             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10094         unsigned StackOffset =
10095             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10096         State.addLoc(
10097             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10098       } else {
10099         // Can't pass scalable vectors on the stack.
10100         return true;
10101       }
10102     }
10103 
10104     return false;
10105   }
10106 
10107   return true; // CC didn't match.
10108 }
10109 
10110 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10111                          CCValAssign::LocInfo LocInfo,
10112                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10113 
10114   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10115     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10116     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10117     static const MCPhysReg GPRList[] = {
10118         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10119         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10120     if (unsigned Reg = State.AllocateReg(GPRList)) {
10121       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10122       return false;
10123     }
10124   }
10125 
10126   if (LocVT == MVT::f32) {
10127     // Pass in STG registers: F1, ..., F6
10128     //                        fs0 ... fs5
10129     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10130                                           RISCV::F18_F, RISCV::F19_F,
10131                                           RISCV::F20_F, RISCV::F21_F};
10132     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10133       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10134       return false;
10135     }
10136   }
10137 
10138   if (LocVT == MVT::f64) {
10139     // Pass in STG registers: D1, ..., D6
10140     //                        fs6 ... fs11
10141     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10142                                           RISCV::F24_D, RISCV::F25_D,
10143                                           RISCV::F26_D, RISCV::F27_D};
10144     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10145       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10146       return false;
10147     }
10148   }
10149 
10150   report_fatal_error("No registers left in GHC calling convention");
10151   return true;
10152 }
10153 
10154 // Transform physical registers into virtual registers.
10155 SDValue RISCVTargetLowering::LowerFormalArguments(
10156     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10157     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10158     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10159 
10160   MachineFunction &MF = DAG.getMachineFunction();
10161 
10162   switch (CallConv) {
10163   default:
10164     report_fatal_error("Unsupported calling convention");
10165   case CallingConv::C:
10166   case CallingConv::Fast:
10167     break;
10168   case CallingConv::GHC:
10169     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10170         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10171       report_fatal_error(
10172         "GHC calling convention requires the F and D instruction set extensions");
10173   }
10174 
10175   const Function &Func = MF.getFunction();
10176   if (Func.hasFnAttribute("interrupt")) {
10177     if (!Func.arg_empty())
10178       report_fatal_error(
10179         "Functions with the interrupt attribute cannot have arguments!");
10180 
10181     StringRef Kind =
10182       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10183 
10184     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10185       report_fatal_error(
10186         "Function interrupt attribute argument not supported!");
10187   }
10188 
10189   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10190   MVT XLenVT = Subtarget.getXLenVT();
10191   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10192   // Used with vargs to acumulate store chains.
10193   std::vector<SDValue> OutChains;
10194 
10195   // Assign locations to all of the incoming arguments.
10196   SmallVector<CCValAssign, 16> ArgLocs;
10197   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10198 
10199   if (CallConv == CallingConv::GHC)
10200     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10201   else
10202     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10203                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10204                                                    : CC_RISCV);
10205 
10206   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10207     CCValAssign &VA = ArgLocs[i];
10208     SDValue ArgValue;
10209     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10210     // case.
10211     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10212       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10213     else if (VA.isRegLoc())
10214       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10215     else
10216       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10217 
10218     if (VA.getLocInfo() == CCValAssign::Indirect) {
10219       // If the original argument was split and passed by reference (e.g. i128
10220       // on RV32), we need to load all parts of it here (using the same
10221       // address). Vectors may be partly split to registers and partly to the
10222       // stack, in which case the base address is partly offset and subsequent
10223       // stores are relative to that.
10224       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10225                                    MachinePointerInfo()));
10226       unsigned ArgIndex = Ins[i].OrigArgIndex;
10227       unsigned ArgPartOffset = Ins[i].PartOffset;
10228       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10229       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10230         CCValAssign &PartVA = ArgLocs[i + 1];
10231         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10232         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10233         if (PartVA.getValVT().isScalableVector())
10234           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10235         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10236         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10237                                      MachinePointerInfo()));
10238         ++i;
10239       }
10240       continue;
10241     }
10242     InVals.push_back(ArgValue);
10243   }
10244 
10245   if (IsVarArg) {
10246     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10247     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10248     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10249     MachineFrameInfo &MFI = MF.getFrameInfo();
10250     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10251     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10252 
10253     // Offset of the first variable argument from stack pointer, and size of
10254     // the vararg save area. For now, the varargs save area is either zero or
10255     // large enough to hold a0-a7.
10256     int VaArgOffset, VarArgsSaveSize;
10257 
10258     // If all registers are allocated, then all varargs must be passed on the
10259     // stack and we don't need to save any argregs.
10260     if (ArgRegs.size() == Idx) {
10261       VaArgOffset = CCInfo.getNextStackOffset();
10262       VarArgsSaveSize = 0;
10263     } else {
10264       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10265       VaArgOffset = -VarArgsSaveSize;
10266     }
10267 
10268     // Record the frame index of the first variable argument
10269     // which is a value necessary to VASTART.
10270     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10271     RVFI->setVarArgsFrameIndex(FI);
10272 
10273     // If saving an odd number of registers then create an extra stack slot to
10274     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10275     // offsets to even-numbered registered remain 2*XLEN-aligned.
10276     if (Idx % 2) {
10277       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10278       VarArgsSaveSize += XLenInBytes;
10279     }
10280 
10281     // Copy the integer registers that may have been used for passing varargs
10282     // to the vararg save area.
10283     for (unsigned I = Idx; I < ArgRegs.size();
10284          ++I, VaArgOffset += XLenInBytes) {
10285       const Register Reg = RegInfo.createVirtualRegister(RC);
10286       RegInfo.addLiveIn(ArgRegs[I], Reg);
10287       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10288       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10289       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10290       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10291                                    MachinePointerInfo::getFixedStack(MF, FI));
10292       cast<StoreSDNode>(Store.getNode())
10293           ->getMemOperand()
10294           ->setValue((Value *)nullptr);
10295       OutChains.push_back(Store);
10296     }
10297     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10298   }
10299 
10300   // All stores are grouped in one node to allow the matching between
10301   // the size of Ins and InVals. This only happens for vararg functions.
10302   if (!OutChains.empty()) {
10303     OutChains.push_back(Chain);
10304     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10305   }
10306 
10307   return Chain;
10308 }
10309 
10310 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10311 /// for tail call optimization.
10312 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10313 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10314     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10315     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10316 
10317   auto &Callee = CLI.Callee;
10318   auto CalleeCC = CLI.CallConv;
10319   auto &Outs = CLI.Outs;
10320   auto &Caller = MF.getFunction();
10321   auto CallerCC = Caller.getCallingConv();
10322 
10323   // Exception-handling functions need a special set of instructions to
10324   // indicate a return to the hardware. Tail-calling another function would
10325   // probably break this.
10326   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10327   // should be expanded as new function attributes are introduced.
10328   if (Caller.hasFnAttribute("interrupt"))
10329     return false;
10330 
10331   // Do not tail call opt if the stack is used to pass parameters.
10332   if (CCInfo.getNextStackOffset() != 0)
10333     return false;
10334 
10335   // Do not tail call opt if any parameters need to be passed indirectly.
10336   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10337   // passed indirectly. So the address of the value will be passed in a
10338   // register, or if not available, then the address is put on the stack. In
10339   // order to pass indirectly, space on the stack often needs to be allocated
10340   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10341   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10342   // are passed CCValAssign::Indirect.
10343   for (auto &VA : ArgLocs)
10344     if (VA.getLocInfo() == CCValAssign::Indirect)
10345       return false;
10346 
10347   // Do not tail call opt if either caller or callee uses struct return
10348   // semantics.
10349   auto IsCallerStructRet = Caller.hasStructRetAttr();
10350   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10351   if (IsCallerStructRet || IsCalleeStructRet)
10352     return false;
10353 
10354   // Externally-defined functions with weak linkage should not be
10355   // tail-called. The behaviour of branch instructions in this situation (as
10356   // used for tail calls) is implementation-defined, so we cannot rely on the
10357   // linker replacing the tail call with a return.
10358   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10359     const GlobalValue *GV = G->getGlobal();
10360     if (GV->hasExternalWeakLinkage())
10361       return false;
10362   }
10363 
10364   // The callee has to preserve all registers the caller needs to preserve.
10365   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10366   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10367   if (CalleeCC != CallerCC) {
10368     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10369     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10370       return false;
10371   }
10372 
10373   // Byval parameters hand the function a pointer directly into the stack area
10374   // we want to reuse during a tail call. Working around this *is* possible
10375   // but less efficient and uglier in LowerCall.
10376   for (auto &Arg : Outs)
10377     if (Arg.Flags.isByVal())
10378       return false;
10379 
10380   return true;
10381 }
10382 
10383 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10384   return DAG.getDataLayout().getPrefTypeAlign(
10385       VT.getTypeForEVT(*DAG.getContext()));
10386 }
10387 
10388 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10389 // and output parameter nodes.
10390 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10391                                        SmallVectorImpl<SDValue> &InVals) const {
10392   SelectionDAG &DAG = CLI.DAG;
10393   SDLoc &DL = CLI.DL;
10394   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10395   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10396   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10397   SDValue Chain = CLI.Chain;
10398   SDValue Callee = CLI.Callee;
10399   bool &IsTailCall = CLI.IsTailCall;
10400   CallingConv::ID CallConv = CLI.CallConv;
10401   bool IsVarArg = CLI.IsVarArg;
10402   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10403   MVT XLenVT = Subtarget.getXLenVT();
10404 
10405   MachineFunction &MF = DAG.getMachineFunction();
10406 
10407   // Analyze the operands of the call, assigning locations to each operand.
10408   SmallVector<CCValAssign, 16> ArgLocs;
10409   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10410 
10411   if (CallConv == CallingConv::GHC)
10412     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10413   else
10414     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10415                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10416                                                     : CC_RISCV);
10417 
10418   // Check if it's really possible to do a tail call.
10419   if (IsTailCall)
10420     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10421 
10422   if (IsTailCall)
10423     ++NumTailCalls;
10424   else if (CLI.CB && CLI.CB->isMustTailCall())
10425     report_fatal_error("failed to perform tail call elimination on a call "
10426                        "site marked musttail");
10427 
10428   // Get a count of how many bytes are to be pushed on the stack.
10429   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10430 
10431   // Create local copies for byval args
10432   SmallVector<SDValue, 8> ByValArgs;
10433   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10434     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10435     if (!Flags.isByVal())
10436       continue;
10437 
10438     SDValue Arg = OutVals[i];
10439     unsigned Size = Flags.getByValSize();
10440     Align Alignment = Flags.getNonZeroByValAlign();
10441 
10442     int FI =
10443         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10444     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10445     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10446 
10447     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10448                           /*IsVolatile=*/false,
10449                           /*AlwaysInline=*/false, IsTailCall,
10450                           MachinePointerInfo(), MachinePointerInfo());
10451     ByValArgs.push_back(FIPtr);
10452   }
10453 
10454   if (!IsTailCall)
10455     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10456 
10457   // Copy argument values to their designated locations.
10458   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10459   SmallVector<SDValue, 8> MemOpChains;
10460   SDValue StackPtr;
10461   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10462     CCValAssign &VA = ArgLocs[i];
10463     SDValue ArgValue = OutVals[i];
10464     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10465 
10466     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10467     bool IsF64OnRV32DSoftABI =
10468         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10469     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10470       SDValue SplitF64 = DAG.getNode(
10471           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10472       SDValue Lo = SplitF64.getValue(0);
10473       SDValue Hi = SplitF64.getValue(1);
10474 
10475       Register RegLo = VA.getLocReg();
10476       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10477 
10478       if (RegLo == RISCV::X17) {
10479         // Second half of f64 is passed on the stack.
10480         // Work out the address of the stack slot.
10481         if (!StackPtr.getNode())
10482           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10483         // Emit the store.
10484         MemOpChains.push_back(
10485             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10486       } else {
10487         // Second half of f64 is passed in another GPR.
10488         assert(RegLo < RISCV::X31 && "Invalid register pair");
10489         Register RegHigh = RegLo + 1;
10490         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10491       }
10492       continue;
10493     }
10494 
10495     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10496     // as any other MemLoc.
10497 
10498     // Promote the value if needed.
10499     // For now, only handle fully promoted and indirect arguments.
10500     if (VA.getLocInfo() == CCValAssign::Indirect) {
10501       // Store the argument in a stack slot and pass its address.
10502       Align StackAlign =
10503           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10504                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10505       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10506       // If the original argument was split (e.g. i128), we need
10507       // to store the required parts of it here (and pass just one address).
10508       // Vectors may be partly split to registers and partly to the stack, in
10509       // which case the base address is partly offset and subsequent stores are
10510       // relative to that.
10511       unsigned ArgIndex = Outs[i].OrigArgIndex;
10512       unsigned ArgPartOffset = Outs[i].PartOffset;
10513       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10514       // Calculate the total size to store. We don't have access to what we're
10515       // actually storing other than performing the loop and collecting the
10516       // info.
10517       SmallVector<std::pair<SDValue, SDValue>> Parts;
10518       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10519         SDValue PartValue = OutVals[i + 1];
10520         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10521         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10522         EVT PartVT = PartValue.getValueType();
10523         if (PartVT.isScalableVector())
10524           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10525         StoredSize += PartVT.getStoreSize();
10526         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10527         Parts.push_back(std::make_pair(PartValue, Offset));
10528         ++i;
10529       }
10530       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10531       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10532       MemOpChains.push_back(
10533           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10534                        MachinePointerInfo::getFixedStack(MF, FI)));
10535       for (const auto &Part : Parts) {
10536         SDValue PartValue = Part.first;
10537         SDValue PartOffset = Part.second;
10538         SDValue Address =
10539             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10540         MemOpChains.push_back(
10541             DAG.getStore(Chain, DL, PartValue, Address,
10542                          MachinePointerInfo::getFixedStack(MF, FI)));
10543       }
10544       ArgValue = SpillSlot;
10545     } else {
10546       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10547     }
10548 
10549     // Use local copy if it is a byval arg.
10550     if (Flags.isByVal())
10551       ArgValue = ByValArgs[j++];
10552 
10553     if (VA.isRegLoc()) {
10554       // Queue up the argument copies and emit them at the end.
10555       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10556     } else {
10557       assert(VA.isMemLoc() && "Argument not register or memory");
10558       assert(!IsTailCall && "Tail call not allowed if stack is used "
10559                             "for passing parameters");
10560 
10561       // Work out the address of the stack slot.
10562       if (!StackPtr.getNode())
10563         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10564       SDValue Address =
10565           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10566                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10567 
10568       // Emit the store.
10569       MemOpChains.push_back(
10570           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10571     }
10572   }
10573 
10574   // Join the stores, which are independent of one another.
10575   if (!MemOpChains.empty())
10576     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10577 
10578   SDValue Glue;
10579 
10580   // Build a sequence of copy-to-reg nodes, chained and glued together.
10581   for (auto &Reg : RegsToPass) {
10582     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10583     Glue = Chain.getValue(1);
10584   }
10585 
10586   // Validate that none of the argument registers have been marked as
10587   // reserved, if so report an error. Do the same for the return address if this
10588   // is not a tailcall.
10589   validateCCReservedRegs(RegsToPass, MF);
10590   if (!IsTailCall &&
10591       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10592     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10593         MF.getFunction(),
10594         "Return address register required, but has been reserved."});
10595 
10596   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10597   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10598   // split it and then direct call can be matched by PseudoCALL.
10599   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10600     const GlobalValue *GV = S->getGlobal();
10601 
10602     unsigned OpFlags = RISCVII::MO_CALL;
10603     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10604       OpFlags = RISCVII::MO_PLT;
10605 
10606     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10607   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10608     unsigned OpFlags = RISCVII::MO_CALL;
10609 
10610     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10611                                                  nullptr))
10612       OpFlags = RISCVII::MO_PLT;
10613 
10614     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10615   }
10616 
10617   // The first call operand is the chain and the second is the target address.
10618   SmallVector<SDValue, 8> Ops;
10619   Ops.push_back(Chain);
10620   Ops.push_back(Callee);
10621 
10622   // Add argument registers to the end of the list so that they are
10623   // known live into the call.
10624   for (auto &Reg : RegsToPass)
10625     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10626 
10627   if (!IsTailCall) {
10628     // Add a register mask operand representing the call-preserved registers.
10629     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10630     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10631     assert(Mask && "Missing call preserved mask for calling convention");
10632     Ops.push_back(DAG.getRegisterMask(Mask));
10633   }
10634 
10635   // Glue the call to the argument copies, if any.
10636   if (Glue.getNode())
10637     Ops.push_back(Glue);
10638 
10639   // Emit the call.
10640   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10641 
10642   if (IsTailCall) {
10643     MF.getFrameInfo().setHasTailCall();
10644     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10645   }
10646 
10647   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10648   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10649   Glue = Chain.getValue(1);
10650 
10651   // Mark the end of the call, which is glued to the call itself.
10652   Chain = DAG.getCALLSEQ_END(Chain,
10653                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10654                              DAG.getConstant(0, DL, PtrVT, true),
10655                              Glue, DL);
10656   Glue = Chain.getValue(1);
10657 
10658   // Assign locations to each value returned by this call.
10659   SmallVector<CCValAssign, 16> RVLocs;
10660   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10661   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10662 
10663   // Copy all of the result registers out of their specified physreg.
10664   for (auto &VA : RVLocs) {
10665     // Copy the value out
10666     SDValue RetValue =
10667         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10668     // Glue the RetValue to the end of the call sequence
10669     Chain = RetValue.getValue(1);
10670     Glue = RetValue.getValue(2);
10671 
10672     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10673       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10674       SDValue RetValue2 =
10675           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10676       Chain = RetValue2.getValue(1);
10677       Glue = RetValue2.getValue(2);
10678       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10679                              RetValue2);
10680     }
10681 
10682     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10683 
10684     InVals.push_back(RetValue);
10685   }
10686 
10687   return Chain;
10688 }
10689 
10690 bool RISCVTargetLowering::CanLowerReturn(
10691     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10692     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10693   SmallVector<CCValAssign, 16> RVLocs;
10694   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10695 
10696   Optional<unsigned> FirstMaskArgument;
10697   if (Subtarget.hasVInstructions())
10698     FirstMaskArgument = preAssignMask(Outs);
10699 
10700   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10701     MVT VT = Outs[i].VT;
10702     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10703     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10704     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10705                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10706                  *this, FirstMaskArgument))
10707       return false;
10708   }
10709   return true;
10710 }
10711 
10712 SDValue
10713 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10714                                  bool IsVarArg,
10715                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10716                                  const SmallVectorImpl<SDValue> &OutVals,
10717                                  const SDLoc &DL, SelectionDAG &DAG) const {
10718   const MachineFunction &MF = DAG.getMachineFunction();
10719   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10720 
10721   // Stores the assignment of the return value to a location.
10722   SmallVector<CCValAssign, 16> RVLocs;
10723 
10724   // Info about the registers and stack slot.
10725   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10726                  *DAG.getContext());
10727 
10728   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10729                     nullptr, CC_RISCV);
10730 
10731   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10732     report_fatal_error("GHC functions return void only");
10733 
10734   SDValue Glue;
10735   SmallVector<SDValue, 4> RetOps(1, Chain);
10736 
10737   // Copy the result values into the output registers.
10738   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10739     SDValue Val = OutVals[i];
10740     CCValAssign &VA = RVLocs[i];
10741     assert(VA.isRegLoc() && "Can only return in registers!");
10742 
10743     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10744       // Handle returning f64 on RV32D with a soft float ABI.
10745       assert(VA.isRegLoc() && "Expected return via registers");
10746       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10747                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10748       SDValue Lo = SplitF64.getValue(0);
10749       SDValue Hi = SplitF64.getValue(1);
10750       Register RegLo = VA.getLocReg();
10751       assert(RegLo < RISCV::X31 && "Invalid register pair");
10752       Register RegHi = RegLo + 1;
10753 
10754       if (STI.isRegisterReservedByUser(RegLo) ||
10755           STI.isRegisterReservedByUser(RegHi))
10756         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10757             MF.getFunction(),
10758             "Return value register required, but has been reserved."});
10759 
10760       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10761       Glue = Chain.getValue(1);
10762       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10763       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10764       Glue = Chain.getValue(1);
10765       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10766     } else {
10767       // Handle a 'normal' return.
10768       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10769       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10770 
10771       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10772         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10773             MF.getFunction(),
10774             "Return value register required, but has been reserved."});
10775 
10776       // Guarantee that all emitted copies are stuck together.
10777       Glue = Chain.getValue(1);
10778       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10779     }
10780   }
10781 
10782   RetOps[0] = Chain; // Update chain.
10783 
10784   // Add the glue node if we have it.
10785   if (Glue.getNode()) {
10786     RetOps.push_back(Glue);
10787   }
10788 
10789   unsigned RetOpc = RISCVISD::RET_FLAG;
10790   // Interrupt service routines use different return instructions.
10791   const Function &Func = DAG.getMachineFunction().getFunction();
10792   if (Func.hasFnAttribute("interrupt")) {
10793     if (!Func.getReturnType()->isVoidTy())
10794       report_fatal_error(
10795           "Functions with the interrupt attribute must have void return type!");
10796 
10797     MachineFunction &MF = DAG.getMachineFunction();
10798     StringRef Kind =
10799       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10800 
10801     if (Kind == "user")
10802       RetOpc = RISCVISD::URET_FLAG;
10803     else if (Kind == "supervisor")
10804       RetOpc = RISCVISD::SRET_FLAG;
10805     else
10806       RetOpc = RISCVISD::MRET_FLAG;
10807   }
10808 
10809   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10810 }
10811 
10812 void RISCVTargetLowering::validateCCReservedRegs(
10813     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10814     MachineFunction &MF) const {
10815   const Function &F = MF.getFunction();
10816   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10817 
10818   if (llvm::any_of(Regs, [&STI](auto Reg) {
10819         return STI.isRegisterReservedByUser(Reg.first);
10820       }))
10821     F.getContext().diagnose(DiagnosticInfoUnsupported{
10822         F, "Argument register required, but has been reserved."});
10823 }
10824 
10825 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10826   return CI->isTailCall();
10827 }
10828 
10829 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10830 #define NODE_NAME_CASE(NODE)                                                   \
10831   case RISCVISD::NODE:                                                         \
10832     return "RISCVISD::" #NODE;
10833   // clang-format off
10834   switch ((RISCVISD::NodeType)Opcode) {
10835   case RISCVISD::FIRST_NUMBER:
10836     break;
10837   NODE_NAME_CASE(RET_FLAG)
10838   NODE_NAME_CASE(URET_FLAG)
10839   NODE_NAME_CASE(SRET_FLAG)
10840   NODE_NAME_CASE(MRET_FLAG)
10841   NODE_NAME_CASE(CALL)
10842   NODE_NAME_CASE(SELECT_CC)
10843   NODE_NAME_CASE(BR_CC)
10844   NODE_NAME_CASE(BuildPairF64)
10845   NODE_NAME_CASE(SplitF64)
10846   NODE_NAME_CASE(TAIL)
10847   NODE_NAME_CASE(MULHSU)
10848   NODE_NAME_CASE(SLLW)
10849   NODE_NAME_CASE(SRAW)
10850   NODE_NAME_CASE(SRLW)
10851   NODE_NAME_CASE(DIVW)
10852   NODE_NAME_CASE(DIVUW)
10853   NODE_NAME_CASE(REMUW)
10854   NODE_NAME_CASE(ROLW)
10855   NODE_NAME_CASE(RORW)
10856   NODE_NAME_CASE(CLZW)
10857   NODE_NAME_CASE(CTZW)
10858   NODE_NAME_CASE(FSLW)
10859   NODE_NAME_CASE(FSRW)
10860   NODE_NAME_CASE(FSL)
10861   NODE_NAME_CASE(FSR)
10862   NODE_NAME_CASE(FMV_H_X)
10863   NODE_NAME_CASE(FMV_X_ANYEXTH)
10864   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10865   NODE_NAME_CASE(FMV_W_X_RV64)
10866   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10867   NODE_NAME_CASE(FCVT_X)
10868   NODE_NAME_CASE(FCVT_XU)
10869   NODE_NAME_CASE(FCVT_W_RV64)
10870   NODE_NAME_CASE(FCVT_WU_RV64)
10871   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10872   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10873   NODE_NAME_CASE(READ_CYCLE_WIDE)
10874   NODE_NAME_CASE(GREV)
10875   NODE_NAME_CASE(GREVW)
10876   NODE_NAME_CASE(GORC)
10877   NODE_NAME_CASE(GORCW)
10878   NODE_NAME_CASE(SHFL)
10879   NODE_NAME_CASE(SHFLW)
10880   NODE_NAME_CASE(UNSHFL)
10881   NODE_NAME_CASE(UNSHFLW)
10882   NODE_NAME_CASE(BFP)
10883   NODE_NAME_CASE(BFPW)
10884   NODE_NAME_CASE(BCOMPRESS)
10885   NODE_NAME_CASE(BCOMPRESSW)
10886   NODE_NAME_CASE(BDECOMPRESS)
10887   NODE_NAME_CASE(BDECOMPRESSW)
10888   NODE_NAME_CASE(VMV_V_X_VL)
10889   NODE_NAME_CASE(VFMV_V_F_VL)
10890   NODE_NAME_CASE(VMV_X_S)
10891   NODE_NAME_CASE(VMV_S_X_VL)
10892   NODE_NAME_CASE(VFMV_S_F_VL)
10893   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10894   NODE_NAME_CASE(READ_VLENB)
10895   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10896   NODE_NAME_CASE(VSLIDEUP_VL)
10897   NODE_NAME_CASE(VSLIDE1UP_VL)
10898   NODE_NAME_CASE(VSLIDEDOWN_VL)
10899   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10900   NODE_NAME_CASE(VID_VL)
10901   NODE_NAME_CASE(VFNCVT_ROD_VL)
10902   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10903   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10904   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10905   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10906   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10907   NODE_NAME_CASE(VECREDUCE_AND_VL)
10908   NODE_NAME_CASE(VECREDUCE_OR_VL)
10909   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10910   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10911   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10912   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10913   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10914   NODE_NAME_CASE(ADD_VL)
10915   NODE_NAME_CASE(AND_VL)
10916   NODE_NAME_CASE(MUL_VL)
10917   NODE_NAME_CASE(OR_VL)
10918   NODE_NAME_CASE(SDIV_VL)
10919   NODE_NAME_CASE(SHL_VL)
10920   NODE_NAME_CASE(SREM_VL)
10921   NODE_NAME_CASE(SRA_VL)
10922   NODE_NAME_CASE(SRL_VL)
10923   NODE_NAME_CASE(SUB_VL)
10924   NODE_NAME_CASE(UDIV_VL)
10925   NODE_NAME_CASE(UREM_VL)
10926   NODE_NAME_CASE(XOR_VL)
10927   NODE_NAME_CASE(SADDSAT_VL)
10928   NODE_NAME_CASE(UADDSAT_VL)
10929   NODE_NAME_CASE(SSUBSAT_VL)
10930   NODE_NAME_CASE(USUBSAT_VL)
10931   NODE_NAME_CASE(FADD_VL)
10932   NODE_NAME_CASE(FSUB_VL)
10933   NODE_NAME_CASE(FMUL_VL)
10934   NODE_NAME_CASE(FDIV_VL)
10935   NODE_NAME_CASE(FNEG_VL)
10936   NODE_NAME_CASE(FABS_VL)
10937   NODE_NAME_CASE(FSQRT_VL)
10938   NODE_NAME_CASE(FMA_VL)
10939   NODE_NAME_CASE(FCOPYSIGN_VL)
10940   NODE_NAME_CASE(SMIN_VL)
10941   NODE_NAME_CASE(SMAX_VL)
10942   NODE_NAME_CASE(UMIN_VL)
10943   NODE_NAME_CASE(UMAX_VL)
10944   NODE_NAME_CASE(FMINNUM_VL)
10945   NODE_NAME_CASE(FMAXNUM_VL)
10946   NODE_NAME_CASE(MULHS_VL)
10947   NODE_NAME_CASE(MULHU_VL)
10948   NODE_NAME_CASE(FP_TO_SINT_VL)
10949   NODE_NAME_CASE(FP_TO_UINT_VL)
10950   NODE_NAME_CASE(SINT_TO_FP_VL)
10951   NODE_NAME_CASE(UINT_TO_FP_VL)
10952   NODE_NAME_CASE(FP_EXTEND_VL)
10953   NODE_NAME_CASE(FP_ROUND_VL)
10954   NODE_NAME_CASE(VWMUL_VL)
10955   NODE_NAME_CASE(VWMULU_VL)
10956   NODE_NAME_CASE(VWMULSU_VL)
10957   NODE_NAME_CASE(VWADD_VL)
10958   NODE_NAME_CASE(VWADDU_VL)
10959   NODE_NAME_CASE(VWSUB_VL)
10960   NODE_NAME_CASE(VWSUBU_VL)
10961   NODE_NAME_CASE(VWADD_W_VL)
10962   NODE_NAME_CASE(VWADDU_W_VL)
10963   NODE_NAME_CASE(VWSUB_W_VL)
10964   NODE_NAME_CASE(VWSUBU_W_VL)
10965   NODE_NAME_CASE(SETCC_VL)
10966   NODE_NAME_CASE(VSELECT_VL)
10967   NODE_NAME_CASE(VP_MERGE_VL)
10968   NODE_NAME_CASE(VMAND_VL)
10969   NODE_NAME_CASE(VMOR_VL)
10970   NODE_NAME_CASE(VMXOR_VL)
10971   NODE_NAME_CASE(VMCLR_VL)
10972   NODE_NAME_CASE(VMSET_VL)
10973   NODE_NAME_CASE(VRGATHER_VX_VL)
10974   NODE_NAME_CASE(VRGATHER_VV_VL)
10975   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10976   NODE_NAME_CASE(VSEXT_VL)
10977   NODE_NAME_CASE(VZEXT_VL)
10978   NODE_NAME_CASE(VCPOP_VL)
10979   NODE_NAME_CASE(READ_CSR)
10980   NODE_NAME_CASE(WRITE_CSR)
10981   NODE_NAME_CASE(SWAP_CSR)
10982   }
10983   // clang-format on
10984   return nullptr;
10985 #undef NODE_NAME_CASE
10986 }
10987 
10988 /// getConstraintType - Given a constraint letter, return the type of
10989 /// constraint it is for this target.
10990 RISCVTargetLowering::ConstraintType
10991 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10992   if (Constraint.size() == 1) {
10993     switch (Constraint[0]) {
10994     default:
10995       break;
10996     case 'f':
10997       return C_RegisterClass;
10998     case 'I':
10999     case 'J':
11000     case 'K':
11001       return C_Immediate;
11002     case 'A':
11003       return C_Memory;
11004     case 'S': // A symbolic address
11005       return C_Other;
11006     }
11007   } else {
11008     if (Constraint == "vr" || Constraint == "vm")
11009       return C_RegisterClass;
11010   }
11011   return TargetLowering::getConstraintType(Constraint);
11012 }
11013 
11014 std::pair<unsigned, const TargetRegisterClass *>
11015 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11016                                                   StringRef Constraint,
11017                                                   MVT VT) const {
11018   // First, see if this is a constraint that directly corresponds to a
11019   // RISCV register class.
11020   if (Constraint.size() == 1) {
11021     switch (Constraint[0]) {
11022     case 'r':
11023       // TODO: Support fixed vectors up to XLen for P extension?
11024       if (VT.isVector())
11025         break;
11026       return std::make_pair(0U, &RISCV::GPRRegClass);
11027     case 'f':
11028       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11029         return std::make_pair(0U, &RISCV::FPR16RegClass);
11030       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11031         return std::make_pair(0U, &RISCV::FPR32RegClass);
11032       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11033         return std::make_pair(0U, &RISCV::FPR64RegClass);
11034       break;
11035     default:
11036       break;
11037     }
11038   } else if (Constraint == "vr") {
11039     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11040                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11041       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11042         return std::make_pair(0U, RC);
11043     }
11044   } else if (Constraint == "vm") {
11045     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11046       return std::make_pair(0U, &RISCV::VMV0RegClass);
11047   }
11048 
11049   // Clang will correctly decode the usage of register name aliases into their
11050   // official names. However, other frontends like `rustc` do not. This allows
11051   // users of these frontends to use the ABI names for registers in LLVM-style
11052   // register constraints.
11053   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11054                                .Case("{zero}", RISCV::X0)
11055                                .Case("{ra}", RISCV::X1)
11056                                .Case("{sp}", RISCV::X2)
11057                                .Case("{gp}", RISCV::X3)
11058                                .Case("{tp}", RISCV::X4)
11059                                .Case("{t0}", RISCV::X5)
11060                                .Case("{t1}", RISCV::X6)
11061                                .Case("{t2}", RISCV::X7)
11062                                .Cases("{s0}", "{fp}", RISCV::X8)
11063                                .Case("{s1}", RISCV::X9)
11064                                .Case("{a0}", RISCV::X10)
11065                                .Case("{a1}", RISCV::X11)
11066                                .Case("{a2}", RISCV::X12)
11067                                .Case("{a3}", RISCV::X13)
11068                                .Case("{a4}", RISCV::X14)
11069                                .Case("{a5}", RISCV::X15)
11070                                .Case("{a6}", RISCV::X16)
11071                                .Case("{a7}", RISCV::X17)
11072                                .Case("{s2}", RISCV::X18)
11073                                .Case("{s3}", RISCV::X19)
11074                                .Case("{s4}", RISCV::X20)
11075                                .Case("{s5}", RISCV::X21)
11076                                .Case("{s6}", RISCV::X22)
11077                                .Case("{s7}", RISCV::X23)
11078                                .Case("{s8}", RISCV::X24)
11079                                .Case("{s9}", RISCV::X25)
11080                                .Case("{s10}", RISCV::X26)
11081                                .Case("{s11}", RISCV::X27)
11082                                .Case("{t3}", RISCV::X28)
11083                                .Case("{t4}", RISCV::X29)
11084                                .Case("{t5}", RISCV::X30)
11085                                .Case("{t6}", RISCV::X31)
11086                                .Default(RISCV::NoRegister);
11087   if (XRegFromAlias != RISCV::NoRegister)
11088     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11089 
11090   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11091   // TableGen record rather than the AsmName to choose registers for InlineAsm
11092   // constraints, plus we want to match those names to the widest floating point
11093   // register type available, manually select floating point registers here.
11094   //
11095   // The second case is the ABI name of the register, so that frontends can also
11096   // use the ABI names in register constraint lists.
11097   if (Subtarget.hasStdExtF()) {
11098     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11099                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11100                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11101                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11102                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11103                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11104                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11105                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11106                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11107                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11108                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11109                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11110                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11111                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11112                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11113                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11114                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11115                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11116                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11117                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11118                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11119                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11120                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11121                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11122                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11123                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11124                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11125                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11126                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11127                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11128                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11129                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11130                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11131                         .Default(RISCV::NoRegister);
11132     if (FReg != RISCV::NoRegister) {
11133       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11134       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11135         unsigned RegNo = FReg - RISCV::F0_F;
11136         unsigned DReg = RISCV::F0_D + RegNo;
11137         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11138       }
11139       if (VT == MVT::f32 || VT == MVT::Other)
11140         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11141       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11142         unsigned RegNo = FReg - RISCV::F0_F;
11143         unsigned HReg = RISCV::F0_H + RegNo;
11144         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11145       }
11146     }
11147   }
11148 
11149   if (Subtarget.hasVInstructions()) {
11150     Register VReg = StringSwitch<Register>(Constraint.lower())
11151                         .Case("{v0}", RISCV::V0)
11152                         .Case("{v1}", RISCV::V1)
11153                         .Case("{v2}", RISCV::V2)
11154                         .Case("{v3}", RISCV::V3)
11155                         .Case("{v4}", RISCV::V4)
11156                         .Case("{v5}", RISCV::V5)
11157                         .Case("{v6}", RISCV::V6)
11158                         .Case("{v7}", RISCV::V7)
11159                         .Case("{v8}", RISCV::V8)
11160                         .Case("{v9}", RISCV::V9)
11161                         .Case("{v10}", RISCV::V10)
11162                         .Case("{v11}", RISCV::V11)
11163                         .Case("{v12}", RISCV::V12)
11164                         .Case("{v13}", RISCV::V13)
11165                         .Case("{v14}", RISCV::V14)
11166                         .Case("{v15}", RISCV::V15)
11167                         .Case("{v16}", RISCV::V16)
11168                         .Case("{v17}", RISCV::V17)
11169                         .Case("{v18}", RISCV::V18)
11170                         .Case("{v19}", RISCV::V19)
11171                         .Case("{v20}", RISCV::V20)
11172                         .Case("{v21}", RISCV::V21)
11173                         .Case("{v22}", RISCV::V22)
11174                         .Case("{v23}", RISCV::V23)
11175                         .Case("{v24}", RISCV::V24)
11176                         .Case("{v25}", RISCV::V25)
11177                         .Case("{v26}", RISCV::V26)
11178                         .Case("{v27}", RISCV::V27)
11179                         .Case("{v28}", RISCV::V28)
11180                         .Case("{v29}", RISCV::V29)
11181                         .Case("{v30}", RISCV::V30)
11182                         .Case("{v31}", RISCV::V31)
11183                         .Default(RISCV::NoRegister);
11184     if (VReg != RISCV::NoRegister) {
11185       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11186         return std::make_pair(VReg, &RISCV::VMRegClass);
11187       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11188         return std::make_pair(VReg, &RISCV::VRRegClass);
11189       for (const auto *RC :
11190            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11191         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11192           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11193           return std::make_pair(VReg, RC);
11194         }
11195       }
11196     }
11197   }
11198 
11199   std::pair<Register, const TargetRegisterClass *> Res =
11200       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11201 
11202   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11203   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11204   // Subtarget into account.
11205   if (Res.second == &RISCV::GPRF16RegClass ||
11206       Res.second == &RISCV::GPRF32RegClass ||
11207       Res.second == &RISCV::GPRF64RegClass)
11208     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11209 
11210   return Res;
11211 }
11212 
11213 unsigned
11214 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11215   // Currently only support length 1 constraints.
11216   if (ConstraintCode.size() == 1) {
11217     switch (ConstraintCode[0]) {
11218     case 'A':
11219       return InlineAsm::Constraint_A;
11220     default:
11221       break;
11222     }
11223   }
11224 
11225   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11226 }
11227 
11228 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11229     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11230     SelectionDAG &DAG) const {
11231   // Currently only support length 1 constraints.
11232   if (Constraint.length() == 1) {
11233     switch (Constraint[0]) {
11234     case 'I':
11235       // Validate & create a 12-bit signed immediate operand.
11236       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11237         uint64_t CVal = C->getSExtValue();
11238         if (isInt<12>(CVal))
11239           Ops.push_back(
11240               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11241       }
11242       return;
11243     case 'J':
11244       // Validate & create an integer zero operand.
11245       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11246         if (C->getZExtValue() == 0)
11247           Ops.push_back(
11248               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11249       return;
11250     case 'K':
11251       // Validate & create a 5-bit unsigned immediate operand.
11252       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11253         uint64_t CVal = C->getZExtValue();
11254         if (isUInt<5>(CVal))
11255           Ops.push_back(
11256               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11257       }
11258       return;
11259     case 'S':
11260       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11261         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11262                                                  GA->getValueType(0)));
11263       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11264         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11265                                                 BA->getValueType(0)));
11266       }
11267       return;
11268     default:
11269       break;
11270     }
11271   }
11272   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11273 }
11274 
11275 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11276                                                    Instruction *Inst,
11277                                                    AtomicOrdering Ord) const {
11278   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11279     return Builder.CreateFence(Ord);
11280   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11281     return Builder.CreateFence(AtomicOrdering::Release);
11282   return nullptr;
11283 }
11284 
11285 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11286                                                     Instruction *Inst,
11287                                                     AtomicOrdering Ord) const {
11288   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11289     return Builder.CreateFence(AtomicOrdering::Acquire);
11290   return nullptr;
11291 }
11292 
11293 TargetLowering::AtomicExpansionKind
11294 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11295   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11296   // point operations can't be used in an lr/sc sequence without breaking the
11297   // forward-progress guarantee.
11298   if (AI->isFloatingPointOperation())
11299     return AtomicExpansionKind::CmpXChg;
11300 
11301   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11302   if (Size == 8 || Size == 16)
11303     return AtomicExpansionKind::MaskedIntrinsic;
11304   return AtomicExpansionKind::None;
11305 }
11306 
11307 static Intrinsic::ID
11308 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11309   if (XLen == 32) {
11310     switch (BinOp) {
11311     default:
11312       llvm_unreachable("Unexpected AtomicRMW BinOp");
11313     case AtomicRMWInst::Xchg:
11314       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11315     case AtomicRMWInst::Add:
11316       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11317     case AtomicRMWInst::Sub:
11318       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11319     case AtomicRMWInst::Nand:
11320       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11321     case AtomicRMWInst::Max:
11322       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11323     case AtomicRMWInst::Min:
11324       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11325     case AtomicRMWInst::UMax:
11326       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11327     case AtomicRMWInst::UMin:
11328       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11329     }
11330   }
11331 
11332   if (XLen == 64) {
11333     switch (BinOp) {
11334     default:
11335       llvm_unreachable("Unexpected AtomicRMW BinOp");
11336     case AtomicRMWInst::Xchg:
11337       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11338     case AtomicRMWInst::Add:
11339       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11340     case AtomicRMWInst::Sub:
11341       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11342     case AtomicRMWInst::Nand:
11343       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11344     case AtomicRMWInst::Max:
11345       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11346     case AtomicRMWInst::Min:
11347       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11348     case AtomicRMWInst::UMax:
11349       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11350     case AtomicRMWInst::UMin:
11351       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11352     }
11353   }
11354 
11355   llvm_unreachable("Unexpected XLen\n");
11356 }
11357 
11358 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11359     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11360     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11361   unsigned XLen = Subtarget.getXLen();
11362   Value *Ordering =
11363       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11364   Type *Tys[] = {AlignedAddr->getType()};
11365   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11366       AI->getModule(),
11367       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11368 
11369   if (XLen == 64) {
11370     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11371     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11372     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11373   }
11374 
11375   Value *Result;
11376 
11377   // Must pass the shift amount needed to sign extend the loaded value prior
11378   // to performing a signed comparison for min/max. ShiftAmt is the number of
11379   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11380   // is the number of bits to left+right shift the value in order to
11381   // sign-extend.
11382   if (AI->getOperation() == AtomicRMWInst::Min ||
11383       AI->getOperation() == AtomicRMWInst::Max) {
11384     const DataLayout &DL = AI->getModule()->getDataLayout();
11385     unsigned ValWidth =
11386         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11387     Value *SextShamt =
11388         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11389     Result = Builder.CreateCall(LrwOpScwLoop,
11390                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11391   } else {
11392     Result =
11393         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11394   }
11395 
11396   if (XLen == 64)
11397     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11398   return Result;
11399 }
11400 
11401 TargetLowering::AtomicExpansionKind
11402 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11403     AtomicCmpXchgInst *CI) const {
11404   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11405   if (Size == 8 || Size == 16)
11406     return AtomicExpansionKind::MaskedIntrinsic;
11407   return AtomicExpansionKind::None;
11408 }
11409 
11410 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11411     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11412     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11413   unsigned XLen = Subtarget.getXLen();
11414   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11415   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11416   if (XLen == 64) {
11417     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11418     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11419     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11420     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11421   }
11422   Type *Tys[] = {AlignedAddr->getType()};
11423   Function *MaskedCmpXchg =
11424       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11425   Value *Result = Builder.CreateCall(
11426       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11427   if (XLen == 64)
11428     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11429   return Result;
11430 }
11431 
11432 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11433   return false;
11434 }
11435 
11436 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11437                                                EVT VT) const {
11438   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11439     return false;
11440 
11441   switch (FPVT.getSimpleVT().SimpleTy) {
11442   case MVT::f16:
11443     return Subtarget.hasStdExtZfh();
11444   case MVT::f32:
11445     return Subtarget.hasStdExtF();
11446   case MVT::f64:
11447     return Subtarget.hasStdExtD();
11448   default:
11449     return false;
11450   }
11451 }
11452 
11453 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11454   // If we are using the small code model, we can reduce size of jump table
11455   // entry to 4 bytes.
11456   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11457       getTargetMachine().getCodeModel() == CodeModel::Small) {
11458     return MachineJumpTableInfo::EK_Custom32;
11459   }
11460   return TargetLowering::getJumpTableEncoding();
11461 }
11462 
11463 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11464     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11465     unsigned uid, MCContext &Ctx) const {
11466   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11467          getTargetMachine().getCodeModel() == CodeModel::Small);
11468   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11469 }
11470 
11471 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11472                                                      EVT VT) const {
11473   VT = VT.getScalarType();
11474 
11475   if (!VT.isSimple())
11476     return false;
11477 
11478   switch (VT.getSimpleVT().SimpleTy) {
11479   case MVT::f16:
11480     return Subtarget.hasStdExtZfh();
11481   case MVT::f32:
11482     return Subtarget.hasStdExtF();
11483   case MVT::f64:
11484     return Subtarget.hasStdExtD();
11485   default:
11486     break;
11487   }
11488 
11489   return false;
11490 }
11491 
11492 Register RISCVTargetLowering::getExceptionPointerRegister(
11493     const Constant *PersonalityFn) const {
11494   return RISCV::X10;
11495 }
11496 
11497 Register RISCVTargetLowering::getExceptionSelectorRegister(
11498     const Constant *PersonalityFn) const {
11499   return RISCV::X11;
11500 }
11501 
11502 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11503   // Return false to suppress the unnecessary extensions if the LibCall
11504   // arguments or return value is f32 type for LP64 ABI.
11505   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11506   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11507     return false;
11508 
11509   return true;
11510 }
11511 
11512 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11513   if (Subtarget.is64Bit() && Type == MVT::i32)
11514     return true;
11515 
11516   return IsSigned;
11517 }
11518 
11519 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11520                                                  SDValue C) const {
11521   // Check integral scalar types.
11522   if (VT.isScalarInteger()) {
11523     // Omit the optimization if the sub target has the M extension and the data
11524     // size exceeds XLen.
11525     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11526       return false;
11527     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11528       // Break the MUL to a SLLI and an ADD/SUB.
11529       const APInt &Imm = ConstNode->getAPIntValue();
11530       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11531           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11532         return true;
11533       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11534       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11535           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11536            (Imm - 8).isPowerOf2()))
11537         return true;
11538       // Omit the following optimization if the sub target has the M extension
11539       // and the data size >= XLen.
11540       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11541         return false;
11542       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11543       // a pair of LUI/ADDI.
11544       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11545         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11546         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11547             (1 - ImmS).isPowerOf2())
11548         return true;
11549       }
11550     }
11551   }
11552 
11553   return false;
11554 }
11555 
11556 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11557                                                       SDValue ConstNode) const {
11558   // Let the DAGCombiner decide for vectors.
11559   EVT VT = AddNode.getValueType();
11560   if (VT.isVector())
11561     return true;
11562 
11563   // Let the DAGCombiner decide for larger types.
11564   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11565     return true;
11566 
11567   // It is worse if c1 is simm12 while c1*c2 is not.
11568   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11569   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11570   const APInt &C1 = C1Node->getAPIntValue();
11571   const APInt &C2 = C2Node->getAPIntValue();
11572   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11573     return false;
11574 
11575   // Default to true and let the DAGCombiner decide.
11576   return true;
11577 }
11578 
11579 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11580     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11581     bool *Fast) const {
11582   if (!VT.isVector())
11583     return false;
11584 
11585   EVT ElemVT = VT.getVectorElementType();
11586   if (Alignment >= ElemVT.getStoreSize()) {
11587     if (Fast)
11588       *Fast = true;
11589     return true;
11590   }
11591 
11592   return false;
11593 }
11594 
11595 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11596     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11597     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11598   bool IsABIRegCopy = CC.hasValue();
11599   EVT ValueVT = Val.getValueType();
11600   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11601     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11602     // and cast to f32.
11603     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11604     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11605     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11606                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11607     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11608     Parts[0] = Val;
11609     return true;
11610   }
11611 
11612   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11613     LLVMContext &Context = *DAG.getContext();
11614     EVT ValueEltVT = ValueVT.getVectorElementType();
11615     EVT PartEltVT = PartVT.getVectorElementType();
11616     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11617     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11618     if (PartVTBitSize % ValueVTBitSize == 0) {
11619       assert(PartVTBitSize >= ValueVTBitSize);
11620       // If the element types are different, bitcast to the same element type of
11621       // PartVT first.
11622       // Give an example here, we want copy a <vscale x 1 x i8> value to
11623       // <vscale x 4 x i16>.
11624       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11625       // subvector, then we can bitcast to <vscale x 4 x i16>.
11626       if (ValueEltVT != PartEltVT) {
11627         if (PartVTBitSize > ValueVTBitSize) {
11628           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11629           assert(Count != 0 && "The number of element should not be zero.");
11630           EVT SameEltTypeVT =
11631               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11632           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11633                             DAG.getUNDEF(SameEltTypeVT), Val,
11634                             DAG.getVectorIdxConstant(0, DL));
11635         }
11636         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11637       } else {
11638         Val =
11639             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11640                         Val, DAG.getVectorIdxConstant(0, DL));
11641       }
11642       Parts[0] = Val;
11643       return true;
11644     }
11645   }
11646   return false;
11647 }
11648 
11649 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11650     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11651     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11652   bool IsABIRegCopy = CC.hasValue();
11653   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11654     SDValue Val = Parts[0];
11655 
11656     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11657     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11658     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11659     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11660     return Val;
11661   }
11662 
11663   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11664     LLVMContext &Context = *DAG.getContext();
11665     SDValue Val = Parts[0];
11666     EVT ValueEltVT = ValueVT.getVectorElementType();
11667     EVT PartEltVT = PartVT.getVectorElementType();
11668     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11669     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11670     if (PartVTBitSize % ValueVTBitSize == 0) {
11671       assert(PartVTBitSize >= ValueVTBitSize);
11672       EVT SameEltTypeVT = ValueVT;
11673       // If the element types are different, convert it to the same element type
11674       // of PartVT.
11675       // Give an example here, we want copy a <vscale x 1 x i8> value from
11676       // <vscale x 4 x i16>.
11677       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11678       // then we can extract <vscale x 1 x i8>.
11679       if (ValueEltVT != PartEltVT) {
11680         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11681         assert(Count != 0 && "The number of element should not be zero.");
11682         SameEltTypeVT =
11683             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11684         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11685       }
11686       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11687                         DAG.getVectorIdxConstant(0, DL));
11688       return Val;
11689     }
11690   }
11691   return SDValue();
11692 }
11693 
11694 SDValue
11695 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11696                                    SelectionDAG &DAG,
11697                                    SmallVectorImpl<SDNode *> &Created) const {
11698   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11699   if (isIntDivCheap(N->getValueType(0), Attr))
11700     return SDValue(N, 0); // Lower SDIV as SDIV
11701 
11702   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11703          "Unexpected divisor!");
11704 
11705   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11706   if (!Subtarget.hasStdExtZbt())
11707     return SDValue();
11708 
11709   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11710   // Besides, more critical path instructions will be generated when dividing
11711   // by 2. So we keep using the original DAGs for these cases.
11712   unsigned Lg2 = Divisor.countTrailingZeros();
11713   if (Lg2 == 1 || Lg2 >= 12)
11714     return SDValue();
11715 
11716   // fold (sdiv X, pow2)
11717   EVT VT = N->getValueType(0);
11718   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11719     return SDValue();
11720 
11721   SDLoc DL(N);
11722   SDValue N0 = N->getOperand(0);
11723   SDValue Zero = DAG.getConstant(0, DL, VT);
11724   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11725 
11726   // Add (N0 < 0) ? Pow2 - 1 : 0;
11727   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11728   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11729   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11730 
11731   Created.push_back(Cmp.getNode());
11732   Created.push_back(Add.getNode());
11733   Created.push_back(Sel.getNode());
11734 
11735   // Divide by pow2.
11736   SDValue SRA =
11737       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11738 
11739   // If we're dividing by a positive value, we're done.  Otherwise, we must
11740   // negate the result.
11741   if (Divisor.isNonNegative())
11742     return SRA;
11743 
11744   Created.push_back(SRA.getNode());
11745   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11746 }
11747 
11748 #define GET_REGISTER_MATCHER
11749 #include "RISCVGenAsmMatcher.inc"
11750 
11751 Register
11752 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11753                                        const MachineFunction &MF) const {
11754   Register Reg = MatchRegisterAltName(RegName);
11755   if (Reg == RISCV::NoRegister)
11756     Reg = MatchRegisterName(RegName);
11757   if (Reg == RISCV::NoRegister)
11758     report_fatal_error(
11759         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11760   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11761   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11762     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11763                              StringRef(RegName) + "\"."));
11764   return Reg;
11765 }
11766 
11767 namespace llvm {
11768 namespace RISCVVIntrinsicsTable {
11769 
11770 #define GET_RISCVVIntrinsicsTable_IMPL
11771 #include "RISCVGenSearchableTables.inc"
11772 
11773 } // namespace RISCVVIntrinsicsTable
11774 
11775 } // namespace llvm
11776